<?php

/**
 * @desc 服务商帐单处理类
 */
class Process_ServeBill
{
    protected $_date = "";
    protected $_userId = "";

    public function __construct()
    {
        $this->_userId = Service_User::getUserId();
        $this->_date = date('Y-m-d H:i:s');
    }

    /**
     * @desc 上传服务商帐单
     * @param array $param
     * @param $file
     * @return array
     */
    public function uploadStandardBillTransaction($param = array(), $file)
    {
        $result = array("state" => 0, "message" => array(), "code" => "");
        $return = array(
            'state' => 0,
            'message' => array()
        );
        if ($file['error']) {
            $return['message'] = array('请选择xls文件');
            return $return;
        }
        
        //帐单信息基本验证
        if (!isset($param['payer_code']) || empty($param['payer_code'])) {
            $return['message'] = array('服务商代码不能为空');
            return $return;
        }
        if (!isset($param['amount']) || empty($param['amount'])) {
            $return['message'] = array('总金额不能为空');
            return $return;
        }
        if (!isset($param['bsb_no']) || empty($param['bsb_no'])) {
            $return['message'] = array('服务商帐单号不能为空');
            return $return;
        }
        if (!isset($param['dateFor']) || empty($param['dateFor'])) {
            $return['message'] = array('业务开始时间不能为空');
            return $return;
        }
        if (!isset($param['dateTo']) || empty($param['dateTo'])) {
            $return['message'] = array('业务结束时间不能为空');
            return $return;
        }
        if (!isset($param['currency_code']) || empty($param['currency_code'])) {
            $return['message'] = array('帐单币种不能为空');
            return $return;
        }
        if (!isset($param['currency_rate']) || empty($param['currency_rate'])) {
            $return['message'] = array('帐单汇率不能为空');
            return $return;
        }
        
        $billArr = array(
            'sp_code' => $param['payer_code'],
            'bsb_amount' => $param['amount'],
            'id_code' => 'standard',
            'bsb_start_time' => $param['dateFor'],
            'bsb_end_time' => $param['dateTo'],
            'currency_code' => $param['currency_code'],
            'currency_rate' => $param['currency_rate'],
            'bsb_note' => $param['note'],
            'sm_code' => $param['sm_code'],
            'bsb_no' => $param['bsb_no'],
            'bsb_bank_account' => isset($param['bsb_bank_account']) ? $param['bsb_bank_account'] : '',
        );
		
        //不允许重复上传相同单号帐单
        $billRow = Service_BilServeBill::getByField($billArr['bsb_no'], 'bsb_no', array('bsb_status'));
        if (!empty($billRow) && $billRow['bsb_status'] != '0') {
            $return['message'] = array('服务商帐单：' . $billArr['bsb_no'] . ' 已存在,不允许重复操作');
            return $return;
        }
		
        $fileName = $file['name'];
        $filePath = $file['tmp_name'];
        $pathinfo = pathinfo($fileName);
        if (!isset($pathinfo["extension"]) && $pathinfo["extension"] != "xls") {
            $return['message'] = array('请选择xls文件');
            return $return;
        }
        
        //4.8s
        $fileData = Common_Upload::readUploadFile($fileName, $filePath);
        
        if (!isset($fileData[1]) || !is_array($fileData[1])) {
            $result['message'] = array('上传失败，无法解析文件内容;');
            return $result;
        }
        /*
        if(count($fileData)-1 > 6000){
        	$result['message'] = array('账单条数大于6000条;');
        	return $result;
        }
        */
        //格式化数据
        $keys = array(
            '日期' => 'date',
            '单号' => 'tracking_number',
            '收费重（KG）' => 'weight',
            '金额' => 'amount',
            '币种' => 'currency_code',
        );
        //导入数据汇总
        //总票数
        $bsb_quantity = 0;
        //汇总金额
        $bsb_payment_total = 0;
        //汇总金额
        $bsb_charge_weight_total = 0;
        $data = $error = array();
        
	//开始时间
//	$start_t = microtime_float();
		$queryTimes = 0;
        foreach ($fileData as $key => $val) {
            $newVal = array();
            /*
            //  5*6k = 3w
            foreach ($keys as $k => $v) {
                $newVal[$v] = isset($val[$k]) ? $val[$k] : '';
            }
            */
            $val = array_values($val);
			$newVal['date'] = $val[0];
			$newVal['tracking_number'] = $val[1];
			$newVal['weight'] = $val[2];
			$newVal['amount'] = $val[3];
			$newVal['currency_code'] = $val[4];
            
            if (empty($newVal['currency_code'])) {
                $error[] = '第 ' . $key . ' 行,币种不能为空';
                continue;
            }
            //核对币种
            $currencyRow = Service_Currency::getByField($newVal['currency_code'], 'currency_code', array('currency_id'));
            if (empty($currencyRow['currency_id'])) {
                $error[] = '第 ' . $key . ' 行,币种不存在或无法识别';
                continue;
            }
            if (empty($newVal['amount']) || !is_numeric($newVal['amount'])) {
                $error[] = '第 ' . $key . ' 行,金额异常';
                continue;
            }
            if (!empty($newVal['weight']) && !is_numeric($newVal['weight'])) {
                $error[] = '第 ' . $key . ' 行,重量异常';
                continue;
            }
            /*
            $orderCode = '';
            $delivered_weight = 0;
            $customer_code = '';
            */
            //查看订单
            if (!empty($newVal['tracking_number'])) {
            	/*
                //先检查订单是否为区内仓订单
                $soRow = Service_ShipOrder::getByField($newVal['tracking_number'], 'tracking_number', array('so_weight', 'order_code', 'so_fee_weight', 'so_weight'));
                if (!empty($soRow)) {
                    $delivered_weight = $soRow['so_weight'];
                    $orderCode = $soRow['order_code'];
                    $orderRow = Service_Orders::getByField($soRow['order_code'], 'order_code', array('customer_code'));
                    $fee_weight = $soRow['so_fee_weight'];
                    $customer_code = $orderRow['customer_code'];
                } else {
                    $orderRow = Service_Orders::getByField($newVal['tracking_number'], 'order_code', array('order_code', 'customer_code'));
                    if (!empty($orderRow)) {
                        $orderCode = $orderRow['order_code'];
                        $soRow = Service_ShipOrder::getByField($orderCode, 'order_code');
                        $fee_weight = $soRow['so_fee_weight'];
                        $delivered_weight = $soRow['so_weight'];
                        $customer_code = $orderRow['customer_code'];
                    }
                }
                
                //先找logistics_cost表数据
                if(empty($orderCode)){
                	$crRow = Service_CostRecording::getByField($newVal['tracking_number'], 'tracking_number', array('weight', 'order_code'));
                	$loRow = Service_LogisticsOrder::getByField($newVal['tracking_number'], 'ref_tracking_number', array('lo_weight'));
                	$delivered_weight = $crRow['weight'];
                	$orderCode = $crRow['order_code'];
                	if(!empty($loRow)){
                		$fee_weight = $loRow['lo_weight'];
                	}else {
                		$loRow = Service_LogisticsOrder::getByField($newVal['tracking_number'], 'logistics_code', array('lo_weight'));
                		$fee_weight = $loRow['lo_weight'];
                	}
                }
                //再检查订单是否为区外仓订单(logistics_order)
                if(empty($orderCode) || '' == $orderCode ){
                    //区外仓订单判断
                    $loRow = Service_LogisticsOrder::getByField($newVal['tracking_number'], 'ref_tracking_number', array('lo_weight', 'logistics_code'));
                    if(!empty($loRow)){
                        $delivered_weight = $loRow['lo_weight'];
                        $orderCode = $loRow['logistics_code'];
                        $fee_weight = $loRow['lo_weight'];
                    } else {
                        $loRow = Service_LogisticsOrder::getByField($newVal['tracking_number'], 'logistics_code', array('lo_weight', 'logistics_code'));
                        if(!empty($loRow)){
                            $delivered_weight = $loRow['lo_weight'];
                            $orderCode = $loRow['logistics_code'];
                            $fee_weight = $loRow['lo_weight'];
                        }
                    }
                }
                */
                /**单号匹配查询 begin**/
            	//根据单号正则匹配
            	$orderCodeRegular = '/^(DOEC|SOE)\d+$/Ax';
            	//追踪单号
            	$trackingNumberRegular = '/^(LO|SW|RE)\d+\w+$/';
            	
				$orderCode = '';
				$delivered_weight = 0;
				$customer_code = '';
            	
            	//匹配订单规则
				if(preg_match($orderCodeRegular, $newVal['tracking_number'])){
					
					$queryTimes++;
					
					$orderRow = Service_Orders::getByField($newVal['tracking_number'], 'order_code', array('order_code', 'customer_code'));
					$orderCode = $orderRow['order_code'];
					$soRow = Service_ShipOrder::getByField($orderCode, 'order_code', array('so_fee_weight', 'so_weight'));
					$fee_weight = $soRow['so_fee_weight'];
					$delivered_weight = $soRow['so_weight'];
					$customer_code = $orderRow['customer_code'];
				}
				
				//匹配追踪号
			//	if( preg_match($trackingNumberRegular, $newVal['tracking_number']) && empty($orderCode)){
				if(empty($orderCode)){
					$queryTimes++;
                	//ship_order - 先检查订单是否为区内仓订单
                	$soRow = Service_ShipOrder::getByField($newVal['tracking_number'], 'tracking_number', array('so_weight', 'order_code', 'so_fee_weight', 'so_weight'));
                	if (!empty($soRow)) {
                		$delivered_weight = $soRow['so_weight'];
                		$orderCode = $soRow['order_code'];
                		$orderRow = Service_Orders::getByField($soRow['order_code'], 'order_code', array('customer_code'));
                		$fee_weight = $soRow['so_fee_weight'];
                		$customer_code = $orderRow['customer_code'];
                	}
                	//再检查订单是否为区外仓订单(logistics_order)
                	if(empty($orderCode)){
                		//区外仓订单判断
                		/*
                		$loRow = Service_LogisticsOrder::getByField($newVal['tracking_number'], 'ref_tracking_number', array('lo_weight', 'logistics_code', 'customer_code'));
                		if(!empty($loRow)){
                			$delivered_weight = $loRow['lo_weight'];
                			$orderCode = $loRow['logistics_code'];
                			$fee_weight = $loRow['lo_weight'];
                			$customer_code = $loRow['customer_code'];
                		} else {
                			//少一次
                			$loRow = Service_LogisticsOrder::getByField($newVal['tracking_number'], 'logistics_code', array('lo_weight', 'logistics_code', 'customer_code'));
                			if(!empty($loRow)){
                				$delivered_weight = $loRow['lo_weight'];
                				$orderCode = $loRow['logistics_code'];
                				$fee_weight = $loRow['lo_weight'];
                				$customer_code = $loRow['customer_code'];
                			}
                		}
                		*/
                		$where = array(
                				'ref_tracking_number' => $newVal['tracking_number'],
                				'logistics_code' => $newVal['tracking_number']
                		);
                		$loRow = Service_LogisticsOrder::getByOrWhere($where, array('lo_weight', 'logistics_code', 'customer_code'));
                		$queryTimes++;
                		if(!empty($loRow)){
                			$delivered_weight = $loRow['lo_weight'];
                			$orderCode = $loRow['logistics_code'];
                			$fee_weight = $loRow['lo_weight'];
                			$customer_code = $loRow['customer_code'];
                		}
                	}
                	
                	//logistics_cost 
                	if(empty($orderCode)){
                		$queryTimes++;
                		$crRow = Service_CostRecording::getByField($newVal['tracking_number'], 'tracking_number', array('weight', 'order_code'));
                		/*
                		$where = array(
                				'ref_tracking_number' => $newVal['tracking_number'],
                				'logistics_code' => $newVal['tracking_number']
                		);
                		//少一次
                		$loRow = Service_LogisticsOrder::getByOrWhere($where, array('lo_weight', 'logistics_code', 'customer_code'));
                		*/
                		$delivered_weight = $crRow['weight'];
                		$orderCode = $crRow['order_code'];
                		$customer_code = $loRow['customer_code'];
                		$fee_weight = $loRow['lo_weight'];
                		/* -- 少一次
                		if(!empty($loRow)){
                			$fee_weight = $loRow['lo_weight'];
                		}else {
                		//	$loRow = Service_LogisticsOrder::getByField($newVal['tracking_number'], 'logistics_code', array('lo_weight'));
                			$fee_weight = $loRow['lo_weight'];
                		}
                		*/
                	}
                	
                }
                /**单号匹配查询 end**/
                //当单号不为空，必需匹配系统单据
                if ($orderCode == '') {
					$error[] = '第 ' . $key . ' 行,单号：' . $newVal['tracking_number'] . ' 未找到匹配的单据';
                }
            }
			
            $bsb_quantity++;
            $bsb_payment_total += abs($newVal['amount']);
            $bsb_charge_weight_total += $newVal['weight'];
            $newVal['date'] = Process_ImportDataProcess::excelTime($newVal['date']);
            $data[$key]['shipment_time'] = date('Y-m-d', strtotime($newVal['date']));
            $data[$key]['weight'] = $newVal['weight'];
            
			$data[$key]['order_code'] = $orderCode;
		//	$data[$key]['order_code'] = '11111';
			
			$data[$key]['tracking_number'] = $newVal['tracking_number'];
            $data[$key]['delivered_weight'] = !empty($delivered_weight)? $delivered_weight : 0;
            $data[$key]['fee_weight'] = !empty($fee_weight)? $fee_weight : 0;
            $data[$key]['currency_code'] = $currencyRow['currency_code'];
		//	$data[$key]['amount'] = round(abs($newVal['amount']), 3);
			$data[$key]['amount'] = sprintf("%.3f", abs($newVal['amount']));
            
			$data[$key]['customer_code'] = $customer_code;
		//	$data[$key]['customer_code'] = '22222';
        }
        
	/*
	print_r($error);
	$end_t = microtime_float();
	$time = $end_t - $start_t;
	echo '查询总次数：'.$queryTimes.'，总耗时：'.$time.'<br />';
	die();
	*/
        unset($fileData, $newVal);
        if (!empty($error) || empty($data)) {
            $return['state'] = 0;
            $return['message'] = $error;
            return $return;
        }
		
        //事务处理
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            $bsbl_status_to = 1;
            $billArr['bsb_code'] = Common_GetNumbers::getCode('serviceBillNo', '', 'CS');
            $billArr['bsb_mode'] = 1;
            $billArr['bsb_creator_id'] = $this->_userId;
            $billArr['bsb_add_time'] = $this->_date;
            $billArr['bsb_status'] = 1;
            $billArr['bsb_quantity'] = $bsb_quantity;
            $billArr['bsb_payment_total'] = $bsb_payment_total;
            $billArr['bsb_charge_weight_total'] = $bsb_charge_weight_total;

            if (!$bsb_id = Service_BilServeBill::add($billArr)) {
                throw new Exception("建立帐单错误");
            }

            //期初数据初始化
            $surplusArr = array(
                'bsb_id' => $bsb_id,
                'bsbs_update_time' => $this->_date,
            );
            Service_BilServeBillSurplus::add($surplusArr);

            //写入明细表
            foreach ($data as $k => $row) {
                $bsd_diff_type = 0;
                $bsd_value = 0;
                $bsd_amount = 0;
                $accepted_amount = $row['amount'];
                $myAmount = 0;
                $detailArr = array(
                    'customer_code' => $row['customer_code'],
                    'bsb_id' => $bsb_id,
                    'bsbd_hawb_code' => $row['tracking_number'],
                    'bsbd_refer_hawb_code' => $row['order_code'],
                    'bsbd_shipment_time' => $row['shipment_time'],
                    'bsbd_charge_weight' => $row['weight'],//服务商重量
                    'bsbd_delivered_weight' => $row['delivered_weight'],//出库重量
                    'bsbd_fee_weight'=>$row['fee_weight'],
                    'bsbd_add_time' => $this->_date,
                );
                if (!$bsbd_id = Service_BilServeBillDetail::add($detailArr)) {
                    throw new Exception("建立帐单明细错误");
                }
                //重量差异(服务商重量>计费)
                if ($row['weight'] > $row['fee_weight']) {
                    $bsd_diff_type = 1;
                    $bsd_value = abs($row['weight'] - $row['delivered_weight']);
                }

                //明细费用(支持多条)
                $detailFeeArr = array(
						'bsbd_id' => $bsbd_id,
	                    'bsb_id' => $bsb_id,
                		//费用种类
	                    'ft_code' => '', 
	                    'bsbdf_amount' => $row['amount'],
	                	'bsbdf_update_time' => $this->_date
                );
                if (!$bsbdf_id = Service_BilServeBillDetailFee::add($detailFeeArr)) {
                    throw new Exception("建立帐单明细费用错误");
                }
                if (!empty($row['order_code'])) {
                    //绑定应付明细
                    $condition = array(
                        //'bp_status' => '2',
                        'sp_code' => $billArr['sp_code'],
                        'bb_refer_code' => $row['order_code'],
                        //'bb_status' => 'y',
                    );
				//	$paymentRows = Table_BilPayment::getInstance()->getBusinessDetailFeeByCondition($condition, '*', 0);
                    $paymentRows = Table_BilPayment::getInstance()->getBusinessDetailFeeByCondition($condition, array('bp_id', 'bp_amount'), 0);
                    if (!empty($paymentRows)) {
                        //更新业务
                        Service_BilBusiness::update(array('bb_bill_compare_sign' => 'y', 'bb_update_time' => $this->_date), $paymentRows[0]['bb_id'], 'bb_id');
                        foreach ($paymentRows as $pRow) {
                            $myAmount += $pRow['bp_amount'];
                            $updateRow = array('bsbdf_id' => $bsbdf_id, 'bp_status' => 3, 'bp_update_time' => $this->_date);
                            if(!(Table_BilPayment::getInstance()->update($updateRow, $pRow['bp_id'], 'bp_id'))){
                                throw new Exception("应付费用表更新失败");
                            }
                        }
                    }
                    //金额差异
                    if ($row['amount'] > $myAmount) {
					//	$bsd_amount = round(abs($row['amount'] - $myAmount), 3);
                    	$bsd_amount = sprintf("%.3f", abs($row['amount'] - $myAmount));
                    	
                    //	比较只比较两位
                    //	$myAmount = 63.538;
                    	$row['amount'] = sprintf("%.2f", $row['amount']);
                    	$myAmount = sprintf("%.2f", $myAmount);
					
                        if(bccomp($row['amount'], $myAmount, 2)!=0){
                            $bsd_diff_type = 2;
                        }
                    }
                } else {
                    //未匹配业务
                    $bsd_amount = $row['amount'];
                    $bsd_diff_type = 3;
                }
			
                //异常情况
                if ($bsd_diff_type != '0') {
                    $diffArr = array(
                        'bsb_id' => $bsb_id,
                        'bsbd_id' => $bsbd_id,
                        'bsd_diff_type' => $bsd_diff_type,
                        'bsd_value' => $bsd_value,
                        'bsd_amount' => $bsd_amount,
                        'bsd_accepted_amount' => $accepted_amount,
                        'bsd_add_time' => $this->_date,
                    );
                } else {
                    $diffArr = array(
                        'bsb_id' => $bsb_id,
                        'bsbd_id' => $bsbd_id,
                        'bsd_status' => 3,
                        'bsd_note' => '数据匹配,自动完成',
                        'bsd_process' => 1,
                        'bsd_diff_type' => $bsd_diff_type,
                        'bsd_value' => $bsd_value,
                        'bsd_amount' => $bsd_amount,
                        'bsd_accepted_amount' => $accepted_amount,
                        'bsd_add_time' => $this->_date,
                        'bsd_verify_time' => $this->_date,
                        'bsd_process_time' => $this->_date,
                        'bsd_update_time' => $this->_date,
                    );
                    //完成明细
                    Service_BilServeBillDetail::update(array('bsbd_compare_sign' => 'y', 'bsbd_verifier_time' => $this->_date, 'bsbd_update_time' => $this->_date), $bsbd_id, 'bsbd_id');
                }
                if (!Service_BilServeBillDifference::add($diffArr)) {
                    throw new Exception('更新差异数据异常');
                }
            }

            $note = '';
            //判断是否已全部对帐
            $condition = array(
                'bsb_id' => $bsb_id,
                'bsbd_compare_sign_arr' => array('u', 'n'),
            );
            if (!Service_BilServeBillDetail::getByCondition($condition, 'count(*)')) {
                $note = "数据全部匹配,自动确认帐单";
                $bsbl_status_to = 2;
                $billUpArr['bsb_status'] = 2; //确认帐单
                $billUpArr['bsb_compare_bill_date_srart'] = $this->_date;
                $billUpArr['bsb_compare_bill_date_end'] = $this->_date;
                Service_BilServeBill::update($billUpArr, $bsb_id, 'bsb_id');
            }

            //日志
            $log = array(
                'bsb_id' => $bsb_id,
                'bsbl_status_from' => 1,
                'bsbl_status_to' => $bsbl_status_to,
                'bsbl_note' => $note,
                'bsbl_ip' => Common_Common::getIP(),
                'bsbl_creator_id' => $this->_userId,
                'bsbl_add_time' => $this->_date,
            );
            Table_BilServeBillLog::getInstance()->add($log);
			$db->commit();
		//	$db->rollBack();
			
            $result['state'] = 1;
            $result['message'] = array('操作成功');

        } catch (Exception $e) {
            $db->rollBack();
            $result['state'] = 0;
            $result['message'] = array($e->getMessage());
        }
        
        return $result;
    }


    /**
     * @desc 上传服务商帐单
     * @param array $param
     * @return array
     */
    public function deleteBillTransaction($param = array())
    {
        $result = array("state" => 0, "message" => array(), "code" => "");
        //事务处理
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            $code = $param['code'];
            $note = $param['note'];

            $result['code'] = $code;
            $billRow = Service_BilServeBill::getByField($code, 'bsb_code');
            if (empty($billRow)) {
                throw new Exception("帐单：" . $code . ' 不存在');
            }
            $billStatusArr = Process_BillConfig::bilServeBillStatus('auto');
            if (!in_array($billRow['bsb_status'], array(1, 2))) {
                throw new Exception("状态[" . $billStatusArr[$billRow['bsb_status']] . ']不允许操作');
            }

            Service_BilServeBill::update(array('bsb_status' => 0, 'bsb_update_time' => $this->_date, 'bsb_verifier' => $this->_userId, 'bsb_verifier_time' => $this->_date), $billRow['bsb_id'], 'bsb_id');

            //更新应付状态
            $sql = "UPDATE bil_serve_bill_detail_fee,bil_payment set bil_payment.bsbdf_id=0,bil_payment.bp_status=2 WHERE bil_serve_bill_detail_fee.bsbdf_id=bil_payment.bsbdf_id and bil_serve_bill_detail_fee.bsb_id={$billRow['bsb_id']}";
            $db->query($sql);

            //日志
            $log = array(
                'bsb_id' => $billRow['bsb_id'],
                'bsbl_status_from' => $billRow['bsb_status'],
                'bsbl_status_to' => 0,
                'bsbl_note' => $note,
                'bsbl_ip' => Common_Common::getIP(),
                'bsbl_creator_id' => $this->_userId,
                'bsbl_add_time' => $this->_date,
            );
            Table_BilServeBillLog::getInstance()->add($log);

            $db->commit();
            $result['state'] = 1;
            $result['message'] = array('操作成功');

        } catch (Exception $e) {
            $db->rollBack();
            $result['state'] = 0;
            $result['message'] = array($e->getMessage());
        }
        return $result;

    }

    /**
     * @desc 单票处理确认
     * @param array $param
     * @return array
     */
    public function confirmBillTransaction($param = array())
    {
        $result = array("state" => 0, "message" => '', "code" => "");
        //事务处理
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            $bsbd_id = $param['bsbd_id'];
            $proType = $param['proType'];
            $note = $param['note'];
            $amount = isset($param['amount']) ? $param['amount'] : '';
            $abnormalType = isset($param['abnormalType']) ? $param['abnormalType'] : 0;

            $row = Service_BilServeBillDifference::getByField($bsbd_id, 'bsbd_id');
            if (empty($row)) {
                throw new Exception('数据不存在');
            }

            //金额为空时，使用服务商金额
            $amount = $amount == '' ? $row['bsd_accepted_amount'] : $amount;

            $bdRow = Service_BilServeBillDetail::getByField($bsbd_id, 'bsbd_id');
            $result['code'] = empty($bdRow['bsbd_refer_hawb_code']) ? $bdRow['bsbd_hawb_code'] : $bdRow['bsbd_refer_hawb_code'];

            $billStatusArr = Process_BillConfig::serveBillDifferenceStatus('auto');
            if (!in_array($row['bsd_status'], array(0, 1, 2)) || ($row['bsd_status'] == '2' && $row['bsd_withdraw_sign'] == 'n')) {
                throw new Exception("状态[" . $billStatusArr[$row['bsd_status']] . ']不允许操作');
            }

            $billRow = Service_BilServeBill::getByField($row['bsb_id'], 'bsb_id');


            //更新帐单信息
            $billUpArr = array();
            if ($billRow['bsb_compare_bill_start'] == '0') {
                $billUpArr = array(
                    'bsb_compare_bill_start' => $this->_userId,
                    'bsb_compare_bill_date_srart' => $this->_date,
                    'bsb_update_time' => $this->_date,
                );
            }

            $billUpArr['bsb_compare_bill_end'] = $this->_userId;
            $billUpArr['bsb_compare_bill_date_end'] = $this->_date;

            $dfArrUp = array();
            $dfArrUp['bsd_note'] = $note;
            $dfArrUp['bsd_process'] = $proType;
            $dfArrUp['bsd_withdraw_sign'] = 'n';
            $dfArrUp['bsd_process_id'] = $this->_userId;
            $dfArrUp['bsd_process_time'] = $this->_date;

            $dfArrUp['bsd_abnormal_type'] = $abnormalType;
            switch ($proType) {
                case '1':
                    $dfArrUp['bsd_status'] = 2;
                    $dfArrUp['bsd_accepted_amount'] = $amount;
                    $bdArrUp = array(
                        'bsbd_verifier_id' => $this->_userId,
                        'bsbd_verifier_time' => $this->_date,
                    );
                    Service_BilServeBillDetail::update($bdArrUp, $row['bsbd_id'], 'bsbd_id');
                    break;
                case '2':
                    $dfArrUp['bsd_status'] = 1;
                    break;
                default:
                    throw new Exception("处理方式异常");
                    break;
            }

            Service_BilServeBillDifference::update($dfArrUp, $row['bsbd_id'], 'bsbd_id');
            Service_BilServeBill::update($billUpArr, $billRow['bsb_id'], 'bsb_id');
            $db->commit();
            $result['state'] = 1;
            $result['message'] = '操作成功';

        } catch (Exception $e) {
            $db->rollBack();
            $result['state'] = 0;
            $result['message'] = $e->getMessage();
        }
        return $result;
    }


    /**
     * @desc 单票处理服务商帐单
     * @param array $param
     * @return array
     */
    public function processBillTransaction($param = array())
    {
        $result = array("state" => 0, "message" => '', "code" => "");
        //事务处理
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            $bsbd_id = $param['bsbd_id'];
            $opType = $param['opType'];

            $row = Service_BilServeBillDifference::getByField($bsbd_id, 'bsbd_id');
            if (empty($row)) {
                throw new Exception('数据不存在');
            }
            $billStatusArr = Process_BillConfig::serveBillDifferenceStatus('auto');
            if ($row['bsd_status'] != '2') {
                throw new Exception("状态[" . $billStatusArr[$row['bsd_status']] . ']不允许操作');
            }
            $billDetailRow = Service_BilServeBillDetail::getByField($bsbd_id, 'bsbd_id');
            $result['code'] = !empty($billDetailRow['bsbd_hawb_code']) ? $billDetailRow['bsbd_hawb_code'] : $billDetailRow['bsbd_refer_hawb_code'];
            $billRow = Service_BilServeBill::getByField($row['bsb_id'], 'bsb_id');
            $dfArrUp['bsd_update_time'] = $this->_date;
            $bdArrUp['bsbd_update_time'] = $this->_date;

            $dfArrUp['bsd_verify_time'] = $this->_date;
            $dfArrUp['bsd_verifier_id'] = $this->_userId;
            $note = '审核单据:' . $result['code'];

            $billUpArr['bsb_status'] = $billRow['bsb_status'];
            switch ($opType) {
                case '1':
                    //通过
                    $bdArrUp['bsbd_compare_sign'] = 'y';
                    $dfArrUp['bsd_withdraw_sign'] = 'n';
                    $dfArrUp['bsd_status'] = 3;
                    Service_BilServeBillDetail::update($bdArrUp, $row['bsbd_id'], 'bsbd_id');
                    //更新实际金额
                    Service_BilServeBillDetailFee::update(array('bsbdf_amount' => $row['bsd_accepted_amount'], 'bsbdf_update_time' => $this->_date), $bsbd_id, 'bsbd_id');

                    $totalAmount = Table_BilServeBillDetailFee::getInstance()->getTotalAmount($billRow['bsb_id']);
                    $billUpArr['bsb_amount'] = $totalAmount;
                    $note .= " 总金额由" . $billUpArr['bsb_amount'] . '调整为' . $totalAmount;

                    $billUpArr['bsb_update_time'] = $this->_date;

                    //判断是否已全部对帐
                    $condition = array(
                        'bsb_id' => $row['bsb_id'],
                        'bsbd_compare_sign_arr' => array('u', 'n'),
                    );
                    if (!Service_BilServeBillDetail::getByCondition($condition, 'count(*)')) {
                        $billUpArr['bsb_status'] = 2; //确认帐单
                        $note = " 全部确认";
                    }
                    Service_BilServeBill::update($billUpArr, $billRow['bsb_id'], 'bsb_id');
                    break;
                case '2':
                    //驳回
                    $bdArrUp['bsbd_compare_sign'] = 'n';
                    $dfArrUp['bsd_withdraw_sign'] = 'y';
                    $dfArrUp['bsd_status'] = 2;
                    Service_BilServeBillDetail::update($bdArrUp, $row['bsbd_id'], 'bsbd_id');
                    break;
                default:
                    throw new Exception("处理方式异常");
                    break;
            }

            Service_BilServeBillDifference::update($dfArrUp, $row['bsbd_id'], 'bsbd_id');

            //日志
            $log = array(
                'bsb_id' => $billRow['bsb_id'],
                'bsbl_status_from' => $billRow['bsb_status'],
                'bsbl_status_to' => $billUpArr['bsb_status'],
                'bsbl_note' => $note,
                'bsbl_ip' => Common_Common::getIP(),
                'bsbl_creator_id' => $this->_userId,
                'bsbl_add_time' => $this->_date,
            );

            Table_BilServeBillLog::getInstance()->add($log);

            $db->commit();
            $result['state'] = 1;
            $result['message'] = '操作成功';

        } catch (Exception $e) {
            $db->rollBack();
            $result['state'] = 0;
            $result['message'] = $e->getMessage();
        }
        return $result;
    }

    /**
     * @desc 批量处理确认
     * @param array $param
     * @return array
     */
    public function batchConfirmBillTransaction($param = array())
    {
        $result = array("state" => 0, "message" => '', "code" => "");
        //事务处理
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            $bsd_id = $param['bsd_id'];
            $proType = $param['proType'];
            $note = $param['note'];
            $amount = $param['amount'];
            $abnormalType = $param['abnormalType'];

            $row = Service_BilServeBillDifference::getByField($bsd_id, 'bsd_id');
            if (empty($row)) {
                throw new Exception('数据不存在');
            }
            $billStatusArr = Process_BillConfig::serveBillDifferenceStatus('auto');
            if (!in_array($row['bsd_status'], array(0, 1, 2))) {
                throw new Exception("状态[" . $billStatusArr[$row['bsd_status']] . ']不允许操作');
            }

            $billRow = Service_BilServeBill::getByField($row['bsb_id'], 'bsb_id');

            //更新帐单信息
            $billUpArr = array();
            if ($billRow['bsb_compare_bill_start'] == '0') {
                $billUpArr = array(
                    'bsb_compare_bill_start' => $this->_userId,
                    'bsb_compare_bill_date_srart' => $this->_date,
                    'bsb_update_time' => $this->_date,
                );
            }

            $billUpArr['bsb_compare_bill_end'] = $this->_userId;
            $billUpArr['bsb_compare_bill_date_end'] = $this->_date;

            $dfArrUp = array();
            $dfArrUp['bsd_note'] = $note;
            $dfArrUp['bsd_process'] = $proType;
            $dfArrUp['bsd_withdraw_sign'] = 'n';
            $dfArrUp['bsd_process_id'] = $this->_userId;
            $dfArrUp['bsd_process_time'] = $this->_date;

            $dfArrUp['bsd_abnormal_type'] = $abnormalType;
            switch ($proType) {
                case '1':
                    $dfArrUp['bsd_status'] = 2;
                    $dfArrUp['bsd_accepted_amount'] = $amount;
                    $bdArrUp = array(
                        'bsbd_verifier_id' => $this->_userId,
                        'bsbd_verifier_time' => $this->_date,
                    );
                    Service_BilServeBillDetail::update($bdArrUp, $row['bsbd_id'], 'bsbd_id');
                    break;
                case '2':
                    $dfArrUp['bsd_status'] = 1;
                    break;
                default:
                    throw new Exception("处理方式异常");
                    break;
            }

            Service_BilServeBillDifference::update($dfArrUp, $row['bsd_id'], 'bsd_id');
            Service_BilServeBill::update($billUpArr, $billRow['bsb_id'], 'bsb_id');
            $db->commit();
            $result['state'] = 1;
            $result['message'] = '操作成功';

        } catch (Exception $e) {
            $db->rollBack();
            $result['state'] = 0;
            $result['message'] = $e->getMessage();
        }
        return $result;
    }


    /**
     * @desc 编辑帐单
     * @param array $param
     * @return array
     */
    public function editBillTransaction($param = array())
    {
        $result = array("state" => 0, "message" => '', "code" => "");
        //事务处理
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            if (!isset($param['bsb_id']) || empty($param['bsb_id'])) {
                throw new Exception("帐单不存在");
            }
            $bsbId = $param['bsb_id'];
            unset($param['bsb_id']);
            $billRow = Service_BilServeBill::getByField($bsbId, 'bsb_id');
            if (empty($billRow)) {
                throw new Exception("帐单不存在");
            }
            $note = '';
            $billStatusArr = Process_BillConfig::bilServeBillStatus('auto');
            if (!in_array($billRow['bsb_status'], array(1, 2))) {
                throw new Exception("状态[" . $billStatusArr[$billRow['bsb_status']] . ']不允许操作');
            }
            if ($param['sm_code'] != '') {
                $smRow = Service_ShippingMethod::getByField($param['sm_code'], 'sm_code');
                if ($smRow['sp_code'] != $billRow['sp_code']) {
                    throw new Exception("运输方式服务商与此帐单服务商不匹配");
                }
            }
            $param['bsb_update_time'] = $this->_date;
            Service_BilServeBill::update($param, $bsbId, 'bsb_id');

            if ($param['bsb_amount'] != $billRow['bsb_amount']) {
                $note .= " 金额由" . $billRow['bsb_amount'] . '调整为' . $param['bsb_amount'];
            }
            //日志
            $log = array(
                'bsb_id' => $billRow['bsb_id'],
                'bsbl_status_from' => $billRow['bsb_status'],
                'bsbl_status_to' => $billRow['bsb_status'],
                'bsbl_note' => '编辑帐单信息' . $note,
                'bsbl_ip' => Common_Common::getIP(),
                'bsbl_creator_id' => $this->_userId,
                'bsbl_add_time' => $this->_date,
            );
            Table_BilServeBillLog::getInstance()->add($log);

            $db->commit();
            $result['state'] = 1;
            $result['message'] = '操作成功';

        } catch (Exception $e) {
            $db->rollBack();
            $result['state'] = 0;
            $result['message'] = $e->getMessage();
        }
        return $result;
    }


    /**
     * @desc 审核帐单
     * @param array $param
     * @return array
     */
    public function verifyBillTransaction($param = array())
    {
        $result = array("state" => 0, "message" => '', "code" => "");
        //事务处理
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            if (!isset($param['bsb_code']) || empty($param['bsb_code'])) {
                throw new Exception("帐单不存在");
            }
            $bsb_code = $param['bsb_code'];
            $result['code'] = $bsb_code;
            $billRow = Service_BilServeBill::getByField($bsb_code, 'bsb_code');
            if (empty($billRow)) {
                throw new Exception("帐单不存在");
            }
            $note = '';
            $billStatusArr = Process_BillConfig::bilServeBillStatus('auto');
            if ($billRow['bsb_status'] != '2') {
                throw new Exception("状态[" . $billStatusArr[$billRow['bsb_status']] . '],不允许操作');
            }

            $upArr['bsb_status'] = 3;
            $upArr['bsb_update_time'] = $this->_date;
            $upArr['bsb_verifier'] = $this->_userId;
            $upArr['bsb_verifier_time'] = $this->_date;

            Service_BilServeBill::update($upArr, $billRow['bsb_id'], 'bsb_id');

            //日志
            $log = array(
                'bsb_id' => $billRow['bsb_id'],
                'bsbl_status_from' => $billRow['bsb_status'],
                'bsbl_status_to' => 3,
                'bsbl_note' => '审核帐单',
                'bsbl_ip' => Common_Common::getIP(),
                'bsbl_creator_id' => $this->_userId,
                'bsbl_add_time' => $this->_date,
            );
            Table_BilServeBillLog::getInstance()->add($log);

            $db->commit();
            $result['state'] = 1;
            $result['message'] = '操作成功';

        } catch (Exception $e) {
            $db->rollBack();
            $result['state'] = 0;
            $result['message'] = $e->getMessage();
        }
        return $result;
    }


    /**
     * @desc 根据帐单号进行核销帐单
     * @param array $param
     * @return array
     */
    public function writeOffBillTransaction($param = array())
    {
        $result = array("state" => 0, "message" => "", "data" => array());
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            $result = $this->writeOffBill($param);
            if (!isset($result['state']) || $result['state'] != '1') {
                throw new Exception($result['message']);
            }
            $db->commit();
        } catch (Exception $e) {
            $db->rollBack();
            $result['state'] = 0;
            $result['message'] = $e->getMessage();
        }
        return $result;
    }

    /**
     * @desc 根据帐单号进行核销帐单 非事务处理
     * @param array $param
     * @return array
     */
    public function writeOffBill($param = array())
    {
        $result = array("state" => 0, "message" => "", "data" => array());
        try {
            $apr_id = isset($param['apr_id']) ? $param['apr_id'] : '';
            $code = $param['code'];
            if ($code == '') {
                throw new Exception("单号不能为空");
            }
            $result['data']['code'] = $code;
            $result['data']['involvedAmount'] = 0;
            //获取帐单信息
            $billRow = Service_BilServeBill::getByField($code, 'bsb_code');
            if (empty($billRow)) {
                throw new Exception('不存在');
            }
            //状态
            $bilBillStatusArr = Process_BillConfig::bilServeBillStatus('auto');
            if (!in_array($billRow['bsb_status'], array(3, 4))) {
                throw new Exception("状态[" . ($bilBillStatusArr[$billRow['bsb_status']]) . '],不允许操作');
            }
            if ($billRow['bsb_writeoff_sign'] == 'y') {
                throw new Exception("帐单已核销");
            }

            $balanceArr = Table_AccountPaymentRecords::getInstance()->getTotal('sp', $billRow['sp_code'], 2);
            $amount = empty($balanceArr['amount']) || !isset($balanceArr['amount']) ? 0 : $balanceArr['amount'];
            $holdAmount = empty($balanceArr['writeoff_amount']) || !isset($balanceArr['writeoff_amount']) ? 0 : $balanceArr['writeoff_amount'];
            //当前可核销金额
            $balance = $amount - $holdAmount;

            //渐减
            $writeOffAmount = Table_BilServeBillBalanceRecords::getInstance()->getTotal($billRow['bsb_id']);

            //未核销金额
            $billAmount = $involvedAmount = $notWriteOffAmount = $billRow['bsb_amount'] - $writeOffAmount;
            //帐单核销状态
            $bcb_writeoff_sign = $billRow['bsb_writeoff_sign'];

            //根据付款记录,核销帐单
            $oCondition = array(
                'apr_type' => '2',
                'so_code' => 'sp',
                'payer_code' => $billRow['sp_code'],
                'apr_settle_sign' => 'y',
                'apr_writeoff_sign' => 'n',
                'apr_id' => $apr_id, //指定收款记录
            );
            $aprRows = Service_AccountPaymentRecords::getByCondition($oCondition, '*', 0, 0, array("apr_transaction_time asc"));

            if (empty($aprRows)) {
                throw new Exception("没有足够的余额");
            }

            foreach ($aprRows as $aRow) {
                $break = false;
                $aprAmount = $aRow['apr_amount'] - $aRow['apr_writeoff_amount'];
                //异常
                if (!$aprAmount) {
                    throw new Exception("金额异常");
                }

                //本次可以核销的金额
                $involvedAmount -= $aprAmount;

                if ($billAmount <= $aprAmount) {
                    $apr_writeoff_sign = $billAmount == $aprAmount ? 'y' : 'n';
                    $aprAmount = $billAmount;
                    $break = true;
                    //已扣完
                    $billAmount = 0;
                    $bcb_writeoff_sign = 'y';
                    $aprUpRow = array('apr_writeoff_amount' => ($aRow['apr_writeoff_amount'] + $aprAmount), 'apr_writeoff_sign' => $apr_writeoff_sign);

                } else {
                    $billAmount -= $aprAmount;
                    $bcb_writeoff_sign = 'p';
                    $aprUpRow = array('apr_writeoff_amount' => ($aRow['apr_writeoff_amount'] + $aprAmount), 'apr_writeoff_sign' => 'y');
                }

                //更新收款记录\增加已核销金额
                Service_AccountPaymentRecords::update($aprUpRow, $aRow['apr_id'], 'apr_id');

                //核销记录
                $balance -= $aprAmount;
                $brArr = array(
                    'bsbbr_amount' => $aprAmount,
                    'spir_id' => $aRow['apr_id'],
                    'bsb_id' => $billRow['bsb_id'],
                    'bsbbr_surplus_amount' => $balance,
                    'bsbbr_creator_id' => $this->_userId,
                    'bsbbr_add_time' => $this->_date,
                );
                Service_BilServeBillBalanceRecords::add($brArr);

                if ($break) {
                    break;
                }
            }

            //已全部核销转为已完结
            $statusTo = $bcb_writeoff_sign == 'y' ? 4 : 3;

            $upRow = array(
                'bsb_status' => $statusTo,
                'bsb_writeoff_sign' => $bcb_writeoff_sign,
                'bsb_writeoff_sign_time' => $this->_date,
                'bsb_update_time' => $this->_date,
            );
            Service_BilServeBill::update($upRow, $billRow['bsb_id'], 'bsb_id');

            //帐单日志
            $log = array(
                'bsb_id' => $billRow['bsb_id'],
                'bsbl_status_from' => $billRow['bsb_status'],
                'bsbl_status_to' => $statusTo,
                'bsbl_note' => "核销金额:" . ($involvedAmount < 0 ? $notWriteOffAmount : $notWriteOffAmount - $involvedAmount),
                'bsbl_ip' => Common_Common::getIP(),
                'bsbl_creator_id' => $this->_userId,
                'bsbl_add_time' => $this->_date,
            );
            Service_BilServeBillLog::add($log);

            $result['data']['involvedAmount'] = ($involvedAmount < 0 ? $notWriteOffAmount : $notWriteOffAmount - $involvedAmount);
            $result['state'] = 1;
            $result['message'] = "操作成功";
        } catch (Exception $e) {
            $result['state'] = 0;
            $result['message'] = $e->getMessage();
        }
        return $result;
    }


    public static function getImportData($code = '', $condition = array('id_id' => -1), $pageSize = 100, $page = 1)
    {
        $columnMap = Process_ImportDataProcess::columnMap($code);
        $columnMapKey = array_flip($columnMap);
        $rows = Table_ImportDataDetailFormat::getInstance()->getGroupByCondition($condition, array('id_id', 'iddf_rowno'), $pageSize, $page, array("id_id"));
        $data = array();
        foreach ($rows as $key => $row) {
            $list = Service_ImportDataDetailFormat::getByCondition(array('id_id' => $row['id_id'], 'iddf_rowno' => $row['iddf_rowno']), '*', 0, 0, array('iddf_rowno asc'));
            foreach ($list as $ro) {
                if (isset($columnMapKey[$ro['iddf_code']])) {
                    $data[$key][$ro['iddf_code']] = $ro['iddf_value'];
                }
            }
        }
        $newData = array();
        foreach ($data as $key => $val) {
            $newData[$val['date'] . '_' . $key] = $val;
        }
        unset($data, $rows);
        sort($newData);
        return $newData;
    }

    /**
     * @desc 生成服务商帐单
     * @param array $param
     * @return array
     */
    public function createBillTransaction($param = array())
    {
        $result = array("state" => 0, "message" => array(), "code" => "");
        //事务处理
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            $bsbl_status_to = 1;
            $id = $param['id_id'];
            $idRow = Service_ImportData::getByField($id, 'id_id');
            if (empty($idRow)) {
                throw new Exception("没有找到数据");
            }
            if (!in_array($idRow['id_status'], array(0, 1))) {
                throw new Exception("数据状态异常");
            }
            $billArr = array(
                'sp_code' => $idRow['payer_code'],
                'bsb_amount' => $param['bsb_amount'],
                'id_code' => $idRow['id_code'],
                'bsb_start_time' => $idRow['id_start_time'],
                'bsb_end_time' => $idRow['id_end_time'],
                'currency_code' => $param['currency_code'],
                'currency_rate' => $param['currency_rate'],
                'bsb_note' => $param['note'],
                'sm_code' => $idRow['sm_code'],
                'bsb_no' => $idRow['id_reference_no'],
                'bsb_bank_account' => isset($param['bsb_bank_account']) ? $param['bsb_bank_account'] : '',
            );

            $billArr['bsb_code'] = Common_GetNumbers::getCode('serviceBillNo', '', 'CS');
            $billArr['bsb_mode'] = 1;
            $billArr['bsb_creator_id'] = $this->_userId;
            $billArr['bsb_add_time'] = $this->_date;
            $billArr['bsb_status'] = 1;
            $billArr['bsb_quantity'] = 0;
            $billArr['bsb_payment_total'] = $param['bsb_amount'];
            $billArr['bsb_charge_weight_total'] = 0;
            
            if (!$bsb_id = Service_BilServeBill::add($billArr)) {
                throw new Exception("建立帐单错误");
            }

            //期初
            $surplusArr = array(
                'bsb_id' => $bsb_id,
                'bsbs_update_time' => $this->_date,
            );
            Service_BilServeBillSurplus::add($surplusArr);

            $data = self::getImportData($idRow['id_code'], array('id_id' => $id));
            $feeTypeArr = array();
            //明细
            foreach ($data as $k => $row) {
            	
                $bsd_diff_type = 0;
                $bsd_value = 0;
                $bsd_amount = 0;
                $accepted_amount = $row['amount'];
                $myAmount = 0;

                $detailArr = array(
                    'customer_code' => '',
                    'bsb_id' => $bsb_id,
                    'bsbd_hawb_code' => (isset($row['code']) ? $row['code'] : ''),
                    'bsbd_refer_hawb_code' => '',
                    'bsbd_shipment_time' => $row['date'],
                    'bsbd_charge_weight' => 0,
                    'bsbd_pieces' => (isset($row['quantity']) ? $row['quantity'] : ''),
                    'bsbd_delivered_weight' => 0,
                    'bsbd_add_time' => $this->_date,
                );
                if (!$bsbd_id = Service_BilServeBillDetail::add($detailArr)) {
                    throw new Exception("建立帐单明细错误");
                }
                //重量差异
                /*
                  if ($row['weight'] > $row['delivered_weight']) {
                      $bsd_diff_type = 1;
                      $bsd_value = abs($row['weight'] - $row['delivered_weight']);
                  }
                 */
                //明细费用(支持多条)
                if (!isset($feeTypeArr[$row['feeType']])) {
                    $ftRow = Service_FeeType::getByField($row['feeType'], 'ft_name_cn');
                    $feeTypeArr[$row['feeType']] = isset($ftRow['ft_code']) ? $ftRow['ft_code'] : '';
                }

                $detailFeeArr = array(
                    'bsbd_id' => $bsbd_id,
                    'bsb_id' => $bsb_id,
                    'ft_code' => $feeTypeArr[$row['feeType']],
                    'bsbdf_amount' => $row['amount'],
                );
                
                if (!$bsbdf_id = Service_BilServeBillDetailFee::add($detailFeeArr)) {
                    throw new Exception("建立帐单明细费用错误");
                }
                
                //业务
                $condition = array(
                    'id_id' => $id,
                    'bp_status' => 2, //已审核
					'ft_code' => $detailFeeArr['ft_code'],
                    'bp_chargeable_time_lt' => date("Y-m-d 23:59:59", strtotime($row['date'])),
                    //  'bb_refer_code' => (isset($row['code']) ? $row['code'] : ''),//如果有单号
                );
                $code = (isset($row['code']) ? $row['code'] : '');
                if (!empty($code)) {
                    $condition['bb_service_number_arr'] = array($code, '');
                }
                
                $payRows = Table_BilPayment::getInstance()->getPaymentListCondition($condition, '*', 0);
                if (!empty($payRows)) {
                    $bbArr = array();
                    foreach ($payRows as $pRow) {
                        $myAmount += $pRow['bp_amount'];
                        if (!isset($bbArr[$pRow['bb_id']])) {
                            $bbArr[$pRow['bb_id']] = $pRow['bb_id'];
                            Service_BilBusiness::update(array('bb_bill_compare_sign' => 'y', 'bb_update_time' => $this->_date), $pRow['bb_id'], 'bb_id');
                        }
                        Table_BilPayment::getInstance()->update(array('bsbdf_id' => $bsbdf_id, 'bp_status' => 3, 'bp_update_time' => $this->_date), $pRow['bp_id'], 'bp_id');
                    }
                    //金额差异
                    if ($row['amount'] != $myAmount) {
                        $bsd_diff_type = 2;
                        $bsd_amount = abs($row['amount'] - $myAmount);
                    }

                } else {
                    //未匹配业务
                    $bsd_amount = $row['amount'];
                    $bsd_diff_type = 3;
                }

                //异常情况
                if ($bsd_diff_type != '0') {
                    $diffArr = array(
                        'bsb_id' => $bsb_id,
                        'bsbd_id' => $bsbd_id,
                        'bsd_diff_type' => $bsd_diff_type,
                        'bsd_value' => $bsd_value,
                        'bsd_amount' => $bsd_amount,
                        'bsd_accepted_amount' => $accepted_amount,
                        'bsd_add_time' => $this->_date,
                    );
                } else {
                    $diffArr = array(
                        'bsb_id' => $bsb_id,
                        'bsbd_id' => $bsbd_id,
                        'bsd_status' => 3,
                        'bsd_note' => '数据匹配,自动完成',
                        'bsd_process' => 1,
                        'bsd_diff_type' => $bsd_diff_type,
                        'bsd_value' => $bsd_value,
                        'bsd_amount' => $bsd_amount,
                        'bsd_accepted_amount' => $accepted_amount,
                        'bsd_add_time' => $this->_date,
                        'bsd_verify_time' => $this->_date,
                        'bsd_process_time' => $this->_date,
                        'bsd_update_time' => $this->_date,
                    );
                    //完成明细
                    Service_BilServeBillDetail::update(array('bsbd_compare_sign' => 'y', 'bsbd_verifier_time' => $this->_date, 'bsbd_update_time' => $this->_date), $bsbd_id, 'bsbd_id');
                }
                //数据对比结果
                if (!Service_BilServeBillDifference::add($diffArr)) {
                    throw new Exception('更新差异数据异常');
                }

            }
            $note = '';
            //判断是否已全部对帐
            $condition = array(
                'bsb_id' => $bsb_id,
                'bsbd_compare_sign_arr' => array('u', 'n'),
            );
            if (!Service_BilServeBillDetail::getByCondition($condition, 'count(*)')) {
                $note = "数据全部匹配,自动确认帐单";
                $bsbl_status_to = 2;
                $billUpArr['bsb_status'] = 2; //确认帐单
                $billUpArr['bsb_compare_bill_date_srart'] = $this->_date;
                $billUpArr['bsb_compare_bill_date_end'] = $this->_date;
                Service_BilServeBill::update($billUpArr, $bsb_id, 'bsb_id');
            }


            //日志
            $log = array(
                'bsb_id' => $bsb_id,
                'bsbl_status_from' => 1,
                'bsbl_status_to' => $bsbl_status_to,
                'bsbl_note' => $note,
                'bsbl_ip' => Common_Common::getIP(),
                'bsbl_creator_id' => $this->_userId,
                'bsbl_add_time' => $this->_date,
            );
            Table_BilServeBillLog::getInstance()->add($log);

            //数据状态
            $idUpArr = array('id_status' => 2, 'id_finish_id' => $this->_userId,
                'id_finish_time' => $this->_date,
                'id_update_time' => $this->_date,
            );
            Service_ImportData::update($idUpArr, $id, 'id_id');
            Service_ImportDataDetail::delete($id, 'id_id');
		//	$db->rollBack();
			$db->commit();
            $result['state'] = 1;
            $result['message'] = array('操作成功');

        } catch (Exception $e) {
            $db->rollBack();
            $result['state'] = 0;
            $result['message'] = array($e->getMessage());
        }
        return $result;

    }


}