<?php

/**
 * @desc 业务处理类
 */
class Service_BusinessProcess
{
    protected $_date = "";
    protected $_userId = "";
    protected $_bb_id = ""; //业务ID
    protected $_businessArr = array();

    public function __construct()
    {
        $this->_userId = 0;//系统操作或客户自己操作
        $this->_date = date('Y-m-d H:i:s');
    }

    /**
     * @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;
              }
                $row['bp_chargeable_time'] = isset($row['bp_chargeable_time']) ? $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'))) {
                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;
    }


}