<?php

/**
 * @author darkredz
 */
class ReceiptAjaxController extends DooController {
	public $staff;
	public $verifyId;
	public $executeId;
	
	// public static $NEW2 = 0;
	public $AGENCY = "日常相关费用";
	public $TRAVEL = "差旅相关费用";
	public $TRAIN = "培训班费用";
	public $OTHER = "其他";
	private $MYREVEIPTCACHEPATH = "protected/cache/myReceipt/";
	private $PERSONALCOLLECTCACHEPATH = "protected/cache/personalCollect/";
	private $CATEGORYCOLLECTPATH = "protected/cache/categoryCollect/";
	private $STAFFCOLLECTPATH = "protected/cache/staffCollect/";
	
	public function beforeRun($resource, $action) {
		Doo::loadClass ( 'XDeode' );
		$XDeode = new XDeode ( 5 );
		$sid = $XDeode->decode ( $_COOKIE ["staff"] );
		// 单独判断公司汇总的访问权限
		if ($action == 'companyCategoryCollect') {
			Doo::loadModel ( "receiptAuthorityManage" );
			$invoiceCompanyManage = new receiptAuthorityManage ();
			
			$icm = $invoiceCompanyManage->getInvoiceCMByStaff ( $sid );
			if (empty ( $icm ))
				die ( 'illegal request' );
		}
		
		Doo::loadModel ( 'staff' );
		$staff = new staff ();
		$detail = $staff->getStaffBySid ( $_COOKIE ["staff"] );
		
		$accessModular = 'RECEIPTSAJAX';//是否已经开放的方法
		$accessAuthority = 'RECEIPTS';//容许访问的权限
		if (empty ( $detail ['cldAccessArray'] ))
			die ( 'illegal request' );
		else {
			if (in_array ( $accessAuthority, $detail ['cldAccessArray'] )) {
				if (Doo::acl ()->isAllowed ( $accessModular, $resource, $action )) {
					$flag = true;
				} else {
					$flag = false;
				}
			} else {
				die ( 'illegal request' );
			}
		}
		if (! $flag)
			die ( 'illegal request' );
	}
	function __construct() {
		if (isset ( $_COOKIE ["staff"] )) {
			
			if (! empty ( $_COOKIE ["staff"] )) {
				
				Doo::loadModel ( 'staff' );
				Doo::loadModel ( 'verify' );
				$verify = new verify ();
				$staff = new staff ();
				Doo::loadModel ( "execute" );
				$execute = new execute ();
				
				$verifyList = $verify->find ( array (
						'select' => 'staff',
						'asArray' => true 
				) );
				$list = array ();
				
				// 判断角色的审批权限
				foreach ( $verifyList as $key => $value ) {
					$ver = json_decode ( $value ['staff'] );
					
					foreach ( $ver as $k => $v ) {
						if ($v [1] == 'ROLE') {
							$roleList = json_decode ( $v [3] );
							foreach ( $roleList as $t => $g ) {
								$gList = explode ( "_", $g );
								array_push ( $list, $gList [0] );
								// print_r($list);
							}
						} else
							array_push ( $list, $v [0] );
					}
				}
				
				// 判断执行人的审批权限
				$executeList = $execute->find ( array (
						'select' => 'staff',
						'asArray' => true 
				) );
				$list2 = array ();
				foreach ( $executeList as $key => $value ) {
					$ver = json_decode ( $value ['staff'] );
					
					foreach ( $ver as $k => $v ) {
						array_push ( $list2, $v [0] );
					}
				}
				
				$eidList = file_get_contents ( "protected/config/execute/execute.ini" );
				$eidList = array_filter ( explode ( ",", $eidList ) );
				
				$this->executeId = array_merge ( $list2, $eidList );
				
				$this->verifyId = $list;
				$this->staff = $staff->getUserByIdList ( $_COOKIE ["staff"] )[0];
				
				// 检测用户信息完成
				$this->data ['isStaffCompleteMsg'] = false;
				$detail = $staff->checkStaffInfoIsComplete ( $_COOKIE ["staff"] );
				if (! empty ( $detail ))
					$this->data ['isStaffCompleteMsg'] = true;
				
				return "/";
			}
		}
		
		Doo::loadCore ( 'uri/DooUriRouter' );
		$router = new DooUriRouter ();
		$routeRs = $router->execute ( Doo::app ()->route, Doo::conf ()->SUBFOLDER );
		
		if ($routeRs ['1'] != "login") {
			header ( 'Content-Type:text/html;charset=utf-8' );
			@header ( "Location: /login" );
		}
	}
	
	/**
	 * 默认获得属于自己和所在办事处10条最新的数据
	 */
	function ajaxGetReceiptTrainLoan(){
		$sid = $this->get_args ( 'sid' ) ? $this->get_args ( 'sid' ) : $this->staff['sid'];
		$cid = $this->get_args ( 'cid' ) ? $this->get_args ( 'cid' ) : $this->staff['cid'];
		$limit = $this->get_args ( 'limit' ) ? $this->get_args ( 'limit' ) : '30';
		$status=8;
		Doo::loadModel ( 'receipt' );
		$receipt = new receipt ();
		
		$list=$receipt->getReceiptLoanByStatus($sid,$cid,$status,$limit);
		
		echo json_encode ( array (
				'status' => 1,
				'receiptLoanList' => $list
		) );
	}
	
	/**
	 * 获得费用详情
	 */
	function ajaxGetReceiptDetailByJson() {
		$ridKey = $this->get_args ( 'ridKey' ) ? $this->get_args ( 'ridKey' ) : "";
	
		Doo::loadClass ( 'XDeode' );
		$XDeode = new XDeode ( 5 );
		$rid = $XDeode->decode ( $ridKey );
	
		Doo::loadModel ( 'receipt' );
		$receipt = new receipt ();
	
		$detail = $receipt->getReceiptByRid ( $rid );
	
		echo json_encode ( array (
				'status' => 1,
				'detail' => $detail
		) );
	}
	
	/**
	 * 更新费用的汇款金额
	 */
	function ajaxSetRceiptAmountByRid(){
		$amount = $this->get_args ( 'amount' ) && is_numeric ( $this->get_args ( 'amount' ) ) ? $this->get_args ( 'amount' ) : 0;
		$ridKey = $this->get_args ( 'ridKey' ) ? $this->get_args ( 'ridKey' ) : '';
		
		if (empty($ridKey)||empty($amount)){
			echo json_encode ( array (
					'status' => 2
			) );
			die;
		}
		
		Doo::loadClass ( 'XDeode' );
		$XDeode = new XDeode ( 5 );
		$rid = $XDeode->decode ( $ridKey );
		Doo::loadModel ( 'receipt' );
		$receipt = new receipt ();
		$detail=$receipt->getReceiptByRid($rid);
		
		if (empty($detail)){
			echo json_encode ( array (
					'status' => 2
			) );
			die;
		}
		if ($detail['status']!=2){
			echo json_encode ( array (
					'status' => 2
			) );
			die;
		}
		$receipt = new receipt ();
		$receipt->amount = $amount;
		$receipt->update ( array (
				'where' => ' rid = ' . $rid
		) );
		echo json_encode ( array (
				'status' => 1
		) );
	}
	
	function setWXMsg($rid, $type) {
		Doo::loadModel ( "receipt" );
		$receipt = new receipt ();
		$receiptDetail = $receipt->getOne ( array (
				'where' => 'rid=' . $rid,
				'asArray' => true 
		) );
		if (! empty ( $receiptDetail )) {
			Doo::loadModel ( 'staff' );
			$staff = new staff ();
			$staffmsg = $staff->getOne ( array (
					'where' => "sid='" . $receiptDetail ['staff'] . "'",
					'asArray' => TRUE 
			) );
			if (! empty ( $staffmsg ['wxid'] )) {
				require_once (SITE_PATH . '/protected/class/client.php');
				$client = new client ( 'http://m.cld.smartcost.com.cn/' );
				$user = $staffmsg ['wxid'];
				$receiptName = '';
				$msg = '';
				switch ($receiptDetail ['Rtype']) {
					case 0 :
						$receiptName = '报销';
						break;
					case 1 :
						$receiptName = '借款';
						break;
					case 2 :
						$receiptName = '对公汇款';
						break;
				}
				switch ($type) {
					case 1 :
						$msg = '太好了，您的' . $receiptName . ' ' . $receiptDetail ['receiptOrder'] . '，￥' . $receiptDetail ['sum'] . '，已同意支付。';
						break;
					case 2 :
						$msg = '注意，您的' . $receiptName . ' ' . $receiptDetail ['receiptOrder'] . '，￥' . $receiptDetail ['sum'] . '，已被撤回，请及时处理。';
						break;
					case 3 :
						$msg = '很遗憾，您的' . $receiptName . ' ' . $receiptDetail ['receiptOrder'] . '，￥' . $receiptDetail ['sum'] . '，已被终止。';
						break;
				}
				
				// $result = $client->SendMsg ( $user, $msg, 'text' );
			}
		}
	}
	
	// Email发送函数
	function SMail($toemail, $subject, $contents) {
		Doo::loadClass ( 'class.phpmailer' );
		$mail = new PHPMailer ();
		$mail->From = "postmaster@support.zhzdwk.com"; // 发送邮箱全名
		$mail->FromName = "=?UTF-8?B?" . base64_encode ( "CLD" ) . "?="; // 发送人昵称
		$mail->Username = "postmaster@websupport.sendcloud.org"; // 用户名
		$mail->Password = "cDO1GjtY1seH"; // 密码
		$mail->CharSet = "UTF8";
		$mail->SMTPAuth = true;
		$mail->Host = "smtpcloud.sohu.com"; // 邮件主机的smtp地址
		$mail->Mailer = "smtp";
		$mail->Port = 25;
		$mail->Subject = "=?UTF-8?B?" . base64_encode ( $subject ) . "?=";
		$mail->MsgHTML ( $contents );
		$mail->AddAddress ( $toemail );
		$mail->CharSet = "UTF-8";
		return $mail->Send ();
	}
	function swfupload() {
		$POST_MAX_SIZE = ini_get ( 'post_max_size' );
		$unit = strtoupper ( substr ( $POST_MAX_SIZE, - 1 ) );
		$multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));
		
		if (( int ) $_SERVER ['CONTENT_LENGTH'] > $multiplier * ( int ) $POST_MAX_SIZE && $POST_MAX_SIZE) {
			header ( "HTTP/1.1 500 Internal Server Error" );
			echo "POST exceeded maximum allowed size.";
			exit ( 0 );
		}
		
		// Settings
		$save_path = DOO::conf ()->SITE_PATH . "upload/swfupload/"; // The path were we will save the file (getcwd() may not be reliable and should be tested in your environment)
		$upload_name = "Filedata";
		$max_file_size_in_bytes = 2147483647; // 2GB in bytes
		$extension_whitelist = array (
				"doc",
				"txt",
				"jpg",
				"gif",
				"png" 
		); // Allowed file extensions
		$valid_chars_regex = '.A-Z0-9_ !@#$%^&()+={}\[\]\',~`-'; // Characters allowed in the file name (in a Regular Expression format)
		                                                         
		// Other variables
		$MAX_FILENAME_LENGTH = 260;
		$file_name = "";
		$file_extension = "";
		$uploadErrors = array (
				0 => "文件上传成功",
				1 => "上传的文件超过了 php.ini 文件中的 upload_max_filesize directive 里的设置",
				2 => "上传的文件超过了 HTML form 文件中的 MAX_FILE_SIZE directive 里的设置",
				3 => "上传的文件仅为部分文件",
				4 => "没有文件上传",
				6 => "缺少临时文件夹" 
		);
		
		$nk = time ();
		$file_name = $nk . '.' . $this->_GetFileEXT ( $_FILES [$upload_name] ['name'] ); // preg_replace('/[^'.$valid_chars_regex.']|\.+$/i', "", basename($_FILES[$upload_name]['name']));
		
		if (! @move_uploaded_file ( $_FILES [$upload_name] ["tmp_name"], $save_path . $file_name )) {
			echo "文件无法保存.";
			exit ( 0 );
		}
		
		// Return output to the browser (only supported by SWFUpload for Flash Player 9)
		
		echo json_encode ( array (
				'filename' => $file_name,
				'id' => $nk 
		) );
		exit ( 0 );
	}
	function _GetFileEXT($filename) {
		$pics = explode ( '.', $filename );
		
		$num = count ( $pics );
		
		return $pics [$num - 1];
	}
	
	/**
	 * 获取get或者POST值
	 * @param string $name 属性名称
	 * @return fixed 值
	 */
	function get_args($name) {
		if (isset ( $_GET [$name] )) {
			if (is_array ( $_GET [$name] ))
				return $_GET [$name];
			else
				return addslashes ( $_GET [$name] );
		} elseif (isset ( $_POST [$name] )) {
			if (is_array ( $_POST [$name] ))
				return $_POST [$name];
			else
				return addslashes ( $_POST [$name] );
		} else
			return false;
	}
	function num_to_rmb($num) {
		$c1 = "零壹贰叁肆伍陆柒捌玖";
		$c2 = "分角元拾佰仟万拾佰仟亿";
		// 精确到分后面就不要了，所以只留两个小数位
		$num = round ( $num, 2 );
		// 将数字转化为整数
		$num = $num * 100;
		if (strlen ( $num ) > 10) {
			return "金额太大，请检查";
		}
		$i = 0;
		$c = "";
		while ( 1 ) {
			if ($i == 0) {
				// 获取最后一位数字
				$n = substr ( $num, strlen ( $num ) - 1, 1 );
			} else {
				$n = $num % 10;
			}
			// 每次将最后一位数字转化为中文
			$p1 = substr ( $c1, 3 * $n, 3 );
			$p2 = substr ( $c2, 3 * $i, 3 );
			
			if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {
				$c = $p1 . $p2 . $c;
			} else {
				$c = $p1 . $c;
			}
			$i = $i + 1;
			// 去掉数字最后一位了
			
			$num = $num / 10;
			// echo $num.'</br>';
			$num = ( int ) $num;
			// $num =floor($num);
			// $num = round ( $num, 0, PHP_ROUND_HALF_DOWN );
			// echo $num.'</br>';
			// 结束循环
			if ($num == 0) {
				break;
			}
		}
		// echo $c.'</br>';
		$j = 0;
		$slen = strlen ( $c );
		while ( $j < $slen ) {
			// utf8一个汉字相当3个字符
			$m = substr ( $c, $j, 6 );
			// 处理数字中很多0的情况,每次循环去掉一个汉字“零”
			if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {
				$left = substr ( $c, 0, $j );
				$right = substr ( $c, $j + 3 );
				$c = $left . $right;
				$j = $j - 3;
				$slen = $slen - 3;
			}
			$j = $j + 3;
		}
		// 这个是为了去掉类似23.0中最后一个“零”字
		if (substr ( $c, strlen ( $c ) - 3, 3 ) == '零') {
			$c = substr ( $c, 0, strlen ( $c ) - 3 );
		}
		// 将处理的汉字加上“整”
		if (empty ( $c )) {
			return "零元整";
		} else {
			return $c . "整";
		}
	}
	
	/**
	 * 获得分页数据
	 * @param unknown_type $table
	 * @param unknown_type $condition
	 * @param unknown_type $on_page
	 * @param unknown_type $page_size
	 */
	function get_page($table = "", $condition = "", $on_page = 1, $page_size = 20, $action = "", $get = "", $other = "page") {
		$page_c = "";
		$page ['previous'] = $this->get_previous ( $on_page );
		$page ['on_page'] = $on_page;
		$total_count = $this->get_table_count ( $table, $condition );
		$total = intval ( $total_count / $page_size );
		
		$page ['total_page'] = ($total_count % $page_size) == 0 ? $total : $total + 1;
		$page ['total_data'] = $total_count;
		$page ['next'] = $on_page == $page ['total_page'] ? $page ['total_page'] : $on_page + 1;
		
		$i = 1;
		$page_max = 1;
		$page_width = 3;
		
		if ($on_page >= $page_width) {
			$page_max = intval ( $on_page / $page_width ) + 1;
			$i = intval ( $on_page / $page_width ) * $page_width - 1;
		}
		
		for(; $i <= $page ['total_page']; $i ++) {
			if ($i == $on_page)
				$page_c .= '<li class="active"><a href="javascript:void(0)">' . $i . '</a></li>';
			else
				$page_c .= '<li><a href="/' . $action . '/' . $i . $get . '">' . $i . '</a></li>';
			
			if ($i == ($page_width * $page_max))
				break;
		}
		
		$page ['page'] = $page_c;
		$page ['lower'] = (-- $on_page) * $page_size;
		return $page;
	}
	
	/**
	 * 获取总页数
	 * @param unknown_type $table
	 * @param unknown_type $condition
	 */
	public function get_table_count($table = "", $condition = "") {
		// $sql = "select count(*) as count from " . $table . " where 1 " . $condition;
		$sql = "select count(*) as count from " . $table . " where 1 " . $condition;
		
		// echo $sql;die;
		$query = Doo::db ()->query ( $sql );
		$result = $query->fetch ();
		return $result ['count'];
	}
	/**
	 * 获取上一页
	 * @param unknown_type $on_page
	 */
	function get_previous($on_page = 1) {
		return $on_page != 0 ? $on_page - 1 : $on_page;
	}
}

?>