<?php

class Default_SoapController extends Ec_Controller_DefaultAction {

    public $appKey;
    public $appToken; //是否用验证码
    public $error = '';
    //appkey FE4713B02DAA22EEF9DFEA67EB875E2DF8DE0D8C5F9EB9966A2FD42927EABF0AC1D2405C77520500377DAB26189FEE63A236E4F99F36A9E5312CFBA95FFD2421
    public function preDispatch() {
    }

    private function validateCustomer($token, $key) {
        $this->appToken = $token;
        $this->appKey = $key;
        if($this->appToken!='GLOBEXBHHKDL'||$this->appKey!=strtoupper(hash('sha512',hash('md5','GLOBEXBHHKDLRECORDEORDER')))){
            $this->error=true;
        }
    }

    public function recordSingleAction() {
        $return = array('state' => '0', 'errorMessage' => 'No data');
        if ($this->_request->isPost()) {
            try {
                $token = $this->_request->getPost('AppToken');
                $appKey = $this->_request->getPost('AppKey');
                $shipmentrequest=$this->_request->getPost('ShipmentRequest');
                $this->validateCustomer($token, $appKey);
                if ($this->error) {
                    throw new Exception('AppToken或AppKey错误');
                }
                if(empty($shipmentrequest)){
                    throw new Exception('提交内容错误');
                }
                $requestXmlObj=  simplexml_load_string($shipmentrequest);
                if($requestXmlObj==false){
                    throw new Exception('不规范的请求内容');
                }
                $requestArray=  Common_Common::objectToArray($requestXmlObj);
                 $this->validateCustomer($requestArray['Header']['AppToken'], $requestArray['Header']['AppKey']);
                if ($this->error) {
                    throw new Exception('AppToken或AppKey错误');
                }

                if(isset($requestArray['OrderInfo']['Piece'])){
                        if(!isset($requestArray['OrderInfo']['Piece'][0])){
                            $pieceOne=$requestArray['OrderInfo']['Piece'];
                            unset($requestArray['OrderInfo']['Piece']);
                            $requestArray['OrderInfo']['Piece'][0]=$pieceOne;
                        }
                }else{
                    throw new Exception('产品详细信息为空');
                }
                $orderCode=$requestArray['OrderInfo']['OrderCode'];
                if(empty($orderCode)){
                    throw new Exception('订单号为空');
                }
                $orderInfo=  Service_Orders::getByField($orderCode,'order_code');
                if(!in_array($orderInfo['sm_code'],array('BH-HKDHL'))){
			throw new Exception('必须是BH-HKDHL的运输方式才能录单');
		}else{
                    if(empty($orderInfo)){
                            throw new Exception('输入订单不存在');
                    }elseif($orderInfo['order_status']!='7'){
                            throw new Exception('订单不是已打包状态,不能录单');
                    }
                }
                $purpose_totalDeclare= Service_OrderProduct::sumPurposeDeclaredValue($orderInfo['order_code']);
                $addressList=Service_OrderAddressBook::getByCondition(array('order_code'=>$orderCode),'*');
                $shipMethod = Service_ShippingMethod::getByField($orderInfo['sm_code'],'sm_code');
                $orderAddress = array(); //收件人
                $orderSendAddress = array(); //发件人
                foreach($addressList as $addressRow) {
                        $country_name = "";
                        if($addressRow['oab_country_id']>0){
                                $country = Service_Country::getByField($addressRow['oab_country_id']);
                                if(!empty($country)){
                                        $country_name = $country['country_name'];
                                }
                        }
                        $addressRow['country_name'] = $country_name;
                        if($addressRow['oab_type']=='0') $orderAddress = $addressRow;
                        else if($addressRow['oab_type']=='1') $orderSendAddress = $addressRow;
                }
                 $invoceContry=Service_ShippingMethodConfig::getInvoiceContry();
                 if (in_array($orderAddress['oab_country_id'],$invoceContry)) {
                       if($orderAddress['oab_country_id']!='251'){
                          $orderInfo['invoiceTip']= '该订单需提供正本发票';
                       }else{
                           if($purpose_totalDeclare>Service_ShippingMethodConfig::$purPusDecalar){
                               $orderInfo['invoiceTip']= '该订单需提供正本发票';
                           }
                       }
                }
                $orderProductCondition=array(  'order_code' => $orderInfo['order_code'] );
                $orderProduct = Service_OrderProduct::getByCondition($orderProductCondition,array('product_id', 'op_quantity','product_barcode'));
                $productSku=array();
                foreach ($orderProduct as $key => $value) {
                    $product = Service_Product::getByField($value['product_id'], 'product_id', array('product_weight','product_sku'));
                    if (isset($product['product_weight']) && $product['product_weight']){
                        $productNetWeight += $product['product_weight'] * $value['op_quantity'];
                    }
                    $productSku[$product['product_sku']]=$value['product_id'];
                }
                $netWeight=0;
                $piecesDetail = array();
                $notExitProduct=array();
                foreach($requestArray['OrderInfo']['Piece'] as $key=>$value){
                    $netWeight+=$value['Weight'];
                    $prodcutId='';
                   if(isset($productSku[$value['ProductSku']])){
                       $prodcutId=$productSku[$value['ProductSku']];
                   }else{
                       $notExitProduct[]=$value['ProductSku'];
                   }
                    $detail = array(
                        'length' => $value['Length'],
                        'width' => $value['Width'],
                        'height' => $value['Height'],
                        'weight' => $value['Weight'],
                        'op_description' => $value['Title'],
                        'op_id' => $prodcutId,
                    );
                    $piecesDetail[] = $detail;
                }
                if(!empty($notExitProduct)){
                    throw new Exception('产品'.implode(',',  array_unique($notExitProduct)).'不属于该订单');
                }
               if ($netWeight < $productNetWeight) {
                   throw new Exception('包裹总重量不能小于产品总净重','50000');
                }
                $params=array(
                    'order_code'=>$orderInfo['order_code'],
                  'totalpiecs'=>count($piecesDetail),
                   'piecesDetail'=>$piecesDetail,
                );
                 $recordSingleObj = new Service_RecordSingleProcess();
                $result = $recordSingleObj->recordSingle($params);
                if($result['state']==1){
                    unset($return['errorMessage']);
                    $return['message']='录单成功';
                    if($orderInfo['invoiceTip']){
                         $return['message'].=','.$orderInfo['invoiceTip'];
                    }
                    $trackingNumber=  Service_Orders::getByField($orderInfo['order_id'], 'order_id', 'ref_tracking_number');
                    $pdf=  Service_OrdersLabel::getByField($orderInfo['order_code'], 'order_code');
                    if(empty($pdf)){
                         if(!empty($trackingNumber)){
                            $bhhkdhlService=new Service_BHHKDHLApiProcess($orderInfo['order_code'], '', '');
                            $bhhkdhlService->setWaybillNumber($trackingNumber);
                            $bhhkdhlService->generatePdf();
                            $pdf=  Service_OrdersLabel::getByField($orderInfo['order_code'], 'order_code');
                        }
                    }
                    $return['TrackingNumber']=$trackingNumber['ref_tracking_number'];
                    $return['label']=$pdf['ol_content'];
                    $return['state']=1;
                }else{
                    $errorArray=array();
                    foreach($result['error'] as $error){
                        $errorArray[]=$error['errorMsg'];
                    }
                    $return['errorMessage']=implode(',',$errorArray);
                }
              
            } catch (Exception $e) {
                $return['errorMessage'] = $e->getMessage();
            }
        }
        header('content-type:text/xml;charset=UTF-8');
        echo Common_Common::assocArrayToXML($return);
    }
}
