<?php

/**
 * 开票功能控制器
 * @author CP
 * @version 1.0
 * @namespace invoice
 * @package InvoiceExtentController
 */
class InvoiceExtendController extends DooController {
	public $staff;
	public $NEW;
	public $data;
	private $INVOICEKEY = "APPROVAL";
	private $INVOICECOLLECTPATH = "protected/cache/invoiceCollect/";
	private $ACTION = '';
	private $appId = 'wx3ee46531947a1384';
	private $appSecret = 'awGWzy3J5q_96VXKBLA2BQ9RpiT0LiPXnkMF-xV6h5o'; // awGWzy3J5q_96VXKBLA2BXU6mVCGynPGD-sxUCsdNDE //'PeiQVH8tbQE7pM9pVO4AIPlX9FFNpwu7O6Iy6VFcAVtpjTA3Qn42dbNmktBFkUHo';
	public function beforeRun($resource, $action) {
		Doo::loadModel ( "invoiceManage" );
		$invoiceManage = new invoiceManage ();
		Doo::loadClass ( 'XDeode' );
		$XDeode = new XDeode ( 5 );
		$sid = $XDeode->decode ( $_COOKIE ["staff"] );
		header ( 'Content-Type:text/html;charset=utf-8' );
		$moldList = $invoiceManage->getInvoiceByStaff ( $sid );
		
		if (empty ( $moldList )) {
			$flag = false;
			$uGroups = 'ordinary';
			if (Doo::acl ()->isAllowed ( $uGroups, $resource, $action )) {
				$flag = true;
			}
		} else {
			$flag = false;
			array_push ( $moldList, array (
					'mold' => 'ordinary' 
			) );
			
			// 删除审批人后-加入权限问题-暂时关闭
			$fileInvoice = file_get_contents ( "protected/config/invoice/invoice.ini" );
			$fiML = json_decode ( $fileInvoice, true );
			if (empty ( $fiML ))
				$fiML = array ();
			foreach ( $fiML as $key => $value ) {
				$sidList = explode ( ',', $value );
				foreach ( $sidList as $k => $v ) {
					if ($v == $sid) {
						array_push ( $moldList, array (
								'mold' => $key 
						) );
						break;
					}
				}
			}
			
			foreach ( $moldList as $value ) {
				if (Doo::acl ()->isAllowed ( $value ['mold'], $resource, $action )) {
					$flag = true;
					break;
				}
			}
		}
		/*
		 * Doo::acl()->isAllowed($uGroups['groups'], $resource, $action);
		 */
		
		// 单独判断办事处汇总的访问权限 invoiceAggregateCategoryDetail,invoiceAggregateStaffDetail
		if ($action == 'invoiceAggregateCategoryDetail' || $action == 'invoiceAggregateStaffDetail') {
			Doo::loadModel ( "invoiceCategoryManage" );
			$invoiceCategoryManage = new invoiceCategoryManage ();
			
			$icm = $invoiceCategoryManage->getInvoiceCMByStaff ( $sid );
			if (empty ( $icm ))
				die ( 'illegal request' );
		}
		// 单独判断应收款访问权限
		if ($action == 'invoiceAggregateCompanyDetail') {
			Doo::loadModel ( "invoiceCompanyManage" );
			$invoiceCompanyManage = new invoiceCompanyManage ();
			
			$icm = $invoiceCompanyManage->getInvoiceCMByStaff ( $sid );
			if (empty ( $icm ))
				die ( 'illegal request' );
		}
		
		// 主权限获得与判断
		Doo::loadModel ( 'staff' );
		$staff = new staff ();
		$detail = $staff->getStaffBySid ( $_COOKIE ["staff"] );
		
		$accessModular = 'INVOICEEXTEND';
		$accessAuthority='INVOICE';
		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' );
				$staff = new staff ();
				
				$uriPartsOrig = explode ( '/', $_SERVER ['REQUEST_URI'] );
				$this->ACTION = $uriPartsOrig [1];
				$this->data ['new'] = $this->isInvoiceNew ();
				$this->staff = $staff->getUserByIdList ( $_COOKIE ["staff"] );
				
				$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" );
		}
	}
	function invoiceSettlementChange() {
		$iidKey = $this->get_args ( 'iidKey' ) ? $this->get_args ( 'iidKey' ) : "";
		$trainId = $this->get_args ( 'trainId' ) ? $this->get_args ( 'trainId' ) : 0;
		$settlementType = $this->get_args ( 'settlementType' ) ? $this->get_args ( 'settlementType' ) : "";
		
		if (empty ( $this->staff [0] )) {
			die ( 'illegal request-Please login' );
		}
		
		if (! empty ( $iidKey ) && ! empty ( $settlementType )) {
			Doo::loadModel ( 'invoice' );
			$invoice = new invoice ();
			Doo::loadClass ( 'XDeode' );
			$XDeode = new XDeode ( 5 );
			Doo::loadModel ( 'invoiceTraining' );
			$invoiceTraining = new invoiceTraining ();
			
			$iid = $XDeode->decode ( $iidKey );
			
			$invoiceDetail=$invoice->getInvoiceByIid($iid);
			if(empty($invoiceDetail)){
				die ( 'illegal request-invoiceData NULL' );
			}
			$trainId = $XDeode->decode ( $trainId );
			
			$itDetail=$invoiceTraining->getInvoiceTrainingByItid($trainId);
			
			$st = '';
			if ($settlementType == 'SOFTWARE') {
				$st = 0;
				$trainId = 0;
				$operation=' 结算方式 改 软件销售';
			} elseif ($settlementType == 'TRAINING') {
				$st = 1;
				$operation=' 结算方式 改 '.$itDetail['trainName'];
				if (empty ( $trainId ) && ! is_numeric ( $trainId )) {
					die ( 'illegal request-trainingIdError' );
				}
			} else {
				die ( 'illegal request-settlementError' );
			}
			
			$invoice->settlementType=$st;
			$invoice->trainId=$trainId;
			
			$invoice->update(array (
				'where' => 'iid = ' . $iid 
			));
			
			Doo::loadModel ( 'invoiceStore' );
			$invoiceStore = new invoiceStore ();
			
			//重置结算方式的相关数据 
			$isSuccess=$invoiceStore->delete ( array (
				'where' => 'iid=' . $iid,
				'limit' => 1 
			) );
			
// 			if($isSuccess){
// 				$detailIT = $invoiceTraining->getInvoiceTrainingByItid ( $invoiceDetail['trainId'] );
// 				if (!empty($detailIT)){
// 				$item = array (
// 						'itid' => $invoiceDetail['trainId'],
// 						'invoiceTotal' => $detailIT ['invoiceTotal'] - 1,
// 				);
// 				$itid = $invoiceTraining->setInvoiceTrainByCondition ( $item );
// 				}
// 			}
			
			
			// 如果是培训班结算 创建培训班发票到培训班备份中
			if (! empty ( $st ) && $st == 1) {
				$isid = $invoiceStore->setInvoiceToInvoiceStore ( $iid );
				$itemIS = array (
						'isid' => $isid,
						'ipSource' => 1,
						'apStatus' => 1,
						'iid' => $iid
				);
				$invoiceStore->setInvoiceStoreByCondition ( $itemIS );
			
				// 更新培训班总数量
				$item = array (
						'itid' => $trainId,
						'submitStatus' => 1
				);
				$itid = $invoiceTraining->setInvoiceTrainByCondition ( $item );
			}
			
			
			Doo::loadModel ( 'invoiceOperationLog' );
			$invoiceOperationLog = new invoiceOperationLog ();
			
			// 操作日志
			$invoiceOperationLog->setInvoiceOperationLog ( $item );
			$item = array (
					'date' => date ( "Y-m-d H:i:s" ),
					'operation' => $operation,
					'status' => 1,
					'img' => $this->staff [0] ['avatar'],
					'username' => $this->staff [0] ['username'],
					'uid' => $this->staff [0] ['sid'],
					'category' => $this->staff [0] ['category'],
					'iid' => $iid 
			);
			$invoiceOperationLog->setInvoiceOperationLog ( $item );
		}
		return "/invoiceApprovalAchieve";
	}

	function invoiceUntreadAdd(){
        session_start ();
        Doo::loadClass ( 'XDeode' );
        $XDeode = new XDeode ( 5 );

        $iidKey = isset ( $this->params ['iidKey'] ) ? $this->params ['iidKey'] : "";
        $iid = $XDeode->decode ( $iidKey );
        if (! is_numeric ( $iid ))
            die ( 'illegal request' );

        Doo::loadModel ( 'invoice' );
        $invoice = new invoice ();
        Doo::loadModel ( 'invoiceOperationLog' );
        $invoiceOperationLog = new invoiceOperationLog ();

        $invoiceDetail = $invoice->getInvoiceByIid ( $iid );
        $operation = $invoiceOperationLog->getInvoiceOperationByDropped ( $iid );
        //获得继承发票金额合计
        $restrictPrice=$invoiceDetail['invoicePrice'];
        if (!empty($invoiceDetail['inheritIid'])){
            $restrictList=$invoice->getInvoiceInIid($invoiceDetail['inheritIid']);
            foreach ($restrictList as $key=>$value){
                $restrictPrice-=$value['invoicePrice'];
            }
        }
        if ($restrictPrice<0){
            $restrictPrice=0;
        }

        $invoiceDetail ['mailItemsJson'] = json_decode ( $invoiceDetail ['mailItemsJson'], true );

        $token = $this->set_token ();
        $_SESSION ['token_' . $this->staff [0] ['sidKey']] = $token;
        $this->data ['token'] = $token;

        $this->data ['restrictPrice'] = floatval($restrictPrice);
        $this->data ['operation'] = $operation;
        $this->data ['invoiceDetail'] = $invoiceDetail;
        $this->data ['memu'] = "invoice";
        $this->data ['staff'] = $this->staff;
        $this->data ['receiptMemu'] = 'invoice';
        $this->render ( "/invoice/invoiceUntreadAdd", $this->data );
    }

    function invoiceUntreadAddDo(){

        $iidKey = $this->get_args ( 'iidKey' ) ? $this->get_args ( 'iidKey' ) : "";
        Doo::loadModel ( 'invoice' );
        $invoice = new invoice ();
        $iid = $invoice->authcode ( $iidKey );
        if (! empty ( $iid ) && ! is_numeric ( $iid ))
            die ( 'illegal request' );

        $cid = $this->get_args ( 'cid' ) && is_numeric ( $this->get_args ( 'cid' ) ) ? $this->get_args ( 'cid' ) : 0;
        $invoiceType = $this->get_args ( 'invoiceType' ) && is_numeric ( $this->get_args ( 'invoiceType' ) ) ? $this->get_args ( 'invoiceType' ) : 0;
        $doPost = $this->get_args ( 'doPost' ) && is_numeric ( $this->get_args ( 'doPost' ) ) ? $this->get_args ( 'doPost' ) : 0;
        // $invoicePrice = $this->get_args ( 'invoicePrice' ) ? $this->get_args ( 'invoicePrice' ) : "";

        $invoiceQuantity = $this->get_args ( 'invoiceQuantity' ) && is_numeric ( $this->get_args ( 'invoiceQuantity' ) ) ? $this->get_args ( 'invoiceQuantity' ) : 0;
        $invoiceUnitPrice = $this->get_args ( 'invoiceUnitPrice' ) && is_numeric ( $this->get_args ( 'invoiceUnitPrice' ) ) ? $this->get_args ( 'invoiceUnitPrice' ) : 0;

        $invoiceElement = $this->get_args ( 'invoiceElement' ) ? $this->get_args ( 'invoiceElement' ) : "";
        $invoiceTitle = $this->get_args ( 'invoiceTitle' ) ? $this->get_args ( 'invoiceTitle' ) : "";
        $invoiceCompany = $this->get_args ( 'invoiceCompany' ) ? $this->get_args ( 'invoiceCompany' ) : "";
        $TIN = $this->get_args ( 'TIN' ) ? $this->get_args ( 'TIN' ) : "";
        $address = $this->get_args ( 'address' ) ? $this->get_args ( 'address' ) : "";
        $phone = $this->get_args ( 'phone' ) ? $this->get_args ( 'phone' ) : "";
        $bank = $this->get_args ( 'bank' ) ? $this->get_args ( 'bank' ) : "";
        $bankAccount = $this->get_args ( 'bankAccount' ) ? $this->get_args ( 'bankAccount' ) : "";
        $recipients = $this->get_args ( 'recipients' ) ? $this->get_args ( 'recipients' ) : "";
        $recipientsPhone = $this->get_args ( 'recipientsPhone' ) ? $this->get_args ( 'recipientsPhone' ) : "";
        $recipientsAddress = $this->get_args ( 'recipientsAddress' ) ? $this->get_args ( 'recipientsAddress' ) : "";

        $remark = $this->get_args ( 'remark' ) ? $this->get_args ( 'remark' ) : "";

        $TINT = $this->get_args ( 'TINT' ) ? $this->get_args ( 'TINT' ) : "";
        $addressT = $this->get_args ( 'addressT' ) ? $this->get_args ( 'addressT' ) : "";
        $phoneT = $this->get_args ( 'phoneT' ) ? $this->get_args ( 'phoneT' ) : "";
        $bankT = $this->get_args ( 'bankT' ) ? $this->get_args ( 'bankT' ) : "";
        $bankAccountT = $this->get_args ( 'bankAccountT' ) ? $this->get_args ( 'bankAccountT' ) : "";

        $softLock = $this->get_args ( 'softLock' ) ? $this->get_args ( 'softLock' ) : 0;
        $softLockNum = $this->get_args ( 'softLockNum' ) ? $this->get_args ( 'softLockNum' ) : 0;
        $contract = $this->get_args ( 'contract' ) ? $this->get_args ( 'contract' ) : 0;
        $contractNum = $this->get_args ( 'contractNum' ) ? $this->get_args ( 'contractNum' ) : 0;
        $instructions = $this->get_args ( 'instructions' ) ? $this->get_args ( 'instructions' ) : 0;
        $instructionsNum = $this->get_args ( 'instructionsNum' ) ? $this->get_args ( 'instructionsNum' ) : 0;
        $remittance = $this->get_args ( 'remittance' ) ? $this->get_args ( 'remittance' ) : 0;

        $mailItems = $this->get_args ( 'mailItems' ) ? $this->get_args ( 'mailItems' ) : "";

        $token = $this->get_args ( 'token' ) ? $this->get_args ( 'token' ) : "";
        if (empty ( $token )) {
            die ( 'illegal request-token' );
        } else {
            session_start ();
            if ($_SESSION ['token_' . $this->staff [0] ['sidKey']] != $token) {
                header ( 'Content-Type:text/html;charset=utf-8' );
                die ( '请勿重复申请发票' );
            } else {
                $_SESSION ['token_' . $this->staff [0] ['sidKey']] = '';
            }
        }

        $temporary = $invoiceQuantity * $invoiceUnitPrice;
        if ($invoiceType == 1) {
            if ($temporary > 10000) {
                header ( 'Content-Type:text/html;charset=utf-8' );
                die ( '专用发票总金额暂时不能超过10000.00（一万）元。' );
                // die ( 'illegal request-Please priceError' );
            }
        }

        if (empty ( $this->staff [0] ))
            die ( 'illegal request-Please login' );

        if (! empty ( $cid ) && ! empty ( $invoiceQuantity ) && ! empty ( $invoiceUnitPrice ) && ! empty ( $invoiceElement ) ) {

            Doo::loadModel ( 'L_category' );
            $lCategory = new L_category ();
            Doo::loadModel ( 'invoiceManage' );
            $invoiceManage = new invoiceManage ();
            Doo::loadModel ( 'invoiceOperationLog' );
            $invoiceOperationLog = new invoiceOperationLog ();

            Doo::loadClass ( 'XDeode' );
            $XDeode = new XDeode ( 5 );


            $categoryDetil = $lCategory->getOne ( array (
                'SELECT' => 'title',
                'where' => 'cid=' . $cid,
                'asArray' => true
            ) );

            $invoicePrice = $invoiceQuantity * $invoiceUnitPrice;

            $invoiceManageList = $invoiceManage->getInvoiceByAll ();
            $invoiceManageDetail = $invoiceManage->getInvoiceByMold ( "发票审批" );
            // print_r(current($invoiceManageDetail ['staffList']));
            // die;

            $moldManage = array ();
            foreach ( $invoiceManageList as $key => $value ) {
                if ($value ['mold'] == '发票打印')
                    $moldManage [$value ['mold']] = $value ['staffList'];
                elseif ($value ['mold'] == '发票邮寄')
                    $moldManage [$value ['mold']] = $value ['staffList'];
                elseif ($value ['mold'] == '发票退票')
                    $moldManage [$value ['mold']] = $value ['staffList'];
            }

            $pendingApprovalsSid = current ( $invoiceManageDetail ['staffList'] ) [0];

            //培训班ID--新增关联-发票关系  发票IID关联
            $invoice = new invoice ();
            $invoiceDetail=$invoice->getInvoiceByIid($iid);
            //退票后，重新开票金额的限制
            $restrictPrice=$invoiceDetail['invoicePrice'];
            if (!empty($invoiceDetail['inheritIid'])){
                $restrictList=$invoice->getInvoiceInIid($invoiceDetail['inheritIid']);
                foreach ($restrictList as $key=>$value){
                    $restrictPrice-=$value['invoicePrice'];
                }
            }
            if ($restrictPrice<0){
                header ( 'Content-Type:text/html;charset=utf-8' );
                die ( '开票金额超出原退票金额-0' );
            }else{
                if($restrictPrice<$temporary){
                    header ( 'Content-Type:text/html;charset=utf-8' );
                    die ( '开票金额超出原退票金额-1' );
                }
            }

            $trainId=$invoiceDetail['trainId'];
            $st = 1;
            if (empty ( $trainId ) && ! is_numeric ( $trainId )) {
                die ( 'illegal request-trainingIdError' );
            }

            $invoice = new invoice ();
            $item = array (
                'cid' => $cid,
                'categoryName' => $categoryDetil ['title'],
                'invoiceElement' => $invoiceElement,

                'invoiceQuantity' => $invoiceQuantity,
                'invoiceUnitPrice' => $invoiceUnitPrice,

                'invoicePrice' => $invoicePrice,
                'invoiceType' => $invoiceType,
                'settlementType' => $st,
                'doPost' => $doPost,
                'status' => 1,
                'invoiceSerial' => "#F" . date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT),
                'date' => date ( "Y-m-d H:i:s" ),
                'updateTime' => date ( "Y-m-d H:i:s" ),
                'sid' => $this->staff [0] ['sid'],
                'userName' => $this->staff [0] ['username'],
                'invoiceManage' => $invoiceManageDetail ['staff'],
                'pendingApprovals' => $pendingApprovalsSid,
                'moldManage' => json_encode ( $moldManage ),
                'remark' => $remark,
                'trainId' => $trainId,
                'parentUntreadIid'=>$trainId
            );
            if ($invoiceType == 0)
                $item += array (
                    'invoiceTitle' => $invoiceTitle,
                    'TIN' => $TINT,
                    'address' => $addressT,
                    'phone' => $phoneT,
                    'bank' => $bankT,
                    'bankAccount' => $bankAccountT
                );
            else {
                $item += array (
                    'invoiceCompany' => $invoiceCompany,
                    'TIN' => $TIN,
                    'address' => $address,
                    'phone' => $phone,
                    'bank' => $bank,
                    'bankAccount' => $bankAccount
                );
            }
            if ($doPost == 1) {
                $mailList = array (
                    'invoice' => 1,
                    'mailItems' => $mailItems
                );
                if (! empty ( $softLock ))
                    $mailList += array (
                        'softLock' => $softLockNum
                    );
                else
                    $mailList += array (
                        'softLock' => 0
                    );
                if (! empty ( $contract ))
                    $mailList += array (
                        'contract' => $contractNum
                    );
                else
                    $mailList += array (
                        'contract' => 0
                    );
                if (! empty ( $instructions ))
                    $mailList += array (
                        'instructions' => $instructionsNum
                    );
                else
                    $mailList += array (
                        'instructions' => 0
                    );
                if (! empty ( $remittance ))
                    $mailList += array (
                        'remittance' => $remittance
                    );
                else
                    $mailList += array (
                        'remittance' => ''
                    );

                $mailString = '发票x1张,备注:' . $mailItems;
                if (! empty ( $softLock ))
                    $mailString .= ',软件锁x' . $softLockNum . '个';
                if (! empty ( $contract ))
                    $mailString .= ',合同x' . $contractNum . '份';
                if (! empty ( $instructions ))
                    $mailString .= ',说明书x' . $instructionsNum . '本';
                if (! empty ( $remittance ))
                    $mailString .= ',汇款账号单(张)';

                $item += array (
                    'recipients' => $recipients,
                    'recipientsPhone' => $recipientsPhone,
                    'recipientsAddress' => $recipientsAddress,
                    'mailItems' => $mailString,
                    'mailItemsJson' => json_encode ( $mailList )
                );
            }
            $iid = $invoice->addInvoice ( $item );

            $invoice = new invoice ();
            if (!empty($invoiceDetail['inheritIid'])){
                $inheritIid=$invoiceDetail['inheritIid'].','.$iid;
            }else{
                $inheritIid=$iid;
            }

            $item = array (
                'iid' => $invoiceDetail['iid'],
                'inheritIid' => $inheritIid
            );
            $invoice->setInvoiceByCondition($item);


            // 如果是培训班结算 创建培训班发票到培训班备份中
            if (! empty ( $st ) && $st == 1) {
                Doo::loadModel ( 'invoiceStore' );
                $invoiceStore = new invoiceStore ();
                Doo::loadModel ( 'invoiceTraining' );
                $invoiceTraining = new invoiceTraining ();

                $isid = $invoiceStore->setInvoiceToInvoiceStore ( $iid );
                $itemIS = array (
                    'isid' => $isid,
                    'ipSource' => 1,
                    'apStatus' => 1,
                    'iid' => $iid
                );
                $invoiceStore->setInvoiceStoreByCondition ( $itemIS );

                // 更新培训班总数量
                $detailIT = $invoiceTraining->getInvoiceTrainingByItid ( $trainId );
                $item = array (
                    'itid' => $trainId,
                    'invoiceTotal' => $detailIT ['invoiceTotal'] + 1,
                    'submitStatus' => 1
                );
                $itid = $invoiceTraining->setInvoiceTrainByCondition ( $item );
            }

            // 操作日志
            $item = array (
                'date' => date ( "Y-m-d H:i:s" ),
                'operation' => "创建",
                'status' => 1,
                'img' => $this->staff [0] ['avatar'],
                'username' => $this->staff [0] ['username'],
                'uid' => $this->staff [0] ['sid'],
                'category' => $this->staff [0] ['category'],
                'iid' => $iid
            );
            $invoiceOperationLog->setInvoiceOperationLog ( $item );
            $item = array (
                'date' => date ( "Y-m-d H:i:s" ),
                'operation' => "提交审批",
                'status' => 1,
                'img' => $this->staff [0] ['avatar'],
                'username' => $this->staff [0] ['username'],
                'uid' => $this->staff [0] ['sid'],
                'category' => $this->staff [0] ['category'],
                'iid' => $iid
            );
            $invoiceOperationLog->setInvoiceOperationLog ( $item );

        }
        //return "/invoiceUntreadED";
    }

	/**
	 * 旧输入导入
	 */
	function _GetFileEXT($filename) {
		$pics = explode ( '.', $filename );
		$num = count ( $pics );
		return $pics [$num - 1];
	}
	
	/**
	 * 生成token
	 * @return string
	 */
	function set_token() {
		$str = md5 ( uniqid ( md5 ( microtime ( true ) ), true ) ); // 生成一个不会重复的字符串
		$str = sha1 ( $str ); // 加密
		return $str;
	}
	
	/**
	 * 获取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 SafeFilter(&$arr) {
		$ra = Array (
				'/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/',
				'/script/',
				'/javascript/',
				'/vbscript/',
				'/expression/',
				'/applet/',
				'/meta/',
				'/xml/',
				'/blink/',
				'/link/',
				'/style/',
				'/embed/',
				'/object/',
				'/frame/',
				'/layer/',
				'/title/',
				'/bgsound/',
				'/base/',
				'/onload/',
				'/onunload/',
				'/onchange/',
				'/onsubmit/',
				'/onreset/',
				'/onselect/',
				'/onblur/',
				'/onfocus/',
				'/onabort/',
				'/onkeydown/',
				'/onkeypress/',
				'/onkeyup/',
				'/onclick/',
				'/ondblclick/',
				'/onmousedown/',
				'/onmousemove/',
				'/onmouseout/',
				'/onmouseover/',
				'/onmouseup/',
				'/onunload/' 
		);
		
		if (is_array ( $arr )) {
			foreach ( $arr as $key => $value ) {
				if (! is_array ( $value )) {
					if (! get_magic_quotes_gpc ()) // 不对magic_quotes_gpc转义过的字符使用addslashes(),避免双重转义。
{
						$value = addslashes ( $value ); // 给单引号（'）、双引号（"）、反斜线（\）与 NUL（NULL 字符）加上反斜线转义
					}
					$value = preg_replace ( $ra, '', $value ); // 删除非打印字符，粗暴式过滤xss可疑字符串
					$arr [$key] = htmlentities ( strip_tags ( $value ) ); // 去除 HTML 和 PHP 标记并转换为 HTML 实体
				} else {
					SafeFilter ( $arr [$key] );
				}
			}
		}
	}
	
	/**
	 * Escape String
	 *
	 * @access public
	 * @param string
	 * @param bool whether or not the string will be used in a LIKE condition
	 * @return string
	 */
	function escape_str($str, $like = FALSE) {
		if (is_array ( $str )) {
			foreach ( $str as $key => $val ) {
				$str [$key] = $this->escape_str ( $val, $like );
			}
			return $str;
		}
		
		var_dump ( Doo::db ()->getDbObject () );
		die ();
		
		if (function_exists ( 'mysql_real_escape_string' ) and is_resource ( Doo::db ()->getDbObject () )) { // Doo::db ()->getDbObject()
			$str = mysql_real_escape_string ( $str, Doo::db ()->getDbObject () );
		} elseif (function_exists ( 'mysql_escape_string' )) {
			$str = mysql_escape_string ( $str );
		} else {
			$str = addslashes ( $str );
		}
		// escape LIKE condition wildcards
		if ($like === TRUE) {
			$str = str_replace ( array (
					'%',
					'_' 
			), array (
					'\\%',
					'\\_' 
			), $str );
		}
		return $str;
	}
	
	/**
	 * 获得分页数据
	 * @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 $on_page
	 */
	function get_previous($on_page = 1) {
		return $on_page != 0 ? $on_page - 1 : $on_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  " . $condition;
		
		// echo $sql;die;
		$query = Doo::db ()->query ( $sql );
		$result = $query->fetch ();
		return $result ['count'];
	}
	
	/**
	 * 获得分页数据
	 * @param unknown_type $table
	 * @param unknown_type $condition
	 * @param unknown_type $on_page
	 * @param unknown_type $page_size
	 */
	function getPageBySql($sql = "", $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->getTableCountBySql ( $sql );
		$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;
	}
	
	/**
	 * 获得总页数 sql
	 * @param string $type
	 * @return boolean[]
	 */
	public function getTableCountBySql($sql = "") {
		$query = Doo::db ()->query ( $sql );
		$result = $query->fetchAll ();
		
		return count ( $result );
	}
	function isInvoiceNew($type = "GLOBAL") {
		Doo::loadModel ( 'invoice' );
		$invoice = new invoice ();
		Doo::loadModel ( 'invoiceReceivables' );
		$invoiceReceivables = new invoiceReceivables ();
		Doo::loadModel ( 'staff' );
		$staff = new staff ();
		
		$st = $staff->getUserByIdList ( $_COOKIE ["staff"] );
		
		// 我的发票待处理
		$pendingInvoice = $invoice->getOne ( array ( // or (status=2 and printStatus=1 and untreadStatus=0 ) or (status=2 and printStatus=1 and untreadStatus=2 )
				'where' => "(status=3 or status=4) and isDelete=0 and sid=" . $st [0] ['sid'],
				'desc' => 'iid',
				'asArray' => TRUE 
		) );
		// 我的收款待入账
		/*
		 * $myClaim = $invoiceReceivables->getOne ( array ( 'where' => " receivablesStaff like '" . $st [0] ['sid'] . "-%' and receivablesCategory like '" . $st [0] ['cid'] . ":%' and bindStatus=0", 'desc' => 'irid', 'asArray' => TRUE ) );
		 */
		// 发票审批
		$approval = $invoice->getOne ( array (
				'where' => 'status=1 and pendingApprovals=' . $st [0] ['sid'],
				'desc' => 'iid',
				'asArray' => true 
		) );
		// 发票邮寄
		$post = $invoice->getOne ( array (
				'where' => "postStatus=0 and  printStatus=1 and isDelete=0 and doPost=1 and status=2",
				'asArray' => TRUE 
		) );
		// 发票打印
		$print = $invoice->getOne ( array (
				'where' => "status=2 and printStatus=0 and untreadStatus=0 and moldManage like '%[\"" . $st [0] ['sid'] . "\",%'",
				'desc' => 'iid',
				'asArray' => TRUE 
		) );
		// 发票退票 printStatus=1 and
		$untread = $invoice->getOne ( array (
				'where' => "  untreadStatus=1 and status=2 ",
				'asArray' => TRUE 
		) );
		
		$new = array (
				'GLOBAL' => FALSE,
				'pendingInvoice' => FALSE,
				// 'myClaim' => FALSE,
				'approval' => FALSE,
				'post' => FALSE,
				'print' => FALSE,
				'untread' => FALSE 
		);
		// || ! empty ( $myClaim )
		if (! empty ( $pendingInvoice ) || ! empty ( $approval ) || ! empty ( $post ) || ! empty ( $print ) || ! empty ( $untread ))
			$new ['GLOBAL'] = TRUE;
		if (! empty ( $pendingInvoice ))
			$new ['pendingInvoice'] = TRUE;
			// if (! empty ( $myClaim ))
			// $new ['myClaim'] = TRUE;
		if (! empty ( $approval ))
			$new ['approval'] = TRUE;
		if (! empty ( $post ))
			$new ['post'] = TRUE;
		if (! empty ( $print ))
			$new ['print'] = TRUE;
		if (! empty ( $untread ))
			$new ['untread'] = TRUE;
		return $new;
	}
	function setWXMsg($rid, $typeMsg = '') {
		Doo::loadModel ( 'invoice' );
		$invoice = new invoice ();
		
		$invoiceDetail = $invoice->getOne ( array (
				'where' => 'iid=' . $rid,
				'asArray' => true 
		) );
		
		if (! empty ( $invoiceDetail )) {
			Doo::loadModel ( 'staff' );
			$staff = new staff ();
			$staffmsg = $staff->getOne ( array (
					'where' => "sid='" . $invoiceDetail ['sid'] . "'",
					'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'];
				
				$expCom = explode ( ":", $invoiceDetail ['expressCompany'] );
				if (empty ( $expCom ))
					$expCom [0] = '';
				
				$msg = "";
				if (empty ( $typeMsg ))
					$msg = '太好了，您的发票' . $invoiceDetail ['invoiceSerial'] . ' 已邮寄  ' . $expCom [0] . ' ,快递号: <a href="https://m.kuaidi100.com/result.jsp?nu=' . $invoiceDetail ['expressNumber'] . '" >' . $invoiceDetail ['expressNumber'] . '</a>';
				elseif ($typeMsg == "PRINT")
					$msg = '太好了，您的发票已打印完成。';
				
				$result = $client->SendMsg ( $user, $msg, 'text' );
			}
		}
	}
	/**
	 * 获取微信部门
	 * @param string $category
	 * @return number|mixed
	 */
	function getToparty($category = '') {
		$token = $this->getAccessToken (); //
		$result = json_decode ( $this->httpGet ( "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={$token}&id=5" ), true );
		$toparty = 0;
		foreach ( $result ['department'] as $key => $value ) {
			if ($value ['name'] == $category)
				$toparty = $value ['id'];
		}
		return $toparty;
	}
	
	/**
	 * 获得某部门下的用户
	 * @param string $toparty
	 */
	function getUserByToparty($toparty = '') {
		$token = $this->getAccessToken (); //
		
		$result = json_decode ( $this->httpGet ( "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token={$token}&department_id={$toparty}" ), true );
		
		$userList = array ();
		foreach ( $result ['userlist'] as $key => $value ) {
			array_push ( $userList, "'" . $value ['userid'] . "'" );
		}
		return $userList;
	}
	function msgSendToparty($msg, $title, $url, $toparty, $text = '') {
		$token = $this->getAccessToken ();
		if ($text == 'text') {
			$data = '{
   				"touser": "' . $toparty . '",
   				"toparty": "",
   				"totag": "",
  				"msgtype": "text",
   				"agentid": 1000002,
   				"text": {
       				"content": "' . $msg . '"
   				},
   				"safe":0
			}';
		}
		$result = json_decode ( $this->httpPOST ( "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={$token}", $data ) );
		if ($result->errmsg != 'ok') {
			return 0;
		} else {
			return 1;
		}
	}
	
	/**
	 * 获得可以发送微信用户列表
	 * @param string $category
	 * @return string
	 */
	function getWxidByCategory($category = "") {
		if (empty ( $category ))
			return "";
		Doo::loadModel ( 'staff' );
		$staff = new staff ();
		$toparty = $this->getToparty ( $category );
		$wxList = array ();
		$wxString = "";
		if (! empty ( $toparty )) {
			$userList = $this->getUserByToparty ( $toparty );
			$userCon = implode ( ',', $userList );
			// echo $userCon;
			$sidList = $staff->getStaffByWxid ( $userCon );
			foreach ( $sidList as $key => $value ) {
				$falg = $this->isSendNotification ( $value ['sid'], 'receivables' );
				if ($falg) {
					array_push ( $wxList, $value ['wxid'] );
				}
			}
			$wxString = implode ( '|', $wxList );
		}
		return $wxString;
	}
	
	/**
	 * 读取发送信息规则判断是否需要发送
	 * @param number $sid
	 * @param string $sendType
	 * @return boolean
	 */
	function isSendNotification($sid = 0, $sendType = '') {
		Doo::loadModel ( "notificationConf" );
		$notificationConf = new notificationConf ();
		
		$detail = $notificationConf->getNotificationConfBySid ( $sid );
		
		$conf = array ();
		$sendFlag = true;
		if (! empty ( $detail )) {
			$conf = json_decode ( $detail ['conf'], true );
			if (! empty ( $sendType )) {
				if (isset ( $conf [$sendType] )) {
					if ($conf [$sendType] == "CLOSE")
						$sendFlag = false;
					elseif ($conf [$sendType] == "Weekend") {
						$day = date ( "w" );
						if (1 <= $day && 5 >= $day)
							$sendFlag = false;
					} elseif ($conf [$sendType] == "OneToFriday") {
						$day = date ( "w" );
						if (0 == $day || 6 == $day)
							$sendFlag = false;
					}
				}
			} else
				$sendFlag = false;
		}
		return $sendFlag;
	}
	
	/**
	 * 根据规则发送信息
	 * @param unknown $msg
	 * @param unknown $title
	 * @param unknown $url
	 * @param unknown $user
	 * @param string $text
	 * @return number
	 */
	private function msgSend($msg, $title, $url, $user, $sid = 0, $sendType = '') {
		$token = $this->getAccessToken ();
		$falg = $this->isSendNotification ( $sid, $sendType );
		// if ($text == 'text') {
		// $data = '{
		// "touser": "' . $user . '",
		// "toparty": "",
		// "totag": "",
		// "msgtype": "text",
		// "agentid": 1000002,
		// "text": {
		// "content": "' . $msg . '"
		// },
		// "safe":0
		// }';
		// } else {
		$data = '{
				"touser": "' . $user . '",
   				"toparty": "",
   				"totag": "",
   				"msgtype": "news",
   				"agentid": 1000002,
   				"news": {
       				"articles":[
           				{
               				"title": "' . $title . '",
               				"description": "' . $msg . '",
               				"url": "' . $url . '",
               				"picurl": ""
           				}
           			]
   				}
			}';
		// }
		if ($falg) {
			$result = json_decode ( $this->httpPOST ( "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={$token}", $data ) );
			if ($result->errmsg != 'ok') {
				return 0;
			} else {
				return 1;
			}
		} else
			return 0;
	}
	private function getAccessToken() {
		// access_token 应该全局存储与更新，以下代码以写入到文件中做示例
		// $file = './access_token.txt';
		// $data = json_decode ( file_get_contents ( $file ) );
		// if ($data->expire_time < time () or ! $data->expire_time) {
		// 如果是企业号用以下URL获取access_token
		$url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
		
		// $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
		$res = json_decode ( $this->httpGet ( $url ) );
		$access_token = $res->access_token;
		// echo $access_token;
		// if ($access_token) {
		// $data->expire_time = time () + 7000;
		// $data->access_token = $access_token;
		// $fp = fopen ( $file, "w" );
		// fwrite ( $fp, json_encode ( $data ) );
		// fclose ( $fp );
		// }
		// } else {
		// $access_token = $data->access_token;
		// }
		return $access_token;
	}
	private function httpGet($url) {
		$curl = curl_init ();
		curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, true );
		curl_setopt ( $curl, CURLOPT_TIMEOUT, 500 );
		// 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
		// 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
		curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, true );
		curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, false );
		curl_setopt ( $curl, CURLOPT_URL, $url );
		
		$res = curl_exec ( $curl );
		curl_close ( $curl );
		
		return $res;
	}
	private function httpPost($url, $data) {
		$curl = curl_init ();
		curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, true );
		curl_setopt ( $curl, CURLOPT_TIMEOUT, 500 );
		// 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
		// 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
		curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, true );
		curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, false );
		curl_setopt ( $curl, CURLOPT_URL, $url );
		curl_setopt ( $curl, CURLOPT_POST, 1 );
		curl_setopt ( $curl, CURLOPT_POSTFIELDS, $data );
		$res = curl_exec ( $curl );
		curl_close ( $curl );
		
		return $res;
	}
}

?>