<?php

/**
 * @desc 业务处理类
 */
class Process_Business
{
    protected $_date = "";
    protected $_userId = "";
    protected $_bb_id = ""; //业务ID
    protected $_businessArr = array();

    public function __construct()
    {
        $this->_userId = Service_User::getUserId();
        $this->_date = date('Y-m-d H:i:s');
    }

    /**
     * @desc 当业务产生新应收费用时，是否需要审核
     * @return int 0:不需要审核  1:需要审核
     */
    public static function businessIncomeFeeConfig()
    {
        return 0;
    }

    /**
     * @desc 当业务产生新应付费用时，是否需要审核
     * @return int 0:不需要审核  1:需要审核
     */
    public static function businessPaymentFeeConfig()
    {
        return 1;
    }

    /**
     * @desc 什么状态下费用可编辑、删除
     * @return array
     */
    public static function editBusinessIncomeFeeConfig()
    {
        return array(1, 2);
    }


    /**
     * @desc 服务商非逻辑，当业务产生新应收费用时，是否需要审核
     * @return int 0:不需要审核  1:需要审核
     */
    public static function incomeFeeConfig()
    {
        return 0;
    }

    /**
     * @desc 服务商非逻辑费用，什么状态下费用可编辑、删除
     * @return array
     */
    public static function editBusinessPaymentFeeConfig()
    {
        return array(1);
    }

    /**
     * @desc 支持重新计费类型
     * @return array
     */
    public static function readjustment()
    {
        return array("so" => '订单');
    }

    /**
     * @desc 获取业务单号
     * @param string $customerCode
     * @return string
     */
    public static function getBusinessReferNo($customerCode = '')
    {
        return Common_GetNumber::getCode('otherFee', $customerCode, 'OT');

    }

    /**
     * @param $param
     * @return mixed
     * @throws Exception
     */
    private function editBusinessFeeValidation($param)
    {
        if (!isset($param['customer_code']) || $param['customer_code'] == '') {
            throw new Exception("客户代码不能为空");
        }
        if ($param['amount'] == '' || !is_numeric($param['amount']) || $param['amount'] <= 0) {
            throw new Exception("金额异常");
        }
        if ($param['currency_code'] == '') {
            throw new Exception("币种不能为空");
        }
        if (!in_array($param['rp_type'], array('0', '1'))) {
            throw new Exception("收付类型异常");
        }
        return $param;
    }

    /**
     * @desc 新增(编辑)业务费用(非逻辑)
     * @param array $param
     * @return array
     */
    public function editBusinessFeeTransaction($param = array())
    {
        $result = array("state" => 0, "message" => "", "data" => array());

        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            $this->editBusinessFeeValidation($param);

            $customerCode = $param['customer_code'];
            $type = $param['rp_type'];
            $amount = abs($param['amount']);
            $currency_code = $param['currency_code'];
            $note = $param['note'];
            $bi_id = $param['bi_id'];
            $bt_code = $param['bt_code'];
            $charge_time = (!isset($param['charge_time']) || empty($param['charge_time']) ? $this->_date : $param['charge_time']);

            $row = Service_Customer::getByField($customerCode, 'customer_code');
            if (empty($row)) {
                throw new Exception("客户代码：" . $customerCode . "不存在");
            }

            //编辑时
            if (!empty($bi_id)) {
                $bilIncomeRow = Service_BilIncome::getByField($bi_id, 'bi_id');
                if (empty($bilIncomeRow)) {
                    throw new Exception("没有找到匹配的数据");
                } elseif (!in_array($bilIncomeRow['bi_status'], self::editBusinessIncomeFeeConfig())) {
                    $bilIncomeStatusArr = Process_BillConfig::bilIncomeStatus('auto');
                    throw new Exception("状态为[" . $bilIncomeStatusArr[$bilIncomeRow['bi_status']] . '],不允许操作');
                }
                //更新业务表
                $businessForUp = array();
                $businessArr = Service_BilBusiness::getAttrByField($bilIncomeRow['bb_id'], 'bb_id');
                if (strtolower($businessArr['bb_status']) == 'n') {
                    throw new Exception("此业务费用已作废,不允许操作");
                }
                $businessForUp['bb_charge_time'] = $charge_time;
                $businessForUp['bb_declared_time'] = $charge_time;
                if (strtolower($businessArr['bt_code']) != strtolower($bt_code)) {
                    $businessForUp['bt_code'] = strtoupper($bt_code);
                }

                $code = $businessArr['bb_refer_code'];

                //转为客户币种
                $cArr = Process_Financial::changeCurrency($amount, $currency_code, $row['customer_currency']);
                if (!is_array($cArr)) {
                    throw new Exception($cArr);
                }
                //按状态判断 是否需要回退原费用
                if ($bilIncomeRow['bi_status'] == '2') {
                    //回退
                    $fee = array(); //置空
                    $fee[] = array(
                        'cbl_type' => $bilIncomeRow['bi_rp_type'] == '0' ? 3 : 2, //反向退回
                        'cbl_value' => abs($bilIncomeRow['bi_amount']),
                        'currency_code' => $row['customer_currency'], //汇率问题暂时不处理
                        'release_value' => '0',
                        'currency_rate' => '',
                        'user_id' => $this->_userId,
                        'cbl_refer_code' => $businessArr['bb_refer_code'],
                        'application_code' => 'edit fee',
                        'fee_id' => '0',
                        'cbl_note' => '费用调整，回退费用'
                    );

                    //新费用
                    $fee[] = array(
                        'cbl_type' => ($type == '0' ? 2 : 3), //类型
                        'cbl_value' => abs($cArr['value']),
                        'currency_code' => $row['customer_currency'], //
                        'release_value' => '0',
                        'currency_rate' => '',
                        'user_id' => $this->_userId,
                        'cbl_refer_code' => $businessArr['bb_refer_code'],
                        'application_code' => 'edit fee',
                        'fee_id' => '0',
                        'cbl_note' => $note
                    );
                    $feeObj = new Common_CustomerFeeProcess();
                    $feeReturn = $feeObj->payment($customerCode, $fee, 1); //强制扣款
                    if ($feeReturn['state'] != '1') {
                        throw new Exception(isset($feeReturn['message']) ? $feeReturn['message'] : 'Payment Fee Fail.');
                    }
                }

                //应收表更新
                $biUpArr = array(
                    'bi_amount' => ($type == '0' ? $cArr['value'] : $cArr['value'] * -1),
                    'bi_org_amount' => ($type == '0' ? $amount : $amount * -1),
                    'currency_code' => $currency_code,
                    'currency_rate' => $cArr['org_rate'],
                    'bi_rp_type' => $type,
                    'bi_note' => $note,
                    'bi_withdraw_sign' => 'n', //是否回退
                    'bi_creator_id' => $this->_userId,
                    'bi_verifier_id' => $this->_userId,
                    'bi_verify_time' => $this->_date,
                    'bi_update_time' => $this->_date,
                    'bi_chargeable_time' => $charge_time,
                );
                Service_BilIncome::update($biUpArr, $bilIncomeRow['bi_id'], 'bi_id');


                //业务更新
                if (!empty($businessForUp)) {
                    $businessForUp['bb_update_time'] = $this->_date;
                    Service_BilBusiness::update($businessForUp, $businessArr['bb_id'], 'bb_id');
                }

            } else {
                //写入业务主表
                $businessArr = array(
                    'bt_code' => strtoupper($param['bt_code']),
                    'ds_code' => 'ot', //非逻辑
                    'customer_code' => $row['customer_code'],
                    'warehouse_id' => (isset($param['warehouse_id']) ? $param['warehouse_id'] : 0),
                    'sm_code' => (isset($param['sm_code']) ? $param['sm_code'] : ''),
                    'bb_charge_time' => $charge_time,
                    'bb_declared_time' => $charge_time,
                    'bb_sales_id' => $row['customer_saler_user_id'], //销售员
                    'bb_charge_sign' => 'y',
                    'bb_balance_sign' => 'y',
                    'bb_add_time' => $this->_date,
                );
                if (!$bb_id = Service_BilBusiness::add($businessArr)) {
                    throw new Exception("写入业务数据异常");
                }
                //附加表
                $code = self::getBusinessReferNo($customerCode);
                if ($code == '') {
                    throw new Exception("无法获取业务单号");
                }
                $attachArr = array(
                    'bb_id' => $bb_id,
                    'bb_refer_code' => $code,
                );
                if (!Service_BilBusinessAttach::add($attachArr)) {
                    throw new Exception("写入业务附加数据异常");
                }

                //按收付类型添加费用
                $config = $type == '0' ? self::businessIncomeFeeConfig() : self::businessPaymentFeeConfig();
                //转为客户币种
                $cArr = Process_Financial::changeCurrency($amount, $currency_code, $row['customer_currency']);
                if (!is_array($cArr)) {
                    throw new Exception($cArr);
                }
                $feeArr = array(
                    'bb_id' => $bb_id,
                    'customer_code' => $row['customer_code'],
                    'ft_code' => (isset($param['ft_code']) ? $param['ft_code'] : ''),
                    'sm_code' => (isset($param['sm_code']) ? $param['sm_code'] : ''),
                    'bi_creator_id' => (isset($param['bi_creator_id']) ? $param['bi_creator_id'] : $this->_userId),
                    'bi_amount' => ($type == '0' ? $cArr['value'] : $cArr['value'] * -1),
                    'bi_org_amount' => ($type == '0' ? $amount : $amount * -1),
                    'bi_note' => $note,
                    'bi_create_type' => 1,
                    'bi_rp_type' => $type,
                    'currency_code' => $currency_code,
                    'currency_rate' => $cArr['org_rate'],
                    'bi_add_time' => $this->_date,
                    'bi_chargeable_time' => $charge_time,
                );
                //当不需要审核时，费用直接扣除
                if ($config == '0') {
                    $feeArr['bi_status'] = 2; //直接审核\并体现余额
                    $feeArr['bi_balance_sign'] = 'y';
                    $feeArr['bi_verifier_id'] = (isset($param['bi_verifier_id']) ? $param['bi_verifier_id'] : $this->_userId);
                    $feeArr['bi_verify_time'] = (isset($param['bi_verify_time']) ? $param['bi_verify_time'] : $this->_date);
                    //操作余额
                    $fee[] = array(
	                        'cbl_type' => ($type == '0' ? 2 : 3), //类型
	                        'cbl_value' => abs($cArr['value']),
	                        'currency_code' => $row['customer_currency'], 
	                        //解冻金额为扣款金额
                    		'release_value' => abs($cArr['value']),
						//	'release_value' => '0',
	                        'currency_rate' => '',
	                        'user_id' => $this->_userId,
	                        'cbl_refer_code' => $code,
	                        'application_code' => 'add',
	                        'fee_id' => '0',
	                        'cbl_note' => $note
                    );
                    $feeObj = new Common_CustomerFeeProcess();
                    $feeReturn = $feeObj->payment($customerCode, $fee, 1); //强制扣款
                    if ($feeReturn['state'] != '1') {
                        throw new Exception(isset($feeReturn['message']) ? $feeReturn['message'] : 'Payment Fee Fail.');
                    }
                } else {
                    $feeArr['bi_balance_sign'] = 'n'; //未支付
                    $feeArr['bi_status'] = 1; //确认状态
                }
                if (!Service_BilIncome::add($feeArr)) {
                    throw new Exception("写入业务费用异常");
                }
            }

            $db->commit();
            $result['state'] = 1;
            $result['message'] = '操作成功';
            $result['code'] = $code;
        } catch (Exception $e) {
            $db->rollBack();
            $result['state'] = 0;
            $result['message'] = $e->getMessage();
        }
        return $result;
    }

    /**
     * @desc 新增业务费用(非逻辑)
     * @tips 用于批量上传
     * @param array $param
     * @throws Exception
     */
    private function addBusinessFee($param = array())
    {
        $this->editBusinessFeeValidation($param);

        $customerCode = $param['customer_code'];
        $type = $param['rp_type'];
        $amount = $param['amount'];
        $currency_code = $param['currency_code'];
        $note = $param['note'];
        $bi_chargeable_time =$param['bi_chargeable_time'];

        $row = Service_Customer::getByField($customerCode, 'customer_code');
        if (empty($row)) {
            throw new Exception("客户代码：" . $customerCode . "不存在");
        }

        //写入业务主表
        $businessArr = array(
            'bt_code' => strtoupper($param['bt_code']),
            'ds_code' => 'ot', //非逻辑
            'customer_code' => $row['customer_code'],
            'warehouse_id' => (isset($param['warehouse_id']) ? $param['warehouse_id'] : 0),
            'sm_code' => (isset($param['sm_code']) ? $param['sm_code'] : ''),
            'bb_charge_time' => (!isset($param['bb_charge_time']) || empty($param['bb_charge_time']) ? $this->_date : $param['bb_charge_time']),
            'bb_declared_time' => (!isset($param['bb_declared_time']) || empty($param['bb_declared_time']) ? $this->_date : $param['bb_declared_time']),
            'bb_sales_id' => $row['customer_saler_user_id'], //销售员
            'bb_charge_sign' => 'y',
            'bb_balance_sign' => 'y',
            'bb_add_time' => $this->_date,
        );
        if (!$bb_id = Service_BilBusiness::add($businessArr)) {
            throw new Exception("写入业务数据异常");
        }
        //附加表
        $code = self::getBusinessReferNo($customerCode);
        if ($code == '') {
            throw new Exception("无法获取业务单号");
        }
        $attachArr = array(
            'bb_id' => $bb_id,
            'bb_refer_code' => $code,
        );
        if (!Service_BilBusinessAttach::add($attachArr)) {
            throw new Exception("写入业务附加数据异常");
        }

        //按收付类型添加费用
        $config = $type == '0' ? self::businessIncomeFeeConfig() : self::businessPaymentFeeConfig();
        //转为客户币种
        $cArr = Process_Financial::changeCurrency($amount, $currency_code, $row['customer_currency']);
        if (!is_array($cArr)) {
            throw new Exception($cArr);
        }
        $feeArr = array(
            'bb_id' => $bb_id,
            'customer_code' => $row['customer_code'],
            'ft_code' => (isset($param['ft_code']) ? $param['ft_code'] : ''),
            'sm_code' => (isset($param['sm_code']) ? $param['sm_code'] : ''),
            'bi_creator_id' => (isset($param['bi_creator_id']) ? $param['bi_creator_id'] : $this->_userId),
            'bi_amount' => ($type == '0' ? $cArr['value'] : $cArr['value'] * -1),
            'bi_org_amount' => ($type == '0' ? $amount : $amount * -1),
            'bi_note' => $note,
            'bi_create_type' => 1,
            'bi_rp_type' => $type,
            'currency_code' => $currency_code,
            'currency_rate' => $cArr['org_rate'],
            'bi_add_time' => $this->_date,
            'bi_chargeable_time' => $bi_chargeable_time,
        );
        //当不需要审核时，费用直接扣除
        if ($config == '0') {
            $feeArr['bi_status'] = 2; //直接审核\并体现余额
            $feeArr['bi_balance_sign'] = 'y';
            $feeArr['bi_verifier_id'] = (isset($param['bi_verifier_id']) ? $param['bi_verifier_id'] : $this->_userId);
            $feeArr['bi_verify_time'] = (isset($param['bi_verify_time']) ? $param['bi_verify_time'] : $this->_date);
            //操作余额
            $fee[] = array(
                'cbl_type' => ($type == '0' ? 2 : 3), //类型
                'cbl_value' => abs($cArr['value']),
                'currency_code' => $row['customer_currency'], //
                'release_value' => '0',
                'currency_rate' => '',
                'user_id' => $this->_userId,
                'cbl_refer_code' => $code,
                'application_code' => 'add',
                'fee_id' => '0',
                'cbl_note' => $note
            );
            $feeObj = new Common_CustomerFeeProcess();
            $feeReturn = $feeObj->payment($customerCode, $fee, 1); //强制扣款
            if ($feeReturn['state'] != '1') {
                throw new Exception(isset($feeReturn['message']) ? $feeReturn['message'] : 'Payment Fee Fail.');
            }
        } else {
            $feeArr['bi_balance_sign'] = 'n'; //未支付
            $feeArr['bi_status'] = 1; //确认状态
        }
        if (!Service_BilIncome::add($feeArr)) {
            throw new Exception("写入业务费用异常");
        }

    }


    /**
     * @desc 删除业务费用(非逻辑)
     * @param array $param
     * @return array
     */
    public function clearBusinessFeeTransaction($param = array())
    {
        $result = array("state" => 0, "message" => "", "code" => '', "amount" => 0);

        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            $note = $param['note'];
            $bi_id = $param['bi_id'];

            $bilIncomeRow = Service_BilIncome::getByField($bi_id, 'bi_id');
            if (empty($bilIncomeRow)) {
                throw new Exception("没有找到匹配的数据");
            }
            //更新业务表
            $businessForUp = array();
            $businessArr = Service_BilBusiness::getAttrByField($bilIncomeRow['bb_id'], 'bb_id');

            $result['code'] = $businessArr['bb_refer_code'];
            $result['amount'] = $bilIncomeRow['bi_amount'];

            if (!in_array($bilIncomeRow['bi_status'], self::editBusinessIncomeFeeConfig())) {
                $bilIncomeStatusArr = Process_BillConfig::bilIncomeStatus('auto');
                throw new Exception("状态为[" . $bilIncomeStatusArr[$bilIncomeRow['bi_status']] . '],不允许操作');
            }
            if (strtolower($businessArr['bb_status']) == 'n') {
                throw new Exception("此业务费用已作废,不允许操作");
            }
            //获取客户币种
            $row = Service_Customer::getByField($bilIncomeRow['customer_code'], 'customer_code', array("customer_currency"));

            if ($bilIncomeRow['bi_status'] == '2') {
                //回退
                $fee = array(); //置空
                $fee[] = array(
                    'cbl_type' => $bilIncomeRow['bi_rp_type'] == '0' ? 3 : 2, //反向退回
                    'cbl_value' => abs($bilIncomeRow['bi_amount']),
                    'currency_code' => $row['customer_currency'], //汇率问题暂时不处理
                    'release_value' => '0',
                    'currency_rate' => '',
                    'user_id' => $this->_userId,
                    'cbl_refer_code' => $businessArr['bb_refer_code'],
                    'application_code' => 'delete_fee',
                    'fee_id' => '0',
                    'cbl_note' => '回退费用'
                );
                $feeObj = new Common_CustomerFeeProcess();
                $feeReturn = $feeObj->payment($bilIncomeRow['customer_code'], $fee, 1); //强制扣款
                if ($feeReturn['state'] != '1') {
                    throw new Exception(isset($feeReturn['message']) ? $feeReturn['message'] : 'Payment Fee Fail.');
                }
            }
            //应收表
            $biUpArr = array(
                'bi_status' => 0,
                'bi_note' => $note,
                'bi_update_time' => $this->_date,
                'bi_verifier_id' => $this->_userId,
                'bi_verify_time' => $this->_date,
            );
            Service_BilIncome::update($biUpArr, $bilIncomeRow['bi_id'], 'bi_id');

            //作废业务表单据
            $businessForUp['bb_status'] = 'n';
            $businessForUp['bb_update_time'] = $this->_date;
            Service_BilBusiness::update($businessForUp, $businessArr['bb_id'], 'bb_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 deleteBusinessFeeTransaction($param = array())
    {
        $result = array("state" => 0, "message" => "", "code" => '', "amount" => 0);

        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {

            $bi_id = $param['bi_id'];
            $note = isset($param['note']) ? $param['note'] : '';

            $bilIncomeRow = Service_BilIncome::getByField($bi_id, 'bi_id');
            if (empty($bilIncomeRow)) {
                throw new Exception("没有找到匹配的数据");
            }
            //更新业务表
            $businessForUp = array();
            $businessArr = Service_BilBusiness::getAttrByField($bilIncomeRow['bb_id'], 'bb_id');

            $result['code'] = $businessArr['bb_refer_code'];
            $result['amount'] = $bilIncomeRow['bi_amount'];

            if (!in_array($bilIncomeRow['bi_status'], self::editBusinessIncomeFeeConfig())) {
                $bilIncomeStatusArr = Process_BillConfig::bilIncomeStatus('auto');
                throw new Exception("状态为[" . $bilIncomeStatusArr[$bilIncomeRow['bi_status']] . '],不允许操作');
            }
            if (strtolower($businessArr['bb_status']) == 'n') {
                throw new Exception("此业务费用已作废,不允许操作");
            }
            //获取客户币种
            $row = Service_Customer::getByField($bilIncomeRow['customer_code'], 'customer_code', array("customer_currency"));

            if ($bilIncomeRow['bi_status'] == '2') {
                //回退
                $fee = array(); //置空
                $fee[] = array(
                    'cbl_type' => $bilIncomeRow['bi_rp_type'] == '0' ? 3 : 2, //反向退回
                    'cbl_value' => abs($bilIncomeRow['bi_amount']),
                    'currency_code' => $row['customer_currency'], //汇率问题暂时不处理
                    'release_value' => '0',
                    'currency_rate' => '',
                    'user_id' => $this->_userId,
                    'cbl_refer_code' => $businessArr['bb_refer_code'],
                    'application_code' => 'delete_fee',
                    'fee_id' => '0',
                    'cbl_note' => '回退费用'
                );
                $feeObj = new Common_CustomerFeeProcess();
                $feeReturn = $feeObj->payment($bilIncomeRow['customer_code'], $fee, 1); //强制扣款
                if ($feeReturn['state'] != '1') {
                    throw new Exception(isset($feeReturn['message']) ? $feeReturn['message'] : 'Payment Fee Fail.');
                }
            }

            if (strtolower($businessArr['ds_code']) == 'ot') {
                //删除数据
                Service_BilIncome::delete($bilIncomeRow['bi_id'], 'bi_id');
                Service_BilBusiness::delete($businessArr['bb_id'], 'bb_id');
                Service_BilBusinessAttach::delete($businessArr['bb_id'], 'bb_id');
            } else {
                //应收表
                $biUpArr = array(
                    'bi_status' => 0,
                    'bi_note' => $note,
                    'bi_update_time' => $this->_date,
                    'bi_verifier_id' => $this->_userId,
                    'bi_verify_time' => $this->_date,
                );
                Service_BilIncome::update($biUpArr, $bilIncomeRow['bi_id'], 'bi_id');
                //作废业务表单据
                $businessForUp['bb_status'] = 'n';
                $businessForUp['bb_update_time'] = $this->_date;
                Service_BilBusiness::update($businessForUp, $businessArr['bb_id'], 'bb_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 verifyBusinessFeeTransaction($param = array())
    {
        $result = array("state" => 0, "message" => "", "code" => '', "amount" => 0, "opType" => 0);

        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            $note = $param['note'];
            $bi_id = $param['bi_id'];
            $opType = $param['opType'];

            $bilIncomeRow = Service_BilIncome::getByField($bi_id, 'bi_id');
            if (empty($bilIncomeRow)) {
                throw new Exception("没有找到匹配的数据");
            }
            //更新业务表
            $businessForUp = array();
            $businessArr = Service_BilBusiness::getAttrByField($bilIncomeRow['bb_id'], 'bb_id');

            $result['code'] = $businessArr['bb_refer_code'];
            $result['amount'] = $bilIncomeRow['bi_amount'];

            if ($bilIncomeRow['bi_status'] != '1') {
                $bilIncomeStatusArr = Process_BillConfig::bilIncomeStatus('auto');
                throw new Exception("状态为[" . $bilIncomeStatusArr[$bilIncomeRow['bi_status']] . '],不允许操作');
            }
            if (strtolower($businessArr['bb_status']) == 'n') {
                throw new Exception("此业务费用已作废,不允许操作");
            }
            //获取客户币种
            $row = Service_Customer::getByField($bilIncomeRow['customer_code'], 'customer_code', array("customer_currency"));

            //审核通过扣费
            if ($opType == '1') {
                //新费用
                $fee = array();
                $fee[] = array(
                    'cbl_type' => ($bilIncomeRow['bi_rp_type'] == '0' ? 2 : 3), //类型
                    'cbl_value' => abs($bilIncomeRow['bi_amount']),
                    'currency_code' => $row['customer_currency'], //客户币种
                    'release_value' => '0',
                    'currency_rate' => '',
                    'user_id' => $this->_userId,
                    'cbl_refer_code' => $businessArr['bb_refer_code'],
                    'application_code' => 'verify fee',
                    'fee_id' => '0',
                    'cbl_note' => $bilIncomeRow['bi_note']
                );
                $feeObj = new Common_CustomerFeeProcess();
                $feeReturn = $feeObj->payment($bilIncomeRow['customer_code'], $fee, 1); //强制扣款
                if ($feeReturn['state'] != '1') {
                    throw new Exception(isset($feeReturn['message']) ? $feeReturn['message'] : 'Payment Fee Fail.');
                }

            }
            //应收表
            $biUpArr = array(
                'bi_status' => $opType == '1' ? 2 : 1,
                'bi_withdraw_sign' => $opType == '1' ? 'n' : 'y',
                'bi_update_time' => $this->_date,
                'bi_verifier_id' => $this->_userId,
                'bi_verify_time' => $this->_date,
            );
            Service_BilIncome::update($biUpArr, $bilIncomeRow['bi_id'], 'bi_id');

            $db->commit();
            $result['state'] = 1;
            $result['message'] = '操作成功';
        } catch (Exception $e) {
            $db->rollBack();
            $result['state'] = 0;
            $result['message'] = $e->getMessage();
        }
        return $result;
    }


    /**
     * @desc 批量导入费用（非逻辑）
     */
    public function uploadFeeTransaction($file)
    {
        require_once APPLICATION_PATH . '/../libs/PHPExcel/IOFactory.php';
        $return = array(
            'state' => 0,
            'message' => array()
        );
        if ($file['error']) {
            $return['message'] = array('请选择xls文件');
            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;
        }

        $fileData = Common_Upload::readUploadFile($fileName, $filePath);
        if (!isset($fileData[1]) || !is_array($fileData[1])) {
            $result['message'] = array('上传失败，无法解析文件内容;');
            return $result;
        }
         $loaderObj = PHPExcel_IOFactory::load($filePath); // 加载Excel文件
        $sheetObj= $loaderObj->getSheet(0); 
        /**
         * 格式化数据
         */
        $keys = array(
            '客户代码' => 'customer_code',
            '仓库代码' => 'warehouse_code',
            '业务类型代码' => 'bt_code',
            '费用类型' => 'ft_code', ///中文名称
            //  '收付类型' => 'rp_type',
            '金额' => 'amount',
            '币种' => 'currency_code',
            '费用发生时间' => 'charge_time',
            '备注' => 'note',
        );

        $btArr = Process_BillConfig::bt('auto');
        $data = $error = array();
        foreach ($fileData as $key => $val) {
            $newVal = array();
            foreach ($keys as $k => $v) {
                if (!isset($val[$k])) {
                    $error[] = '第 ' . $key . ' 行,无法识别[' . $k . ']';
                    break;
                }
                $newVal[$v] = isset($val[$k]) ? $val[$k] : '';
            }
            $customerCode = preg_replace('/([0-9a-zA-Z]+)\s+.*/', '\\1', $newVal['customer_code']);
            if (empty($customerCode)) {
                $error[] = '第 ' . $key . ' 行,客户代码不能为空';
                continue;
            }

            $whCode = preg_replace('/([0-9a-zA-Z]+)\s+.*/', '\\1', $newVal['warehouse_code']);


            if (empty($newVal['ft_code'])) {
                $error[] = '第 ' . $key . ' 行,费用类型不能为空';
                continue;
            }

            if (empty($newVal['currency_code'])) {
                $error[] = '第 ' . $key . ' 行,币种不能为空';
                continue;
            }


            if (!empty($newVal['bt_code']) && !isset($btArr[strtoupper($newVal['bt_code'])])) {
                $error[] = '第 ' . $key . ' 行,业务类型不存在' . $newVal['bt_code'];
                continue;
            }

            if (!is_numeric($newVal['amount'])) {
                $error[] = '第 ' . $key . ' 行,金额异常';
                continue;
            }


            if (!empty($whCode)) {
                $whRow = Service_Warehouse::getByField($whCode, 'warehouse_code', array('warehouse_code', 'warehouse_id'));
                if (empty($whRow)) {
                    $error[] = '第 ' . $key . ' 行,仓库代码不存在或无法识别';
                    continue;
                }
            }

            $ftRow = Service_FeeType::getByField($newVal['ft_code'], 'ft_name_cn');
            if (empty($ftRow)) {
                $error[] = '第 ' . $key . ' 行,费用类型不存在或无法识别';
                continue;
            }

            $currencyRow = Service_Currency::getByField($newVal['currency_code'], 'currency_code');
            if (empty($currencyRow)) {
                $error[] = '第 ' . $key . ' 行,币种不存在或无法识别';
                continue;
            }

            $chargTimeCell =$sheetObj->getCellByColumnAndRow('6',$key+1);  
           if($chargTimeCell->getDataType()==PHPExcel_Cell_DataType::TYPE_NUMERIC){
                 $cellstyleformat=$cell->getParent()->getStyle( $cell->getCoordinate() )->getNumberFormat();  
                 $formatcode=$cellstyleformat->getFormatCode(); 
                  if (preg_match('/^(\[\$[A-Z]*-[0-9A-F]*\])*[hmsdy]/i', $formatcode)){
                        $error[] = '第'.$key.'行计费时间列格式不正确，正确格式如2015/10/10且单元格格式为文本格式';
                         continue;
                  }elseif($formatcode=='General'){
                      if(!preg_match('/^\d{4}\/{1}\d{1,2}\/{1}\d{1,2}$/',$newVal['charge_time'])){
                              $error[] = '第'.$key.'行计费时间列格式不正确，正确格式如2015/10/10且单元格格式为文本格式';
                            continue;
                         }
                  }
           }else{
               if(!preg_match('/^\d{4}\/{1}\d{1,2}\/{1}\d{1,2}$/',$newVal['charge_time'])){
                       $error[] = '第'.$key.'行计费时间列格式不正确，正确格式如2015/10/10且单元格格式为文本格式';
                     continue;
               }
           }
           $dateSplide=  explode('/', $newVal['charge_time']);
           if(!checkdate($dateSplide[1], $dateSplide[2], $dateSplide[0])){
               $error[] = '第 ' . $key . ' 行,非法的计费时间，请检查时间是否正确';
                continue;
           }
            $customerRow = Service_Customer::getByField($customerCode, 'customer_code');

            if (empty($customerRow)) {
                $error[] = '第 ' . $key . ' 行,客户代码：' . $customerCode . '不存在或无法识别';
                continue;
            }

            $data[$key]['warehouse_id'] = isset($whRow['warehouse_id']) ? $whRow['warehouse_id'] : 0;
            $data[$key]['bt_code'] = empty($newVal['bt_code']) ? 'EX' : strtoupper($newVal['bt_code']);
            $data[$key]['ft_code'] = $ftRow['ft_code'];
            $data[$key]['currency_code'] = $currencyRow['currency_code'];
            $data[$key]['amount'] = abs($newVal['amount']);
            $data[$key]['rp_type'] = $newVal['amount'] < 0 ? 1 : 0;
            $data[$key]['note'] = $newVal['note'];
            $data[$key]['customer_code'] = $customerRow['customer_code'];
            $data[$key]['bi_chargeable_time'] = Process_ImportDataProcess::excelTime($newVal['charge_time']);

        }
        unset($fileData, $newVal);
        if (!empty($error) || empty($data)) {
            $return['state'] = 0;
            $return['message'] = $error;
            return $return;
        }

        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            foreach ($data as $key => $row) {
                $this->addBusinessFee($row);
            }
            $db->commit();
            $return['state'] = 1;
            $return['message'] = array('操作成功');
        } catch (Exception $e) {
            $db->rollBack();
            $return['message'] = array($e->getMessage());
        }
        return $return;
    }

    /**
     * @desc 设置业务数据
     * @param string $code
     */
    private function setBusiness($code = '')
    {
        $businessArr = Service_BilBusinessAttach::getByField($code, 'bb_refer_code');
        if (!empty($businessArr)) {
            $this->_bb_id = $businessArr['bb_id'];
            $this->_businessArr['business'] = Service_BilBusiness::getByField($businessArr['bb_id'], 'bb_id');
            $this->_businessArr['attach'] = $businessArr;
            $this->_businessArr['income'] = Service_BilIncome::getByCondition(array('bb_id' => $businessArr['bb_id']), '*', 0);
            $this->_businessArr['payment'] = Service_BilPayment::getByCondition(array('bb_id' => $businessArr['bb_id']), '*', 0);
        }
    }

    /**
     * @desc 新增业务费用(逻辑)
     * @param array $businessArr
     * @param array $incomeArr
     * @param array $paymentArr
     * @throws Exception
     */
    private function createBusinessFee($businessArr = array(), $incomeArr = array(), $paymentArr = array())
    {
        //附加表
        $attachArr = array(
            'bb_refer_code' => $businessArr['bb_refer_code'],
            'bb_service_number' => $businessArr['bb_service_number'],
            'bb_reference_no' => $businessArr['bb_reference_no'],
        );
        //业务表
        if(!isset($businessArr['bb_add_time'])) 
        {
            $businessArr['bb_add_time']= $this->_date;
        }
        unset($businessArr['bb_refer_code'], $businessArr['bb_service_number'], $businessArr['bb_reference_no']);
        if (!$bbId = Service_BilBusiness::add($businessArr)) {
            throw new Exception("建立业务数据错误");
        }
        $attachArr['bb_id'] = $bbId;
        Service_BilBusinessAttach::add($attachArr);
  
        //应收
        if (!empty($incomeArr)) {
            foreach ($incomeArr as $row) {
                $row['bb_id'] = $bbId;
                $row['bi_status'] = 2;
                $row['customer_code'] = $businessArr['customer_code'];
                $row['bi_rp_type'] = $row['bi_amount'] > 0 ? 0 : 1;
                if(!isset($row['bi_add_time'])){
                      $row['bi_add_time'] = $this->_date;
                }
              if(!isset($row['bi_verify_time'])){
                $row['bi_verify_time'] = $this->_date;
              }
                $row['bi_chargeable_time'] = isset($row['bi_chargeable_time']) ? $row['bi_chargeable_time'] : $businessArr['bb_charge_time'];
                //汇率为空
                if(!empty($row['currency_rate'])){
                    $currencyArr[$row['currency_code']] = $row['currency_rate'];
                }
                if (!isset($currencyArr[$row['currency_code']])) {
                    $cArr = Service_Currency::getByField($row['currency_code'], 'currency_code');
                    $currencyArr[$row['currency_code']] = $cArr['currency_rate'];
                }
                $row['currency_rate'] = $currencyArr[$row['currency_code']];
                Service_BilIncome::add($row);
            }
        }
        //应付
        if (!empty($paymentArr)) {
            foreach ($paymentArr as $row) {
                $row['bb_id'] = $bbId;
                $row['bp_status'] = 2;
                $row['bp_rp_type'] = $row['bp_amount'] < 0 ? 0 : 1;
                if(!isset($row['bp_add_time'])){
                      $row['bp_add_time'] = $this->_date;
                }
              if(!isset($row['bp_verify_time'])){
                $row['bp_verify_time'] = $this->_date;
              }
               if(isset($row['bp_chargeable_time'])){
                   $row['bp_chargeable_time'] = $row['bp_chargeable_time'];
               }else{
                   $row['bp_chargeable_time'] = isset($businessArr['bb_declared_time']) ? $businessArr['bb_declared_time'] : $businessArr['bb_charge_time'];
               }
                //汇率为空
                if(!empty($row['currency_rate'])){
                    $currencyArr[$row['currency_code']] = $row['currency_rate'];
                }
                if (!isset($currencyArr[$row['currency_code']])) {
                    $cArr = Service_Currency::getByField($row['currency_code'], 'currency_code', 'currency_rate');
                    $currencyArr[$row['currency_code']] = $cArr['currency_rate'];
                }
                $row['currency_rate'] = $currencyArr[$row['currency_code']];
                Service_BilPayment::add($row);
            }
        }
    }


    /**
     * @desc 编辑业务费用(逻辑)
     * @param array $businessArr
     * @param array $incomeArr
     * @param array $paymentArr
     * @throws Exception
     */
    private function editBusinessFee($businessArr = array(), $incomeArr = array(), $paymentArr = array())
    {
        //业务表
        $businessUpArr['bb_update_time'] = $this->_date;
        foreach ($this->_businessArr['business'] as $key => $val) {
            if (isset($businessArr[$key])) {
                $businessUpArr[$key] = $businessArr[$key];
            }
        }
        unset($businessUpArr['bb_id']);
        if (!Service_BilBusiness::update($businessUpArr, $this->_bb_id, 'bb_id')) {
            throw new Exception("建立业务错误");
        }

        //附加表
        $attachArr['bba_update_time'] = $this->_date;
        foreach ($this->_businessArr['attach'] as $key => $val) {
            $attachArr[$key] = isset($businessArr[$key]) ? $businessArr[$key] : $val;
        }
        unset($attachArr['bb_id'], $attachArr['bb_refer_code']);
        Service_BilBusinessAttach::update($attachArr, $this->_bb_id, 'bb_id');
        $currencyArr = array();
        //应收
        if (!empty($incomeArr)) {
            $income = false;
            $incomeArray = array();
            if (!empty($this->_businessArr['income'])) {
                foreach ($this->_businessArr['income'] as $iRow) {
                    if ($iRow['bi_status'] == '3') {
                        $income = true;
                        if (!isset($incomeArray[$iRow['ft_code']])) {
                            $incomeArray[$iRow['ft_code']] = $iRow['bi_amount'];
                        } else {
                            $incomeArray[$iRow['ft_code']] += $iRow['bi_amount'];
                        }
                    }
                }
            }
            //判断是否已存在出帐
            if ($income) {
                //汇总各类型费用
                $incomeNewArray = array();
                foreach ($incomeArr as $iRow) {
                    if (isset($incomeNewArray[$iRow['ft_code']])) {
                        $incomeNewArray[$iRow['ft_code']]['bi_amount'] += $iRow['bi_amount'];
                    } else {
                        $incomeNewArray[$iRow['ft_code']] = $iRow;
                    }
                }

                //多还少补
                foreach ($incomeNewArray as $code => $row) {
                    $oAmount = isset($incomeArray[$code]['bi_amount']) ? $incomeArray[$code]['bi_amount'] : 0;
                    $amount = $row['bi_amount'] - $oAmount;
                    if ($amount == 0) {
                        continue;
                    }
                    $row['bb_id'] = $this->_bb_id;
                    $row['bi_status'] = 2;
                    $row['customer_code'] = $this->_businessArr['business']['customer_code'];
                    $row['bi_rp_type'] = $amount > 0 ? 0 : 1;
                    $row['bi_add_time'] = $this->_date;
                    $row['bi_verify_time'] = $this->_date;
                    $row['bi_update_time'] = $this->_date;
                    $row['bi_chargeable_time'] = isset($row['bi_chargeable_time']) ? $row['bi_chargeable_time'] : $businessArr['bb_charge_time'];
                    //汇率为空
                    if(!empty($row['currency_rate'])){
                        $currencyArr[$row['currency_code']] = $row['currency_rate'];
                    }
                    if (!isset($currencyArr[$row['currency_code']])) {
                        $cArr = Service_Currency::getByField($row['currency_code'], 'currency_code', 'currency_rate');
                        $currencyArr[$row['currency_code']] = $cArr['currency_rate'];
                    }
                    $row['currency_rate'] = $currencyArr[$row['currency_code']];
                    Service_BilIncome::add($row);
                }
            } else {
                //清理原费用
                Service_BilIncome::delete($this->_bb_id, 'bb_id');
                foreach ($incomeArr as $row) {
                    $row['bb_id'] = $this->_bb_id;
                    $row['bi_status'] = 2;
                    $row['customer_code'] = $businessArr['customer_code'];
                    $row['bi_rp_type'] = $row['bi_amount'] > 0 ? 0 : 1;
                    $row['bi_add_time'] = $this->_date;
                    $row['bi_verify_time'] = $this->_date;
                    $row['bi_chargeable_time'] = isset($row['bi_chargeable_time']) ? $row['bi_chargeable_time'] : $businessArr['bb_charge_time'];
                    //汇率为空
                    if(!empty($row['currency_rate'])){
                        $currencyArr[$row['currency_code']] = $row['currency_rate'];
                    }
                    if (!isset($currencyArr[$row['currency_code']])) {
                        $cArr = Service_Currency::getByField($row['currency_code'], 'currency_code', 'currency_rate');
                        $currencyArr[$row['currency_code']] = $cArr['currency_rate'];
                    }
                    $row['currency_rate'] = $currencyArr[$row['currency_code']];
                    Service_BilIncome::add($row);
                }
            }
        }
        //应付
        if (!empty($paymentArr)) {
            $payment = false;
            $paymentArray = array();
            if (!empty($this->_businessArr['payment'])) {
                foreach ($this->_businessArr['payment'] as $iRow) {
                    if ($iRow['bp_status'] == '3') {
                        $payment = true;
                        if (!isset($paymentArray[$iRow['ft_code']])) {
                            $paymentArray[$iRow['ft_code']] = $iRow['bp_amount'];
                        } else {
                            $paymentArray[$iRow['ft_code']] += $iRow['bp_amount'];
                        }
                    }
                }
            }

            if ($payment) {
                //多还少补
                foreach ($paymentArr as $code => $row) {
                    $oAmount = isset($paymentArray[$code]['bp_amount']) ? $paymentArray[$code]['bp_amount'] : 0;
                    $amount = $row['bp_amount'] - $oAmount;
                    if ($amount == 0) {
                        continue;
                    }
                    $row['bb_id'] = $this->_bb_id;
                    $row['bp_status'] = 2;
                    $row['bp_amount'] = $amount;
                    $row['bp_rp_type'] = $amount < 0 ? 0 : 1;
                    $row['bp_add_time'] = $this->_date;
                    $row['bp_verify_time'] = $this->_date;
                    $row['bp_chargeable_time'] = isset($row['bp_chargeable_time']) ? $row['bp_chargeable_time'] : $businessArr['bb_declared_time'];
                    //汇率为空
                    if(!empty($row['currency_rate'])){
                        $currencyArr[$row['currency_code']] = $row['currency_rate'];
                    }
                    if (!isset($currencyArr[$row['currency_code']])) {
                        $cArr = Service_Currency::getByField($row['currency_code'], 'currency_code', 'currency_rate');
                        $currencyArr[$row['currency_code']] = $cArr['currency_rate'];
                    }
                    $row['currency_rate'] = $currencyArr[$row['currency_code']];
                    Service_BilPayment::add($row);
                }
            } else {
                //清理原费用
                Service_BilPayment::delete($this->_bb_id, 'bb_id');
                foreach ($paymentArr as $row) {
                    $row['bb_id'] = $this->_bb_id;
                    $row['bp_status'] = 2;
                    $row['bp_rp_type'] = $row['bp_amount'] < 0 ? 0 : 1;
                    $row['bp_add_time'] = $this->_date;
                    $row['bp_verify_time'] = $this->_date;
                    $row['bp_chargeable_time'] = isset($row['bp_chargeable_time']) ? $row['bp_chargeable_time'] : $businessArr['bb_declared_time'];
                    //汇率为空
                    if(!empty($row['currency_rate'])){
                        $currencyArr[$row['currency_code']] = $row['currency_rate'];
                    }
                    if (!isset($currencyArr[$row['currency_code']])) {
                        $cArr = Service_Currency::getByField($row['currency_code'], 'currency_code', 'currency_rate');
                        $currencyArr[$row['currency_code']] = $cArr['currency_rate'];
                    }
                    $row['currency_rate'] = $currencyArr[$row['currency_code']];
                    Service_BilPayment::add($row);
                }
            }

        }
    }

    /**
     * @desc 新增/编辑业务费用(逻辑)
     * @param array $businessArr
     * @param array $incomeArr
     * @param array $paymentArr
     * @return array
     */
    public function businessFee($businessArr = array(), $incomeArr = array(), $paymentArr = array())
    {
        $result = array("state" => 0, "message" => "", "data" => array());

        try {
            //主要参考
            $paramArr = array(
                'bt_code' => 'EX',
                'ds_code' => '',
                'customer_code' => '',
                'warehouse_id' => '0',
                'sm_code' => '',
                'bb_volume_weight' => 0,
                'bb_charge_weight' => 0,
                'bb_delivered_weight' => 0,
                'bb_pieces' => 0,
                'bb_declared_value' => 0,
                'bb_declared_currency_code' => 'USD',
                'country_code' => '',
                'bb_postcode' => '',
                'bb_charge_time' => '',
                'bb_declared_time' => '', //发货时间 此时间与服务商对接
                'bb_sales_id' => 0,

                'bb_refer_code' => '',
                'bb_service_number' => '',
                'bb_reference_no' => '',
            );

            if (!isset($businessArr['ds_code'])) {
                throw new Exception("业务类型不能为空");
            }
            if (!isset($businessArr['bb_refer_code']) || $businessArr['bb_refer_code'] == '') {
                throw new Exception("业务单号不能为空");
            }
            $businessArr['ds_code'] = strtolower($businessArr['ds_code']);
            if (!in_array($businessArr['ds_code'], array('so', 'lo', 'asn', 'ot','vf'))) {
                throw new Exception("业务类型异常");
            }
            //设置业务
            $this->setBusiness($businessArr['bb_refer_code']);

            //主要信息
            foreach ($paramArr as $key => $val) {
                $paramArr[$key] = isset($businessArr[$key]) ? $businessArr[$key] : $val;
            }
            //判断是否为新增
            if ($this->_bb_id == '') {
                $this->createBusinessFee($paramArr, $incomeArr, $paymentArr);
            } else {
                $this->editBusinessFee($paramArr, $incomeArr, $paymentArr);
            }

            $result['state'] = 1;
            $result['message'] = '操作成功';
        } catch (Exception $e) {
            $result['state'] = 0;
            $result['message'] = $e->getMessage();
        }
        return $result;
    }


    /**
     * @desc 批量导入服务商重量
     */
    public function uploadWeightTransaction($file)
    {
        $return = array(
            'state' => 0,
            'message' => array()
        );
        if ($file['error']) {
            $return['message'] = array('请选择xls文件');
            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;
        }

        $fileData = Common_Upload::readUploadFile($fileName, $filePath);
        if (!isset($fileData[1]) || !is_array($fileData[1])) {
            $result['message'] = array('上传失败，无法解析文件内容;');
            return $result;
        }
        /**
         * 格式化数据
         * 单号    服务商收费重量    服务商实际重量    服务商体积重量    长(CM)    高(CM)    宽(CM)
         */
        $keys = array(
            '单号' => 'code',
            '服务商收费重量' => 'charge_weight',
            //'服务商实际重量' => 'actual_weight',
            //'服务商体积重量' => 'volume_weight',
            //'长(CM)' => 'length',
            //'高(CM)' => 'height',
            //'宽(CM)' => 'width',
        );

        $data = $error = array();
        foreach ($fileData as $key => $val) {
            //是否区外仓
            $is_lo = false;

            $newVal = array();
            foreach ($keys as $k => $v) {
                if (!isset($val[$k])) {
                    $error[] = '第 ' . $key . ' 行,无法识别';
                    break;
                }
                $newVal[$v] = isset($val[$k]) ? $val[$k] : '';
            }
            $newVal['actual_weight'] = $newVal['charge_weight'];
            $newVal['volume_weight'] = 0;
            $newVal['length'] = 0;
            $newVal['height'] = 0;
            $newVal['width']  = 0;
            unset($fileData[$key]);

            if (empty($newVal['code'])) {
                $error[] = '第 ' . $key . ' 行,单号不能为空';
                continue;
            }
            if (empty($newVal['charge_weight']) || !is_numeric($newVal['charge_weight']) || $newVal['charge_weight'] < 0) {
                $error[] = '第 ' . $key . ' 行,服务商收费重量异常';
                continue;
            }
            //查看订单
            $orderCode = '';
            $delivered_weight = 0;
            if (!empty($newVal['code'])) {
                //区内仓订单判断
                $soRow = Service_ShipOrder::getByField($newVal['code'], 'tracking_number');
                if (!empty($soRow)) {
                    $delivered_weight = $soRow['so_weight'];
                    $orderCode = $soRow['order_code'];
                } else {
                    $orderRow = Service_Orders::getByField($newVal['code'], 'order_code');
                    if (!empty($orderRow)) {
                        $orderCode = $orderRow['order_code'];
                        $soRow = Service_ShipOrder::getByField($orderCode, 'order_code');
                        $delivered_weight = $soRow['so_weight'];
                    }
                }
                if('' == $orderCode){
                    //区外仓订单判断
                    $loRow = Service_LogisticsOrder::getByField($newVal['code'], 'ref_tracking_number');
                    if(!empty($loRow)){
                        $is_lo = true;
                        $loRboRow = Service_ReceivingBatchOrder::getByField($loRow['logistics_code'], 'logistics_code');
                        $delivered_weight = $loRboRow['weight'];
                        $orderCode = $loRow['logistics_code'];
                    } else {
                        $loRow = Service_LogisticsOrder::getByField($newVal['code'], 'logistics_code');
                        if(!empty($loRow)){
                            $is_lo = true;
                            $loRboRow = Service_ReceivingBatchOrder::getByField($loRow['logistics_code'], 'logistics_code');
                            $delivered_weight = $loRboRow['weight'];
                            $orderCode = $loRow['logistics_code'];
                        }
                    }
                }
                
                //必需匹配系统单据
                if ($orderCode == '') {
                    $error[] = '第 ' . $key . ' 行,单号：' . $newVal['code'] . ' 未找到匹配的单据';
                    continue;
                }
            }
            $data[$key]['code'] = $orderCode;
            $data[$key]['so_weight'] = $delivered_weight;
            if($is_lo){
                $data[$key]['lo_weight'] = $delivered_weight;
            }
            $data[$key]['charge_weight'] = $newVal['charge_weight'];
            $data[$key]['actual_weight'] = $newVal['actual_weight'];
            $data[$key]['volume_weight'] = $newVal['volume_weight'];
            $data[$key]['length'] = $newVal['length'];
            $data[$key]['height'] = $newVal['height'];
            $data[$key]['width'] = $newVal['width'];

        }
        unset($fileData, $newVal);
        if (!empty($error) || empty($data)) {
            $return['state'] = 0;
            $return['message'] = $error;
            return $return;
        }

        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            //更新ship_order重量
            $obj = new Service_BilBusiness();
            $objSo = new Service_ShipOrder();
            $objLo = new Service_LogisticsOrder();
            $objRbo = new Service_ReceivingBatchOrder();
            foreach ($data as $key => $row) {
                $bbRow = $obj->getAttrByRefCode($row['code']);
                if (empty($bbRow)) {
                    throw new Exception("单号：" . $row['code'] . ' 没有找到匹配的业务数据');
                }
                //目前只更新重量
                //如果上传的计费重量不大于原来的重量，则不更新
                if ($row['so_weight'] < $row['charge_weight']) {
                    if(!isset($row['lo_weight'])){
                        $soArr = array('so_service_provider_weight' => $row['charge_weight'], 'so_update_time' => $this->_date);
                        $objSo->update($soArr, $row['code'], 'order_code');
                    } else {
                        //区外仓订单直接在 logistics_order 及 receiving_batch_order 更新
                        $loArr = array(
                                'lo_service_provider_weight' => $row['charge_weight'], 
                                'lo_update_time' => $this->_date
                            );
                        $objLo->update($loArr, $row['code'], 'logistics_code');
                        $rboArr = array(
                            'lo_service_provider_weight' => $row['charge_weight'], 
                            'update_time' => $this->_date
                        );
                        $objRbo->update($rboArr, $row['code'], 'logistics_code');
                    }
                    //业务数据更新
                    $bbArr = array(
                        // 业务数
                        'bb_volume_weight' => $row['volume_weight'],
                        'bb_charge_weight' => $row['charge_weight'],
                        //服务商数据
                        'bb_volume' => $row['volume_weight'],
                        'bb_service_actual_weight' => $row['actual_weight'],
                        'bb_service_provider_weight' => $row['charge_weight'],
                        'bb_package_width' => $row['width'],
                        'bb_package_height' => $row['height'],
                        'bb_package_length' => $row['length'],
                        'bb_charge_weight_sign' => 'y',
                        'bb_update_time' => $this->_date,
                    );
                    $obj->update($bbArr, $bbRow['bb_id'], 'bb_id');
                }
            }
            $db->commit();
            $return['state'] = 1;
            $return['message'] = array('操作成功');
        } catch (Exception $e) {
            $db->rollBack();
            $return['message'] = array($e->getMessage());
        }
        return $return;
    }


}