<?php

class Service_CalculateLogisticOtherFee {

    protected $_paramsArray = array(); //参数
    protected $_dataArray = array(); //自定义
    protected $_errorArray = array(); //错误信息
    //只针对以下运输方式扣费
    protected $allowShipType = array(
        'SZY-EMS',
        'SZY-EUB',
        'WG-EUB',
        'WG-EMS'
    );
    protected $zccqShipType = array(
        'ZCCQ',
    );
    protected $iszccq = false;

    /*     * *
     * 逻辑如下:
     * -----------------------------------------------------------
     *
     *                                 设置客户折扣 可用    （收费，按设置的打折）
     *                1) 默认费用设置  设置客户折扣 不可用  （收费，不打折）
     * 设置费用可用                    无设置客户折扣       （不收费）  
     *                                 
     *
     *                                 无设置客户折扣       （不收费）
     *                2) 非默认费用    设置客户折扣 可用    （收费，按设置的打折）
     *                                 设置客户折扣 不可用  （不收费）
     * ------------------------------------------------------------
     * 设置费用不可用 （不收费）
     */

    public function construct($params = array()) {
        $this->setParams($params);
    }

    /**
     * @设置参数
     */
    public function setParams($params = array()) {
        $keys = array(
            'customerCode' => '',
            'warehouseId' => '',
            'countryId' => 0,
            'smId' => 0,
            'smCode' => '',
            'weight' => 0,
            'length' => 0,
            'width' => 0,
            'height' => 0,
            'provinceId' => 0,
            'cityId' => 0,
            'zip' => null,
            //'warehouseName'     => '',
            //'countryCode'       => '',
            //'smClassCode'       => null, //运输方式分类的code
            'smFeeType' => null, //费用类型：单票,总单
            'smCalcType' => null, //计费类型：区间,首续重
            'logistics_code' => null,
            'receiving_weight' => null,
            'orderProducts' => array(),
            'orderInfo' => array(),
            'receingInfo' => array(),
            'realWeight' => 0,
        );
        if (is_array($params)) {
            foreach ($keys as $key => $val) {
                if (isset($params[$key])) {
                    $keys[$key] = $params[$key];
                }
            }
        }
        unset($params);
        $this->_paramsArray = $keys;
        $ordersHs = '';
        $orderinfo = '';
        if (isset($this->_paramsArray['logistics_code']) && $this->_paramsArray['logistics_code'] != '') {
            $ordersProductCondition = array(
                'logistics_code' => $this->_paramsArray['logistics_code']
            );
            $ordersHs = Service_LogisticsOrderHs::getByCondition($ordersProductCondition, '*');
            $orderinfo = Service_LogisticsOrder::getByField($this->_paramsArray['logistics_code'], 'logistics_code');
            $this->_paramsArray['warehouse_id'] = $orderinfo['warehouse_id'];
        }
        $this->_paramsArray['orderProducts'] = $ordersHs;
        $this->_paramsArray['orderInfo'] = $orderinfo;
        $this->getzccq();
    }

    private function getzccq() {
        $smCode = strtoupper($this->_paramsArray['smCode']);
        if (in_array($smCode, $this->zccqShipType)) {
            $this->iszccq = true;
        }
    }

    /**
     * @todo 得到其它费用
     */
    public function getOtherFee($feeCode = '') {
        $result = array(
            'state' => 0,
            'error' => array(),
            'data' => array()
        );
        if (!empty($feeCode)) {
            switch (strtoupper($feeCode)) {
                case "PIANYUAN":
                    $this->getPianyuanFee();
                    break;
                case "CHAOCHANG";
                    $this->getChaoChangFee();
                    break;
            }
        } else {
            $this->getChaoChangFee();
            $this->getPianyuanFee();
        }
        $result = array(
            'state' => 1,
            'data' => array(
                'otherFee' => $this->_dataArray['costArr']['otherFee']
            )
        );
        return $result;
    }

    /**
     * 超长费
     */
    private function getChaoChangFee() {
        if ($this->iszccq) {
            return;
        }
        $chaochangfee = 0;
        $cost = 0;
        $sum = 0;
        $otherfee = Service_OtherFee::getByField('CHAOCHANG', 'fee_code');
        if (empty($otherfee)) {
            return;
        }

        $customerFeeCondition = array(
            'customer_code' => $this->_paramsArray['orderInfo']['customer_code'],
            'fee_id' => $otherfee['fee_id']
        );
        $customerOtherFee = Service_CustomerOtherFee::getByCondition($customerFeeCondition, '*');

        if ('1' == $otherfee['status']) {
            if ($this->_paramsArray['orderInfo']['sm_code'] == 'HKDHL') {
                $order_code = $this->_paramsArray['orderInfo']['logistics_code'];
                $shippingMethod = Service_ShippingMethod::getByField('HKDHL', "sm_code");
                $shipOrderD = Service_OutsideShipOrderDetail::getByCondition(array('logistics_code' => $order_code), '*');
                foreach ($shipOrderD as $key => $shipOrderDetail) {
                    if ((int) $shipOrderDetail['length'] > 120 || (int) $shipOrderDetail['width'] > 120 || (int) $shipOrderDetail['height'] > 120 || (int) $shipOrderDetail['weight'] > 70) {
                        $sum=1;
                        break;
                    }
                }
                if ($sum > 0) {
                    if ($customerOtherFee[0]['status'] == '1') {
                        $chaochangfee = $customerOtherFee[0]['discount'] * $otherfee['fee_value'];
                    } else {
                        $chaochangfee = $otherfee['fee_value'];
                    }
                    $cost = $otherfee['fee_amount'] + $otherfee['fee_amount'] * $shippingMethod['sm_baf'];
                }
            }
        }
        $this->_dataArray['costArr']['otherFee']['chaochang'] = array(
            'cost_currency_code' => $otherfee['cost_currency_code'],
            'currency_code' => $otherfee['fee_currency_code'],
            'price' => $chaochangfee,
            'discount' => 0,
            'cost' => $cost, /* 成本写死为 0 */
            'sp_code' => $otherfee['sp_code'],
            'fee_id' => $otherfee['fee_id']
        );
    }

    /**
     * @author william-fan
     * @todo 计算偏远费
     */
    private function getPianyuanFee() {
        if ($this->iszccq) {
            return;
        }
        //是偏远的订单
        if ($this->_paramsArray['orderInfo']['is_remote_city'] == '1') {
            //偏远城市，计算偏远费
            $pianyuan = Service_OtherFee::getByField("PIANYUAN", "fee_code", "*");
            if (!empty($pianyuan)) {
                $customerFeeCondition = array(
                    'customer_code' => $this->_paramsArray ['orderInfo'] ['customer_code'],
                    'fee_id' => $pianyuan ['fee_id']
                );
                $customerOtherFee = Service_CustomerOtherFee::getByCondition($customerFeeCondition, '*');
                $smCode = $this->_paramsArray['smCode'];
                $pianyuanFee = $pianyuan ['fee_value'];
                //$cost = $pianyuan ['fee_amount'];
                //echo $cost;exit;
                $discount = 1;
                if (!empty($smCode)) {
                    $shippingMethod = Service_ShippingMethod::getByField($smCode, "sm_code");
                    if ('CRE' == $shippingMethod['sm_class_code']) {
                        $baf = $shippingMethod['sm_baf'];
                        $pianyuanFee = $pianyuanFee * $baf + $pianyuanFee;
                    }
                }
                $cost = $pianyuan['fee_amount'] + $pianyuan['fee_amount'] * $shippingMethod['sm_baf'];
                if ('1' == $pianyuan ['status']) {
                    // 杂费状态：可用
                    if (!empty($customerOtherFee)) {
                        if ($customerOtherFee [0] ['status'] == '1') {
                            // 客户杂费可用，则参与打折计算
                            $pianyuanFee = $customerOtherFee [0] ['discount'] * $pianyuanFee;
                            $discount = $customerOtherFee [0] ['discount'];
                        }
                    } else {
                        // 非默认费用且该客户无此项杂费设置，则此项费用不收
                        if ('0' == $pianyuan ['is_default_fee']) {
                            $pianyuanFee = 0;
                            $cost = 0;
                        }
                    }
                } else {
                    // 杂费状态：不可用
                    $pianyuanFee = 0;
                    $cost = 0;
                }
                $this->_dataArray ['costArr'] ['otherFee'] ['pianyuan'] = array(
                    'cost_currency_code' => $pianyuan ['cost_currency_code'],
                    'currency_code' => $pianyuan ['fee_currency_code'],
                    'price' => $pianyuanFee,
                    'discount' => $discount,
                    'cost' => $cost,
                    'sp_code' => $pianyuan ['sp_code'],
                    'fee_id' => $pianyuan ['fee_id']
                );
            }
        }
    }

   
    public function calculateLogisticOrderFrezRemoteFee($logisticOrderInfo, $logisticAddressInfo) {
        if ($this->iszccq) {
            return;
        }
        $outsideLogistics = new Process_OutsideLogistics();
        $isRemotCity = $outsideLogistics->isRemoteCity($logisticAddressInfo['loa_country'], $logisticAddressInfo['loa_city'], $logisticAddressInfo['loa_zipcode']);
        //是偏远的订单
        if ($isRemotCity) {
            //偏远城市，计算偏远费
            $pianyuan = Service_OtherFee::getByField("PIANYUAN", "fee_code", "*");
            if (!empty($pianyuan)) {
                $customerFeeCondition = array(
                    'customer_code' => $logisticOrderInfo ['customer_code'],
                    'fee_id' => $pianyuan ['fee_id']
                );
                $customerOtherFee = Service_CustomerOtherFee::getByCondition($customerFeeCondition, '*');
                $smCode = $logisticOrderInfo['sm_code'];
                $pianyuanFee = $pianyuan ['fee_value'];
                $discount = 1;

                $cost = $pianyuan['fee_amount'];
                if ('1' == $pianyuan ['status']) {
                    // 杂费状态：可用
                    if (!empty($customerOtherFee)) {
                        if ($customerOtherFee [0] ['status'] == '1') {
                            // 客户杂费可用，则参与打折计算
                            $pianyuanFee = $customerOtherFee [0] ['discount'] * $pianyuanFee;
                            $discount = $customerOtherFee [0] ['discount'];
                        }
                    } else {
                        // 非默认费用且该客户无此项杂费设置，则此项费用不收
                        if ('0' == $pianyuan ['is_default_fee']) {
                            $pianyuanFee = 0;
                            $cost = 0;
                        }
                    }
                } else {
                    // 杂费状态：不可用
                    $pianyuanFee = 0;
                    $cost = 0;
                }
                $pianyuanFeeList = array(
                    'cost_currency_code' => $pianyuan ['cost_currency_code'],
                    'currency_code' => $pianyuan ['fee_currency_code'],
                    'price' => $pianyuanFee,
                    'discount' => $discount,
                    'cost' => $cost,
                    'sp_code' => $pianyuan ['sp_code'],
                    'fee_id' => $pianyuan ['fee_id']
                );
                return $pianyuanFeeList;
            }
        }
        return '';
    }

}
