<?php
Doo::loadCore ( 'db/DooModel' );
/**
 * 发票审批相关信息及其操作业务逻辑
 * @author CP.
 * @version 1.0
 * @namespace invoice
 * @package invoiceModel
 */
class invoiceStore extends DooModel {
	private $INVOICEKEY = "APPROVAL";
	private $FUZZY = 'FUZZY';
	private $EXACTLY = "EXACTLY";
	
	/**
	 *
	 * @var integer $iid 发票ID
	 */
	public $trainId;
	public $apStatus;
	public $isid;
	public $iid;
	public $lossIid;
	public $ipSource;
	/**
	 *
	 * @var integer $status 审批状态
	 */
	public $status;
	/**
	 *
	 * @var string $invoiceManage 当前审批组人员
	 */
	public $printStatus;
	public $postStatus;
	public $invoiceManage;
	/**
	 *
	 * @var string $pendingApprovals 当前需要审批的人
	 */
	public $pendingApprovals;
	/**
	 *
	 * @var string $processApprovals 已经审批过的人员
	 */
	public $processApprovals;
	/**
	 *
	 * @var string $invoiceSerial 发票单号
	 */
	public $invoiceSerial;
	/**
	 *
	 * @var integer $invoicePrice 发票金额
	 */
	public $invoicePrice;
	public $invoiceQuantity;
	public $invoiceUnitPrice;
	
	/**
	 * 管理组人员：发票打印，
	 * @var unknown
	 */
	public $moldManage;
	/**
	 *
	 * @var integer $cid 办事处ID
	 */
	public $cid;
	/**
	 *
	 * @var string $categoryName 办事处名称
	 */
	public $categoryName;
	/**
	 *
	 * @var integer $sid 提交发票人ID
	 */
	public $sid;
	/**
	 *
	 * @var string $userName 提交人名字
	 */
	public $printer;
	public $userName;
	/**
	 *
	 * @var string $remark 备注
	 */
	public $remark;
	/**
	 *
	 * @var string $invoiceElement 发票内容
	 */
	public $invoiceElement;
	/**
	 *
	 * @var string $invoiceType 发票类型
	 */
	public $invoiceType;
	/**
	 *
	 * @var string $invoiceTitle 发票抬头
	 */
	public $invoiceTitle;
	/**
	 *
	 * @var string $invoiceCompany 开票公司
	 */
	public $invoiceCompany;
	/**
	 *
	 * @var string $invoiceNo 发票号
	 */
	public $invoiceNo;
	/**
	 *
	 * @var string $TIN 纳税人识别码
	 */
	public $TIN;
	/**
	 *
	 * @var string $address 注册地址
	 */
	public $address;
	/**
	 *
	 * @var string $phone 电话
	 */
	public $phone;
	/**
	 *
	 * @var string $bank 开户银行
	 */
	public $bank;
	/**
	 *
	 * @var string $bankAccount 银行账户
	 */
	public $bankAccount;
	/**
	 *
	 * @var integer $doPost 邮寄
	 */
	public $doPost;
	/**
	 *
	 * @var string $recipients 收件人
	 */
	public $recipients;
	/**
	 *
	 * @var string $recipientsPhone 收件人电话
	 */
	public $recipientsPhone;
	/**
	 *
	 * @var string $recipientsAddress 收件地址
	 */
	public $recipientsAddress;
	/**
	 *
	 * @var string $mailItems 邮寄物品
	 */
	public $mailItems;
	public $mailItemsJson;
	public $expressCompany;
	public $expressNumber;
	public $actualItems;
	public $poster;
	public $untreadReason;
	public $untreadPost;
	public $untreadCompany;
	public $untreadNumber;
	public $untreadItems;
	public $untreadStatus;
	public $irid;
	public $bindTime;
	/**
	 *
	 * @var date $date 提交时间
	 */
	public $date;
	public $isDelete;
	/**
	 *
	 * @var date $updateTime 更新时间
	 */
	public $updateTime;
	/**
	 *
	 * @var date $printTime 打印时间
	 */
	public $printTime;
	public $postTime;
	public $_table = 'CLD_invoiceStore';
	public $_primarykey = 'isid';
	public $_fields = array (
			'trainId',
			'apStatus',
			'isid',
			'iid',
			'ipSource',
			'lossIid',
			'invoiceManage',
			'pendingApprovals',
			'processApprovals',
			'invoiceSerial',
			'status',
			'printStatus',
			'postStatus',
			'untreadStatus',
			'invoiceQuantity',
			'invoiceUnitPrice',
			'invoicePrice',
			'moldManage',
			'cid',
			'categoryName',
			'irid',
			'remark',
			'invoiceElement',
			'invoiceType',
			'invoiceTitle',
			'invoiceCompany',
			'invoiceNo',
			'TIN',
			'address',
			'phone',
			'bank',
			'bankAccount',
			'doPost',
			'recipients',
			'recipientsPhone',
			'recipientsAddress',
			'mailItems',
			'mailItemsJson',
			'expressCompany',
			'expressNumber',
			'actualItems',
			'untreadReason',
			'untreadPost',
			'untreadCompany',
			'untreadNumber',
			'untreadItems',
			'poster',
			'sid',
			'userName',
			'printer',
			'date',
			'isDelete',
			'updateTime',
			'printTime',
			'postTime',
			'bindTime' 
	);
	
	/**
	 * 根据培训班ID获得发票数据
	 * @param number $itid
	 */
	function getinvoiceStoreByItid($itid = 0,$con='')
    {
        Doo::loadClass('XDeode');
        $XDeode = new XDeode (5);
        $itid = $XDeode->decode($itid);
        Doo::loadModel('invoice');
        $invoice = new invoice ();

        $list = array();
        if (!empty ($itid) && is_numeric($itid)) {

            $field = 'b.iid,a.status,a.apStatus,a.isid,a.invoiceCompany,a.invoiceTitle,a.TIN,a.address,a.phone,a.bank,a.bankAccount,a.invoiceElement
			        ,a.invoiceQuantity,a.invoiceUnitPrice,a.invoicePrice,a.invoiceType,a.remark
					,a.mailItems,a.recipientsAddress,a.recipients,a.recipientsPhone,a.remark,a.remark,a.remark,a.remark,a.userName
					,b.invoiceSerial,b.printTime,b.invoiceNo,b.status,b.printStatus,b.untreadStatus,b.irid
					,b.invoicePrice as Bprice,b.invoiceQuantity as BQuantity,b.invoiceUnitPrice as BUnitPrice,b.status as BStatus';

            $sql = "select " . $field . " from " . $this->_table . " as a left join CLD_invoice as b on (a.iid=b.iid  )  
			where " . $con . "  a.trainId=" . $itid . '   and ( b.isDelete is null or b.isDelete=0 )  order by a.isid desc ';
            //echo $sql;


            $query = Doo::db()->query($sql);
            $list = $query->fetchAll();
        }

        // 获得收款流水号
        $iridList = array();
        $iidList = array();
        foreach ($list as $key => $value) {
            array_push($iidList, $value['iid']);
            if (!empty($value['Bprice'])) {
                $list [$key] ['invoicePrice'] = $value['Bprice'];
            }
            if (!empty($value['BQuantity'])) {
                $list [$key] ['invoiceQuantity'] = $value['BQuantity'];
            }
            if (!empty($value['BUnitPrice'])) {
                $list [$key] ['invoiceUnitPrice'] = $value['BUnitPrice'];
            }
            if (!empty($value['BStatus'])) {//已提交的发票
                $list [$key] ['apStatus'] = 1;
            }


            $list [$key] ['storeKey'] = $XDeode->encode($value ['isid']);
            $list [$key] ['iridArray'] = array();
            if (!empty ($value ['irid'])) {
                array_push($iridList, $value ['irid']);
                $list [$key] ['iridArray'] = explode(',', $value ['irid']);
            }
            $list [$key] ['invoiceReceivables'] = array();
        }
        $iridString = implode(',', $iridList);
        $iidList=array_filter ($iidList);
        $iidString = implode(',', $iidList);


        if (!empty($iidString)) {
        $ilist = $invoice->find(array(
            'where' => "trainId = " . $itid . " and (status=1 or status=2) and untreadStatus!=2 and ( isDelete is null or isDelete=0 ) and iid not in (" . $iidString . ")",
            'asArray' => TRUE
        ));

        if (!empty($ilist)) {
            foreach ($ilist as $key => $value) {
                $value['apStatus'] = 1;
                array_push($list, $value);
                $isid =$this->setInvoiceToInvoiceStore($value['iid']);
                //更新为已提交
                $itemIS = array (
                    'isid' => $isid,
                    'ipSource' => 1,
                    'apStatus' => 1,
                    'iid' => $value['iid']
                );
                $this->setInvoiceStoreByCondition ( $itemIS );
            }
        }
        }
		//print_r($ilist);

		Doo::loadModel ( 'invoiceReceivables' );
		$invoiceReceivables = new invoiceReceivables ();
		
		$irlist = $invoiceReceivables->getInvoiceReceivablesInIridString ( $iridString );
		foreach ( $irlist as $key => $value ) {
			foreach ( $list as $k => $v ) {
				if (in_array ( $value ['irid'], $v ['iridArray'] )) {
					array_push ( $list [$k] ['invoiceReceivables'], array (
							$value ['irid'],
							$value ['receivablesSerial'],
							$value ['iridKeyK'] 
					) );
				}
			}
		}
		
		// print_r($list);
		// echo $iridString;
		
		return $list;
	}
	
	/**
	 * 根据参数字段更新相应字段（主键ID必须传）
	 * @param array $item 相关需要更新的字段信息
	 * @return number 返回发票ID
	 */
	public function setInvoiceStoreByCondition($item = array(), $isid = "") {
		$lid = 0;
		
		if (is_array ( $item ) && ! empty ( $item )) {
			foreach ( $item as $key => $value ) {
				$this->$key = $value;
			}
			
			if (! empty ( $isid )) {
				$condition = array (
						'where' => "isid in (" . $isid . ")",
						'asArray' => TRUE 
				);
				$this->update ( $condition );
			} else
				$lid = $this->update ();
		}
		return $lid;
	}
	
	/**
	 * 根据发票ID获取一条发票数据
	 * @param number $iid 发票ID
	 * @param number $select 需要获取的字段,为空获取全部数据
	 * @return array|array() 返回发票数据
	 */
	public function getInvoiceStoreByIsid($iid = 0, $select = "") {
		if (! is_numeric ( $iid ))
			$iid = $this->authcode ( $iid );
		
		$condition = array (
				'where' => "isid=" . $iid,
				'asArray' => TRUE 
		);
		if (! empty ( $select ))
			$condition += array (
					'select' => $select 
			);
		
		$Detail = array ();
		if (is_numeric ( $iid ) && ! empty ( $iid ))
			$Detail = $this->getOne ( $condition );
		
		if (empty ( $Detail ))
			return $Detail;
		if (isset ( $Detail ['expressCompany'] ) && ! empty ( $Detail ['expressCompany'] )) {
			$express = explode ( ":", $Detail ['expressCompany'] );
			$Detail ['expressCompany'] = $express [0];
			$Detail ['expressCom'] = $express [1];
		} else {
			$Detail ['expressCompany'] = '';
			$Detail ['expressCom'] = '';
		}
		
		Doo::loadClass ( 'XDeode' );
		$XDeode = new XDeode ( 5 );
		
		$Detail ['storeKey'] = $XDeode->encode ( $Detail ['isid'] );
		$Detail ['trainKey'] = $XDeode->encode ( $Detail ['trainId'] );
		
		$Detail ['iidKey'] = $this->authcode ( $Detail ['isid'], '' );
		Doo::loadModel ( 'L_category' );
		$lCategory = new L_category ();
		$Detail ['category'] = $lCategory->getCategory ();
		return $Detail;
	}
	
	/**
	 * 根据Isid 获得多条数据
	 */
	function getInvoiceStoreInIsid($isid = '', $select = "") {
		$condition = array (
				'where' => "isid in ( " . $isid . ")",
				'asArray' => TRUE 
		);
		if (! empty ( $select ))
			$condition += array (
					'select' => $select 
			);
		$detail = array ();
		if (! empty ( $isid ))
			$detail = $this->find ( $condition );
		return $detail;
	}
	
	// 拷贝一条数据
	function setInvoiceStoreToApproval($isid = "") {
		if (empty ( $isid ))
			return 0;
		
		$sql = 'insert into CLD_invoice (`isid`,`invoiceQuantity`, `invoiceUnitPrice`, `invoicePrice`, `moldManage`, `cid`, `categoryName`, `sid`, `userName`, `remark`, `invoiceElement`, `invoiceType`, `invoiceTitle`, `invoiceCompany`, `invoiceNo`, `TIN`, `address`, `phone`, `bank`, `bankAccount`, `doPost`, `recipients`, `recipientsPhone`, `recipientsAddress`, `mailItems`, `mailItemsJson`, `expressCompany`, `expressNumber`, `actualItems`, `untreadReason`, `untreadPost`, `untreadCompany`, `untreadNumber`, `untreadItems`)
			select `isid`,`invoiceQuantity`, `invoiceUnitPrice`, `invoicePrice`, `moldManage`, `cid`, `categoryName`, `sid`, `userName`, `remark`, `invoiceElement`, `invoiceType`, `invoiceTitle`, `invoiceCompany`, `invoiceNo`, `TIN`, `address`, `phone`, `bank`, `bankAccount`, `doPost`, `recipients`, `recipientsPhone`, `recipientsAddress`, `mailItems`, `mailItemsJson`, `expressCompany`, `expressNumber`, `actualItems`, `untreadReason`, `untreadPost`, `untreadCompany`, `untreadNumber`, `untreadItems` from ' . $this->_table . '  
			where isid=' . $isid;
		$query = Doo::db ()->query ( $sql );
		
		return Doo::db ()->lastInsertId ();
	}
	
	//拷贝一条发票到库存
	function setInvoiceToInvoiceStore($iid = "") {
		if (empty ( $iid ))
			return 0;
		
		$sql = 'insert into '. $this->_table . ' (`iid`,`status`,`untreadStatus`,`trainId`,`invoiceQuantity`, `invoiceUnitPrice`, `invoicePrice`, `moldManage`, `cid`, `categoryName`, `sid`, `userName`, `remark`, `invoiceElement`, `invoiceType`, `invoiceTitle`, `invoiceCompany`, `invoiceNo`, `TIN`, `address`, `phone`, `bank`, `bankAccount`, `doPost`, `recipients`, `recipientsPhone`, `recipientsAddress`, `mailItems`, `mailItemsJson`, `expressCompany`, `expressNumber`, `actualItems`, `untreadReason`, `untreadPost`, `untreadCompany`, `untreadNumber`, `untreadItems`)
										select `iid`,`status`,`untreadStatus`,`trainId`,`invoiceQuantity`, `invoiceUnitPrice`, `invoicePrice`, `moldManage`, `cid`, `categoryName`, `sid`, `userName`, `remark`, `invoiceElement`, `invoiceType`, `invoiceTitle`, `invoiceCompany`, `invoiceNo`, `TIN`, `address`, `phone`, `bank`, `bankAccount`, `doPost`, `recipients`, `recipientsPhone`, `recipientsAddress`, `mailItems`, `mailItemsJson`, `expressCompany`, `expressNumber`, `actualItems`, `untreadReason`, `untreadPost`, `untreadCompany`, `untreadNumber`, `untreadItems` from 
				CLD_invoice where iid=' . $iid;
		//echo $sql;die;
		$query = Doo::db ()->query ( $sql );
		
		return Doo::db ()->lastInsertId ();
	}
	
	/**
	 * 批量插入多条发票发
	 * @param string $isid
	 * @return number
	 */
	function setInvoiceStoreBatchToApproval($isid = "") {
		if (empty ( $isid ))
			return 0;
		
		$sql = 'insert into CLD_invoice (`isid`,`invoiceQuantity`, `invoiceUnitPrice`, `invoicePrice`, `moldManage`, `cid`, `categoryName`, `sid`, `userName`, `remark`, `invoiceElement`, `invoiceType`, `invoiceTitle`, `invoiceCompany`, `invoiceNo`, `TIN`, `address`, `phone`, `bank`, `bankAccount`, `doPost`, `recipients`, `recipientsPhone`, `recipientsAddress`, `mailItems`, `mailItemsJson`, `expressCompany`, `expressNumber`, `actualItems`, `untreadReason`, `untreadPost`, `untreadCompany`, `untreadNumber`, `untreadItems`)
			select `isid`,`invoiceQuantity`, `invoiceUnitPrice`, `invoicePrice`, `moldManage`, `cid`, `categoryName`, `sid`, `userName`, `remark`, `invoiceElement`, `invoiceType`, `invoiceTitle`, `invoiceCompany`, `invoiceNo`, `TIN`, `address`, `phone`, `bank`, `bankAccount`, `doPost`, `recipients`, `recipientsPhone`, `recipientsAddress`, `mailItems`, `mailItemsJson`, `expressCompany`, `expressNumber`, `actualItems`, `untreadReason`, `untreadPost`, `untreadCompany`, `untreadNumber`, `untreadItems` from ' . $this->_table . '
			where isid in (' . $isid . ')';
		$query = Doo::db ()->query ( $sql );
		
		return Doo::db ()->lastInsertId ();
	}
	function delInvoiceStoreByIsid($isid='') {
		if (empty ( $isid ))
			return '';
		$sql = "DELETE FROM " . $this->_table . " WHERE `isid`=" . $isid." limit 1";
		$query = Doo::db ()->query ( $sql );
	}
	
	/**
	 * 批量更新
	 * @param string $isid
	 * @return number
	 */
	function UpdateBatchInvoiceStore($sql = "") {
		if (empty ( $sql ))
			return 0;
		
		$query = Doo::db ()->query ( $sql );
	}
}

?>