<?php

class Service_RecordSingleProcess extends Common_Service {

    protected $_OrderCode = null;
    protected $_Order = null;
    protected $_errorArr = array();
    protected $_params = array();
    protected $_date = '';

    private function setData($params = array()) {
        $keys = array(
            'order_code' => '',
            'totalpiecs' => 0,
            'piecesDetail' => array(),
        );
        foreach ($keys as $key => $val) {
            $this->_params[$key] = isset($params[$key]) ? $params[$key] : $val;
        }
        $this->_userId = Service_User::getUserId();
        $this->_warehouseId = Service_User::getUserWarehouseId();
        $this->_Order = Service_Orders::getByField($this->_params['order_code'], 'order_code');
        $this->orderAddress = Service_OrderAddressBook::getByField($this->_params['order_code'], 'order_code');
    }

    public static function getOneWorldExpressSmCodes() {
        return array(
            'BH-3HPA',
            'BH-3H',
            'BH-UKECSLTYD',
            'BH-UKECSLTRM',
            'BH-CORREOS',
            'BH-19EURDPDDE',
            'BH-DAC',
            'BH-SL018',
            'BH-IESLTANPOST'
        );
    }

    public static function getBaseDhlSmCodes() {
        return array('HKDHL','CNDHL','BH-HKDHL','WWDHLP','WWDHLU');
    }

    public static function getZheMengDhlSmCodes() {
        return array('DHL-TH');
    }

    private function valid() {
        $piecesDetail = $this->_params['piecesDetail'];
        if (isset($this->_params['order_code']) && $this->_params['order_code'] != '') {
            if (empty($this->_Order)) {
                $this->_errorArr[] = array('errorCode' => '30002', 'errorMsg' => "该订单不存在");
            } else {
                if ($this->_Order['order_status'] != '7') {
                    $this->_errorArr[] = array('errorCode' => '30003', 'errorMsg' => "订单不是已打包状态,不能录单");
                }
                if ($this->_Order['order_status'] != '7') {
                    $this->_errorArr[] = array('errorCode' => '30004', 'errorMsg' => "订单不是已打包状态,不能录单");
                }
                $allowShip = array_merge( self::getBaseDhlSmCodes(), self::getOneWorldExpressSmCodes(), self::getZheMengDhlSmCodes() );
                if(!in_array($this->_Order['sm_code'],$allowShip)){
                        $this->_errorArr[] = array('errorCode' => '30005', 'errorMsg'=>"订单渠道非".implode(',',$allowShip).'不能录单');
                }
                /* if($this->_Order['order_mode_type']!='1'){
                  $this->_errorArr[] = array('errorCode' => '30005', 'errorMsg'=>"必须是集货模式的订单才能录单");
                  } */
            }
        } else {
            $this->_errorArr[] = array('errorCode' => '30006', 'errorMsg' => "订单号必填");
        }
        if (!(isset($this->_params['totalpiecs']) && is_int($this->_params['totalpiecs'] + 0) && $this->_params['totalpiecs'] > 0)) {
            $this->_errorArr[] = array('errorCode' => '30007', 'errorMsg' => " PIECE数必须是大于0的整数");
        }

        $oneWorldExpressSmCodes = self::getOneWorldExpressSmCodes();
        $shiMengSmCodes = self::getZheMengDhlSmCodes();

        if ( ( in_array($this->_Order['sm_code'], $oneWorldExpressSmCodes) || in_array( $this->_Order['sm_code'], $shiMengSmCodes ) ) && $this->_params['totalpiecs'] != 1) {
            $this->_errorArr[] = array('errorCode' => '30007', 'errorMsg' => "该渠道PIECE数必须等于1");
        }
        if (!empty($piecesDetail)) {
            //校验
            foreach ($piecesDetail as $key => $val) {
                $index = $key + 1;
                // 长度验证
                if (is_int($val['length'] + 0)) {
                    if (!in_array($this->_Order['sm_code'], $oneWorldExpressSmCodes)) {
                        if ($val['length'] <=1) $this->_errorArr[] = array('errorCode' => '30008', 'errorMsg' => "PIECE{$index}长必须是大于1的正整数");
                    } else {
                        if (in_array($this->_Order['sm_code'], array('BH-3HPA', 'BH-UKECSLTYD')) && $val['length'] > 45) {
                            $this->_errorArr[] = array('errorCode' => '30008', 'errorMsg' => "PIECE{$index}长不能大于45cm");
                        }
                        if ($this->_Order['sm_code'] == 'BH-UKECSLTRM' && $val['length'] > 61) {
                            $this->_errorArr[] = array('errorCode' => '30008', 'errorMsg' => "PIECE{$index}长不能大于61cm");
                        }
                        if (in_array($this->_Order['sm_code'], array('BH-SL018', 'BH-IESLTANPOST')) && $val['length'] > 100) {
                            $this->_errorArr[] = array('errorCode' => '30008', 'errorMsg' => "PIECE{$index}长不能大于100cm");
                        }
                        if (in_array($this->_Order['sm_code'], array('BH-3H', 'BH-CORREOS', 'BH-DAC')) && $val['length'] > 120) {
                            $this->_errorArr[] = array('errorCode' => '30008', 'errorMsg' => "PIECE{$index}长不能大于120cm");
                        }

                    }
                } else {
                    $this->_errorArr[] = array('errorCode' => '30008', 'errorMsg' => "PIECE{$index}长必填");
                }

                // 宽度验证
                if (is_int($val['width'] + 0)) {
                    if (!in_array($this->_Order['sm_code'], $oneWorldExpressSmCodes)) {
                        if ($val['width'] <=1) $this->_errorArr[] = array('errorCode' => '30009', 'errorMsg' => "PIECE{$index}宽必须是大于1的正整数");
                    } else {
                        if (in_array($this->_Order['sm_code'], array('BH-3HPA', 'BH-UKECSLTYD')) && $val['width'] > 35) {
                            $this->_errorArr[] = array('errorCode' => '30009', 'errorMsg' => "PIECE{$index}长不能大于35cm");
                        }
                        if ($this->_Order['sm_code'] == 'BH-UKECSLTRM' && $val['width'] > 46) {
                            $this->_errorArr[] = array('errorCode' => '30009', 'errorMsg' => "PIECE{$index}长不能大于46cm");
                        }
                    }
                } else {
                    $this->_errorArr[] = array('errorCode' => '30009', 'errorMsg' => "PIECE{$index}宽必填");
                }

                // 高度验证
                if (is_int($val['height'] + 0)) {
                    if (!in_array($this->_Order['sm_code'], $oneWorldExpressSmCodes)) {
                        if ($val['height'] <=1) $this->_errorArr[] = array('errorCode' => '30010', 'errorMsg' => "PIECE{$index}宽必须是大于1的正整数");
                    } else {
                        if (in_array($this->_Order['sm_code'], array('BH-3HPA', 'BH-UKECSLTYD')) && $val['height'] > 20) {
                            $this->_errorArr[] = array('errorCode' => '30010', 'errorMsg' => "PIECE{$index}长不能大于20cm");
                        }
                        if ($this->_Order['sm_code'] == 'BH-UKECSLTRM' && $val['height'] > 46) {
                            $this->_errorArr[] = array('errorCode' => '30010', 'errorMsg' => "PIECE{$index}长不能大于46cm");
                        }
                    }
                } else {
                    $this->_errorArr[] = array('errorCode' => '30010', 'errorMsg' => "PIECE{$index}宽必填");
                }

                // 重量验证
                if (!is_numeric($val['weight'] + 0) || $val['weight'] <= 0) {
                    $this->_errorArr[] = array('errorCode' => '30011', 'errorMsg' => "PIECE{$index}重量必填,且必须是大于0的数字");
                }
                if ($this->_Order['sm_code'] == 'BH-UKECSLTRM' && $val['weight'] > 2) {
                    $this->_errorArr[] = array('errorCode' => '30011', 'errorMsg' => "PIECE{$index}重量必填,且必须是小于等于2的数字");
                }
                if (in_array($this->_Order['sm_code'], array('BH-3HPA', 'BH-UKECSLTYD')) && $val['weight'] > 3) {
                    $this->_errorArr[] = array('errorCode' => '30011', 'errorMsg' => "PIECE{$index}重量必填,且必须是小于等于3的数字");
                }
                if (in_array($this->_Order['sm_code'], array('BH-3H', 'BH-CORREOS', 'BH-19EURDPDDE', 'BH-DAC', 'BH-SL018', 'BH-IESLTANPOST')) && $val['weight'] > 30) {
                    $this->_errorArr[] = array('errorCode' => '30011', 'errorMsg' => "PIECE{$index}重量必填,且必须是小于等于30的数字");
                }

                if (empty($val['op_description'])) {
                    $this->_errorArr[] = array('errorCode' => '30012', 'errorMsg' => "PIECE{$index}品名,必须填写");
                }

                // 体积验证
                if ($this->_Order['sm_code'] == 'BH-3H' && $val['length']*$val['width']*$val['height'] >230000) {
                    $this->_errorArr[] = array('errorCode' => '30013', 'errorMsg' => "PIECE{$index}体积不能超过0.23立方米");
                }

                // 周长验证
                if ($this->_Order['sm_code'] == 'BH-SL018' && $val['length']+$val['width']+$val['height'] > 150) {
                    $this->_errorArr[] = array('errorCode' => '30013', 'errorMsg' => "PIECE{$index}长宽高之和不能超过150cm");
                }
                if ($this->_Order['sm_code'] == 'BH-CORREOS' && $val['length']+$val['width']+$val['height'] > 210) {
                    $this->_errorArr[] = array('errorCode' => '30013', 'errorMsg' => "PIECE{$index}长宽高之和不能超过210cm");
                }
                if (in_array($this->_Order['sm_code'], array('BH-19EURDPDDE', 'BH-DAC', 'BH-IESLTANPOST')) && $val['length']+$val['width']+$val['height'] > 270) {
                    $this->_errorArr[] = array('errorCode' => '30013', 'errorMsg' => "PIECE{$index}长宽高之和不能超过270cm");
                }
            }
        }
    }

    /**
     * @author william-fan
     * @todo 用于录单操作
     */
    public function recordSingle($params = array()) {
        $result = array(
            'state' => 0,
            'error' => array(),
            'message' => '录单失败'
        );
        $this->setData($params);
        $shipOrder = Service_ShipOrder::getByField($this->_Order['order_code'], 'order_code');
        if (in_array($params['sm_code'], array('HKDHL', 'CNDHL', 'BH-HKDHL','DHL-TH','WWDHLP','WWDHLU'))) {
            $apiDhlRow = Service_ApiDhl::getByField($this->_Order['order_code'], 'order_code');
            if(empty($apiDhlRow)){
                $insertRow['order_code'] = $this->_Order['order_code'];
                $insertRow['so_code'] = $shipOrder['so_code'];
                $insertRow['status'] = 1;
                $insertRow['create_time'] = date('Y-m-d H:i:s');
                Service_ApiDhl::add($insertRow);
            }
        }

        $this->valid();
        if (!empty($this->_errorArr)) {
            $result['error'] = $this->_errorArr;
            return $result;
        }
        $warming = array();
        try {
            $db = Common_Common::getAdapter();
            $db->beginTransaction();
            $dateTime = date('Y-m-d H:i:s', time());
            $order_code = $this->_Order['order_code'];
            $result['order_code'] = $order_code;
            $piecesDetail = $this->_params['piecesDetail'];
            //print_r($piecesDetail);
            $apisoCode = '';
            if (!empty($shipOrder)) {
                $apisoCode = $shipOrder['so_code'];
            }
            $shipMethod = Service_ShippingMethod::getByField($this->_Order['sm_code'], 'sm_code');
            if (empty($shipMethod) || $shipMethod['sm_vol_rate'] <= 0) {
                throw new Exception("运输方式体积转换率必须大于0");
            }
            switch($this->_Order['sm_code']){
                case 'BH-HKDHL':
                    $dhlApiProcess = new Service_BHHKDHLApiProcess($order_code, $apisoCode, $piecesDetail);
                    $apiResult = $dhlApiProcess->runAPI();
                    break;
                case 'WWDHLP':
                case 'WWDHLU':
                case 'HKDHL':
                case 'CNDHL':
                    $dhlApiProcess = new Service_DHLApiProcess($order_code, $apisoCode, $piecesDetail);
                    $apiResult = $dhlApiProcess->runAPI();
                    break;
                case 'DHL-TH':
                    $obj = new Service_DHLTHApiProcess();
                    $apiResult = $obj->createOrder( $order_code, $piecesDetail );
                    $warming = $obj->getWarming();
                    break;
                case 'BH-3HPA':
                case 'BH-3H':
                case 'BH-UKECSLTYD':
                case 'BH-UKECSLTRM':
                case 'BH-CORREOS':
                case 'BH-19EURDPDDE':
                case 'BH-DAC':
                case 'BH-SL018':
                case 'BH-IESLTANPOST':
                    $apiResult = array('ask' => '0', 'message' => '');
                    // 1创建包裹 2获取包裹标签
                    // step 1.
                    $dhlApiProcess = new Service_OneWorldExpressApiProcess();
                    $apiParcels = $dhlApiProcess->parcels($order_code, $piecesDetail);
                
                    if (!$apiParcels['Succeeded'] && mb_substr($apiParcels['Error']['Message'], 0, 24) != '客单号 '.$order_code.' 己经存在' ) {
                        $apiResult['message'] = $apiParcels['Error']['Message'];
                    } else {
                        if ($apiParcels['Succeeded'] == true) {
                            // 调用成功
                            $processCode = $apiParcels['Data']['ProcessCode'];
                            $trackingNumber = $apiParcels['Data']['TrackingNumber'];
                        } else {
                            // 调用失败且已存在 需要调用获取包裹接口获取运单号
                            $processCode = substr($apiParcels['Error']['Message'], -18);
                            $apiGetParcels = $dhlApiProcess->getParcels($processCode);
                            if (isset($apiGetParcels['Data']) && $apiGetParcels['Data']['TrackingNoProcessResult']['Code'] == 'Success') {
                                $trackingNumber = $apiGetParcels['Data']['FinalTrackingNumber'];
                            } else {
                                $apiResult['message'] .= $apiGetParcels['Data']['TrackingNoProcessResult']['Message'];
                            }
                        }
                        if (isset($trackingNumber)&&!empty($trackingNumber)) {
                            $pdfPath = $dhlApiProcess->getParcelsLabel($order_code, $processCode);
                            $apiResult = array(
                                'ask' => 1,
                                'PDF' => $pdfPath,
                                'AirwayBillNumber' => $trackingNumber, //跟踪号
                                'LicensePlates' => $trackingNumber,
                            );
                        }
                    }
                    break;
            }
            //var_dump($apiResult['ask']==0);
            if ($apiResult['ask'] == '0') {
                throw new Exception($apiResult['message']);
            }
            $pdfPath = $apiResult['PDF'];
            $encodePath = base64_encode($pdfPath);
            $tracking_number = $apiResult['AirwayBillNumber']; //跟踪号
            $subTrackingNumber = $apiResult['LicensePlates'];


            //print_r($apiResult);
            $so_weight = 0;
            $so_volWeight = 0;
            $updateOrder = array(
                'order_status' => '14',
                'update_time' => date('Y-m-d H:i:s', time()),
            );
            if(in_array($this->_Order['sm_code'], array('BH-HKDHL', 'BH-3HPA', 'BH-3H', 'BH-UKECSLTYD', 'BH-UKECSLTRM', 'BH-CORREOS', 'BH-19EURDPDDE', 'BH-DAC', 'BH-SL018', 'BH-IESLTANPOST','DHL-TH'))){
                $updateOrder['ref_tracking_number']=$tracking_number;
            }
            Service_Orders::update($updateOrder, $this->_Order['order_code'], 'order_code');
            //添加日志
            $orderLog = array(
                'order_id' => $this->_Order['order_id'],
                'order_code' => $this->_Order['order_code'],
                'ol_type' => '0',
                'order_status_from' => $this->_Order['order_status'],
                'order_status_to' => '14',
                'ol_add_time' => $dateTime,
                'user_id' => $this->_userId,
                'ol_ip' => Common_Common::getIP(),
                'ol_comments' => '录单操作',
            );
            Service_OrderLog::add($orderLog);
            //调用hkdhl接口信息 
            $interfaceInfo = array();
            //$tracking_number = $this->_Order['order_code'];

            Service_ShipOrderDetail::delete($order_code, 'order_code'); //删除ship_order_detail数据

            if (!empty($shipOrder)) {
                //在Ship_Order表插入一条数据，Tracking_No为订单号
                //存在就更新数据
                $shipOrderRow = array(
                    'tracking_number' => $tracking_number,
                    'file_path' => $pdfPath,
                    'so_update_time' => date("Y-m-d H:i:s", time()),
                    'so_piece' => $params['totalpiecs'],
                );
                Service_ShipOrder::update($shipOrderRow, $order_code, 'order_code');
                $soId = $shipOrder['so_id'];
                $soCode = $shipOrder['so_code'];
            } else {
                $soCode = $soCode = Common_GetNumbers::getCode('shiporder', $this->_Order['customer_code'], 'SP');
                //不存在就插入数据
                $shipOrderRow = array(
                    'so_code' => $soCode,
                    'order_id' => $this->_Order['order_id'],
                    'order_code' => $this->_Order['order_code'],
                    'tracking_number' => $tracking_number,
                    'warehouse_id' => $this->_warehouseId,
                    'pp_barcode' => '',
                    'sm_code' => $this->_Order['sm_code'],
                    'so_status' => '0',
                    'so_weight' => '',
                    'so_vol_weight' => '',
                    'so_length' => '',
                    'so_width' => '',
                    'so_height' => '',
                    'so_declared_value' => '',
                    'so_shipping_fee' => '',
                    'currency_code' => '',
                    'so_add_time' => $dateTime,
                    'so_ship_time' => $dateTime,
                    'so_update_time' => $dateTime,
                    'file_path' => $pdfPath,
                    'so_piece' => $params['totalpiecs'],
                );
                $soId = Service_ShipOrder::add($shipOrderRow);
            }


            foreach ($piecesDetail as $key => $value) {
                $so_weight +=$value['weight'];
                //获取order_product信息
                $orderProduct = Service_OrderProduct::getByField($value['op_id']);
                $product = array();
                if (!empty($orderProduct)) {
                    $product = Service_Product::getByField($orderProduct['product_id']);
                }
                $op_subtotal = 0;
                if (!empty($product)) {
                    $op_subtotal = $orderProduct['op_quantity'] * $product['product_sales_value'];
                }
                $volWeight = ($value['length'] * $value['width'] * $value['height']) / $shipMethod['sm_vol_rate'];
                $so_volWeight+=$volWeight;
                $sub_tracking_number = isset($subTrackingNumber[$key]) ? $subTrackingNumber[$key] : '';
                if(in_array($this->_Order['sm_code'], array('BH-3HPA', 'BH-3H', 'BH-UKECSLTYD'))){
                    $sub_tracking_number = 'J'.$tracking_number;
                }elseif(in_array($this->_Order['sm_code'], array('BH-HKDHL', 'BH-UKECSLTRM', 'BH-CORREOS', 'BH-19EURDPDDE', 'BH-DAC', 'BH-SL018', 'BH-IESLTANPOST','DHL-TH'))){
                    $sub_tracking_number = $tracking_number;
                }else{
                    //noting to do
                }
                $shipOrderDetailRow = array(
                    'so_code' => $soCode,
                    'so_id' => $soId,
                    'order_id' => $this->_Order['order_id'],
                    'order_code' => $this->_Order['order_code'],
                    'sub_tracking_number' => $sub_tracking_number,
                    'op_id' => $value['op_id'],
                    'op_title' => !empty($product) ? $product['product_title'] : '',
                    'sod_length' => $value['length'],
                    'sod_width' => $value['width'],
                    'sod_height' => $value['height'],
                    'sod_weight' => $value['weight'],
                    'sod_vol_weight' => $volWeight,
                    'sod_quantity' => $orderProduct['op_quantity'],
                    'op_description' => $value['op_description'],
                    'cn_description' => !empty($product) ? $product['product_title'] : '',
                    'hs_code' => !empty($product) ? $product['hs_code'] : '',
                    'op_unit_price' => !empty($product) ? $product['product_sales_value'] : '',
                    'op_subtotal' => $op_subtotal,
                    'op_origin' => '',
                    'op_declared_value' => !empty($product) ? $product['product_declared_value'] : '',
                );
                Service_ShipOrderDetail::add($shipOrderDetailRow);
            }
            $originWeight = $so_weight;
            $so_weight = ($so_weight > $so_volWeight) ? $so_weight : $so_volWeight;
            $shipOrderRow = array(
                'so_weight' => $originWeight,
                'so_vol_weight' => $so_volWeight
            );

            $objCalculate = new Common_CalculateShipping();
            $keys = array(
                'warehouseId' => $this->_warehouseId,
                'countryId' => $this->orderAddress['oab_country_id'],
                'smCode' => $this->_Order['sm_code'],
                'weight' => $so_weight,
                'realWeight' => $so_weight,
                'order_code' => $order_code,
                'customerCode' => $this->_Order['customer_code'],
            );

            $objCalculate->setParams($keys);
            $aCalculate = $objCalculate->getRate();

            $fee_weight = isset($aCalculate['data']['cost']['fee_weight']) ? $aCalculate['data']['cost']['fee_weight'] : 0;
            if (isset($fee_weight) && $fee_weight > 0) {
                $shipOrderRow['so_fee_weight'] = $fee_weight;
            } else {
                $shipOrderRow['so_fee_weight'] = $so_weight;
            }
            Service_ShipOrder::update($shipOrderRow, $order_code, 'order_code');
            $orders =   Service_Orders::getByField($order_code , 'order_code' , array('is_remote_city'));
            if($orders['is_remote_city']==1){
                Service_Exception::addExceptionByCode('theGoodsInRemoteAreas' , $order_code);
            }
            //$db->rollBack();
            $db->commit();
            $result['state'] = '1';
            $result['path'] = $encodePath;
            $result['message'] = '录单成功';
        } catch (Exception $e) {
            $db->rollBack();
            $result['error'][] = array(
                'errorCode' => '50000',
                'errorMsg' => $e->getMessage()
            );
        }
        $result['warming'] = $warming;
        return $result;
    }

}
