<?php
class Process_OutsideLogistics
{
        private $_userId;
        private $_warehouseId;
        private $_Order;
        protected $_errorArr = array();
        public function dealSinglePostData($post){
			$lengthData = isset($post['length'])?$post['length']:array();
			$widthData =isset($post['width'])?$post['width']:array(); 
			$heightData = isset($post['height'])?$post['height']:array();
			$weightData = isset($post['weight'])?$post['weight']:array();
			$opIdData = isset($post['op_id'])?$post['op_id']:array();
			$totalpiecs =isset($post['totalpiecs'])?$post['totalpiecs']:array();
			$enameData	= isset($post['ename'])?$post['ename']:array();		
			$piecesDetail = array();
			foreach($lengthData as $key=>$length){
				 $detail = array(
                                                'length'=>$length,
                                                'width'=>$widthData[$key],
                                                'height'=>$heightData[$key],
                                                'weight'=>$weightData[$key],
                                                'op_description'=>$enameData[$key],
                                                'op_id'=>$opIdData[$key]
							);
				 $piecesDetail[] = $detail;
			}
			$post['piecesDetail'] = $piecesDetail;
            return $post;
        }
    private function setData($params = array()) {
        $keys = array(
            'order_code' => '',
            'totalpiecs' => 0,
            'piecesDetail' => array(),
        );
        foreach ($keys as $key => $val) {
            if(isset($params[$key])){
                if(is_array($params[$key])){
                    $this->_params[$key]= $params[$key];
                }else{
                     $this->_params[$key]=trim($params[$key]);
                }
            }else{
                 $this->_params[$key] =$val;
            }
        }
        $this->_userId = Service_User::getUserId();
        $this->_warehouseId = Service_User::getUserWarehouseId();
        $this->_Order = Service_LogisticsOrder::getByField( $this->_params['order_code'], 'logistics_code');
        $this->orderAddress = Service_LogisticsOrderAddress::getByField($this->_params['order_code'], 'logistics_code');
    }
    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['lo_status'] != '2') {
                    $this->_errorArr[] = array('errorCode' => '30003', 'errorMsg' => "订单不是已提交状态,不能录单");
                }
                if($this->_Order['sm_code']!='HKDHL'){
                        $this->_errorArr[] = array('errorCode' => '30005', 'errorMsg'=>"订单渠道非HKDHL,不能录单");
                }
            }
        } 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的整数");
        }
        if (!empty($piecesDetail)) {
            //校验
            foreach ($piecesDetail as $key => $val) {
                $index = $key + 1;
                if (!is_int($val['length'] + 0) || $val['length'] <= 1) {
                    $this->_errorArr[] = array('errorCode' => '30008', 'errorMsg' => "PIECE{$index}长必填,且必须是大于1的正整数");
                }//var_dump($val['width']);
                if (!is_int($val['width'] + 0) || $val['width'] <= 1) {
                    $this->_errorArr[] = array('errorCode' => '30009', 'errorMsg' => "PIECE{$index}宽必填,且必须是大于1的正整数");
                }
                if (!is_int($val['height'] + 0) || $val['height'] <= 1) {
                    $this->_errorArr[] = array('errorCode' => '30010', 'errorMsg' => "PIECE{$index}高必填,且必须是大于1的正整数");
                }
                if (!is_numeric($val['weight'] + 0) || $val['weight'] <= 0) {
                    $this->_errorArr[] = array('errorCode' => '30011', 'errorMsg' => "PIECE{$index}重量必填,且必须是大于0的数字");
                }
                if (empty($val['op_description'])) {
                    $this->_errorArr[] = array('errorCode' => '30012', 'errorMsg' => "PIECE{$index}品名,必须填写");
                }
            }
        }
    }
    public function isRemoteCity($country_id, $city_name, $postcode) {
        $aCity = Service_City::getByWhere(array('country_id'=>$country_id, 'city_name'=>strtoupper($city_name)));
        if(!empty($aCity)) {
            if($aCity['is_remote']==1) {
                return true;
            } else {
                $condition = array(
                    'country_id'=>$country_id,
                    'postcode_no'=>$postcode,
                    'is_remote'=>'1',
                );
                $counts = Service_Postcode::getByCondition($condition,'count(*)');
                if($counts>0){
                    return true;
                }else{
                    $condition = array(
                        'country_id'=>$country_id,
                        'postcode_no_start'=>$postcode,
                        'postcode_no_end'=>$postcode,
                        'is_remote'=>'1'
                    );
                    $counts = Service_Postcode::getByCondition($condition,'count(*)');
                    if($counts>0){
                        return true;
                    }
                }
            }
        }
        return false;
    }
   public function recordSingle($params){
         $result = array(
            'state' => 0,
            'error' => array(),
            'message' => '录单失败'
        );
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        $this->setData($params);

        $this->valid();
        if (!empty($this->_errorArr)) {
            $result['error'] = $this->_errorArr;
            return $result;
        }
        try {
            $dateTime = date('Y-m-d H:i:s', time());
            $order_code = $this->_Order['logistics_code'];
            $result['order_code'] = $order_code;
            $shipOrder =  Service_OutsideShipOrder::getByField($order_code, 'logistics_code');
            $piecesDetail = $this->_params['piecesDetail'];
            //print_r($piecesDetail);
            $apisoCode = $order_code;
            
            $shipMethod = Service_ShippingMethod::getByField($this->_Order['sm_code'], 'sm_code');
            if (empty($shipMethod) || $shipMethod['sm_vol_rate'] <= 0) {
                throw new Exception("运输方式体积转换率必须大于0");
            }
          
            $dhlApiProcess = new Service_DHLApiProcess($order_code, $apisoCode, $piecesDetail);
            $dhlApiProcess->setXmlProcess('logistic_order');
           $apiResult = $dhlApiProcess->runAPI();
            //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'];


//            $tracking_number='sdfsdjhfslajopu';
//            $pdfPath='sfsdafaskfj';
            //print_r($apiResult);
            $so_weight = 0;
            $so_volWeight = 0;
            $updateOrder = array(
                'lo_status' => '9',
                'lo_update_time' => date('Y-m-d H:i:s', time()),
                'ref_tracking_number'=>$tracking_number,
            );
            Service_LogisticsOrder::update($updateOrder, $this->_Order['logistics_code'], 'logistics_code');
              
            //添加日志
            $orderLog = array(
                'logistics_code' => $this->_Order['logistics_code'],
                'order_status_from' => $this->_Order['lo_status'],
                'order_status_to' => '7',
                'lol_create_time' => $dateTime,
                'lol_operator' => $this->_userId,
                'lol_ip' => Common_Common::getIP(),
                'lol_comment' => '录单操作',
            );
            Service_LogisticsOrderLog::add($orderLog);
            //调用hkdhl接口信息 
            $interfaceInfo = array();
            //$tracking_number = $this->_Order['order_code'];
            Service_OutsideShipOrderDetail::delete($order_code, 'logistics_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()),
                );
                Service_OutsideShipOrder::update($shipOrderRow, $order_code, 'logistics_code');
                $soId = $shipOrder['oso_id'];
//                $soCode = $shipOrder['logistics_code'];
            } else {
//                $soCode = Common_GetNumbers::getCode('shiporder', $this->_Order['customer_code'], 'SP');
                //不存在就插入数据
                $shipOrderRow = array(
                    'logistics_code' =>  $this->_Order['logistics_code'],
                    'tracking_number' => $tracking_number,
                    'warehouse_id' => $this->_warehouseId,
                    'sm_code' => $this->_Order['sm_code'],
                    'add_time' => $dateTime,
                    'update_time' => $dateTime,
                    'file_path' => $pdfPath,
                );
                $soId = Service_OutsideShipOrder::add($shipOrderRow);
            }
            foreach ($piecesDetail as $key => $value) {
                $orderHs=  Service_LogisticsOrderHs::getByField($value['op_id'],'loh_id');
//                var_dump($orderHs,$value);
//                
                $so_weight +=$value['weight'];
                //获取order_product信息
           
                $volWeight = ($value['length'] * $value['width'] * $value['height']) / $shipMethod['sm_vol_rate'];
                $so_volWeight+=$volWeight;
                $sub_tracking_number = isset($subTrackingNumber[$key]) ? $subTrackingNumber[$key] : '';
                $shipOrderDetailRow = array(
                    'logistics_order_id' => $this->_Order['lo_id'],
                    'logistics_code' => $this->_Order['logistics_code'],
                    'sub_tracking_number' => $sub_tracking_number,
                    'op_id' => $value['op_id'],
                    'op_title' => !empty($product) ? $product['product_title'] : '',
                    'length' => $value['length'],
                    'width' => $value['width'],
                    'height' => $value['height'],
                    'weight' => $value['weight'],
                    'quantity'=>$orderHs['loh_quantity'],
                    'vol_weight' => $volWeight,
                    'op_description' => $value['op_description'],
                    'cn_description' => '',
                    'hs_code' =>  '',
                    'unit_price' =>'',
                    'declared_value' => '',
                );
                Service_OutsideShipOrderDetail::add($shipOrderDetailRow);
            }
            $originWeight = $so_weight;
            $so_weight = ($so_weight > $so_volWeight) ? $so_weight : $so_volWeight;
            $shipOrderRow = array(
                'oso_weight' => $originWeight,
                'oso_vol_weight' => $so_volWeight
            );

            $objCalculate = new Common_CalculateShipping();
            $keys = array(
                'warehouseId' => $this->_warehouseId,
                'countryId' => $this->orderAddress['loa_country'],
                '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->getFeeWeight();
              
            $fee_weight = isset($aCalculate['data']['fee_weight']) ? $aCalculate['data']['fee_weight'] : 0;
            if (isset($fee_weight) && $fee_weight > 0) {
                $shipOrderRow['oso_fee_weight'] = $fee_weight;
            } else {
                $shipOrderRow['oso_fee_weight'] = $so_weight;
            }
            Service_OutsideShipOrder::update($shipOrderRow, $order_code, 'logistics_code');
           $isRemote=$this->isRemoteCity( $this->orderAddress['loa_country'],$this->orderAddress['loa_city'],$this->orderAddress['loa_zipcode']);
            
            if($isRemote){
                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(),
            );
            return $result;
        }
        return $result;
    }
   
}