<?php

class Service_BHHKDHLApiProcess {

    private $statusKV = array('success' => 2, 'failure' => 3);
    private $_requestUrl = 'http://www.1001000.cc/predictOrder.xsv'; //'http://www.chukouoms.com/default/index/bh';
    private $_pdfRequestUrl = 'http://www.1001000.cc/PrintPDFLableServlet.xsv';
    private $_shipmentRequestUrl = 'http://www.1001000.cc/queryTrack.sv';
    private $username = '1042901API';
    private $password = '1042901';
    private $apiDhlRow = array();
    private $order_code = '';
    private $so_code = '';
    private $pieces = array();
    private $airwayBillNumber = '';
    private $dhlDataPath = '';
    private $resFileName = '';
    private $bhhkdhlPdfPath = '';
    private $error = '';
    private $result = array('ask' => 0, 'message' => '');
    private $sendfile=0;

    /**
     * 构造函数
     * @param string $order_code 订单号
     * @param string $so_code 物流单号
     * @param  array $pieces 物品详细列表
     */
    public function __construct($order_code, $so_code, $pieces,$sendfile=0) {
        $this->order_code = $order_code;
        $this->so_code = $so_code;
        $this->pieces = $pieces;
        $this->initDHLDataPath();
		$this->sendfile=$sendfile;
    }
    public function setWaybillNumber($waybillNumber){
        $this->airwayBillNumber=$waybillNumber;
    }
    /**
     * 初始化在WEB中存放文件的目录
     */
    private function initDHLDataPath() {
        $this->dhlDataPath = APPLICATION_PATH . '/../data/bhhkdhl/' . date('Y/m');
        if (!file_exists($this->dhlDataPath)) {
            $this->mkdirs($this->dhlDataPath);
        }
        $this->bhhkdhlPdfPath = APPLICATION_PATH . '/../data/pdf/BHHKDHL/';
        if (!file_exists($this->bhhkdhlPdfPath)) {
            $this->mkdirs($this->bhhkdhlPdfPath);
        }
    }

    public function mkdirs($dir) {
        $dirArray = explode('/', $dir);
        $path = array_shift($dirArray);
        while (file_exists($path)) {
            $path.='/' . array_shift($dirArray);
        }
        foreach ($dirArray as $mk) {
            $path.='/' . $mk;
            mkdir($path, 0777, true);
        }
    }

    /**
     * 检查接口记录表中是否存在数据，不存在则创建
     */
    private function checkIsExistData() {
        $this->apiDhlRow = Service_ApiDhl::getByField($this->order_code, 'order_code');
        if (empty($this->apiDhlRow)) {
            $insertRow['order_code'] = $this->order_code;
            $insertRow['so_code'] = $this->so_code;
            $insertRow['status'] = 1;
            $insertRow['create_time'] = date('Y-m-d H:i:s');
            Service_ApiDhl::add($insertRow);
            $this->apiDhlRow = Service_ApiDhl::getByField($this->order_code, 'order_code');
        }
    }

    /**
     * 请求XML文件路径
     * @return string
     */
    private function getReqFilePath() {
        return $this->dhlDataPath . '/REQ_' . $this->order_code . '.xml';
    }

    /**
     * 响应XML文件路径
     * @return string
     */
    private function getResFilePath() {
        return $this->dhlDataPath . '/RES_' . $this->order_code . '.xml';
    }

    /**
     * 标签PDF文件路径
     * @return string
     */
    private function getPdfFilePath() {
        return $this->bhhkdhlPdfPath . '/' . $this->order_code . '.pdf';
    }

    /**
     * 标签EPL2文件路径
     * @return string
     */
    private function getEpl2FilePath() {
        return $this->dhlDataPath . '/' . $this->order_code . '.epl2';
    }

    public static function http_request($url, $timeout = 300, $post = array()) {

        $ch = curl_init();
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //支持跳转
        curl_setopt($ch, CURLOPT_MAXREDIRS, 2); //可跳转的次数
        // curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1); // 检查证书中是否设置域名，并且是否与提供的主机名匹配
        //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        if (!empty($post)) {
            curl_setopt($ch, CURLOPT_POST, true);
            if (is_scalar($post)) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
            } else {
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
            }
        }
        $data = curl_exec($ch);
//        list($header) = explode("\r\n\r\n", $data);
//        if ($header == 'HTTP/1.1 100 Continue') {
//            list($header, , $data) = explode("\r\n\r\n", $data);
//        } else {
//            list($header, $data) = explode("\r\n\r\n", $data);
//        }
//        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//        if ($http_code == 301 || $http_code == 302) {
//            $matches = array();
//            preg_match('/Location:(.*?)\n/', $header, $matches);
//            $url = trim(array_pop($matches));
//            curl_setopt($ch, CURLOPT_URL, $url);
//            curl_setopt($ch, CURLOPT_HEADER, false);
//            $data = curl_exec($ch);
//        }
//        print_r($post);
//        var_dump($data);
        //var_dump(curl_getinfo($ch, CURLINFO_HEADER_OUT));
        // print_r(curl_getinfo($ch));
//        die();
        if ($data == false) {
            curl_close($ch);
        }

        @curl_close($ch);
        return $data;
    }

    /**
     * 向DHL接口发起请求
     * @return string|boolean
     */
    private function request() {
        $requestContent = file_get_contents($this->getReqFilePath());
        $request = array(
            'username' => $this->username,
            'password' => $this->password,
            'shipmentrequest' => $requestContent
        );
        $result = self::http_request($this->_requestUrl, 300, $request);
        if($result){
            file_put_contents($this->getResFilePath(), $result);
            //通过文件名判断是否请求失败
            $xmlObj = simplexml_load_string($result);
            if ((string) $xmlObj->errorcode != '') {
                $this->error = (string) $xmlObj->errorinfo;
                return false;
            }
        }else{
             $this->error = '请求返回内容为空，请尝试重新录单';
             return false;
        }
        return true;
    }

    /**
     * 解析响应的XML文件
     */
    private function parseResFile() {
        $dom = new DOMDocument('1.0', 'UTF-8');
        $source=  file_get_contents($this->getResFilePath());
        $source=  str_replace('&', ' ', $source);
        $dom->loadXML($source);
        //运单号
        $nodes = $dom->getElementsByTagName('AWB');
        $errorInfo= $dom->getElementsByTagName('errorinfo');
        if ($nodes->length == 0) {
            if($errorInfo->length){
                $this->error=$errorInfo->item(0)->textContent;
            }else{
                 $this->error = '解析XML失败，不存在[AWB]字段';
            }
            return false;
        }
        $this->airwayBillNumber = $nodes->item(0)->textContent;
        return true;
    }

    /**
     * 获取pdf标签地址，并保存文件
     */
    public function generatePdf() {
        $pdfPath = $this->getPdfFilePath();
        $pdfRequestInfo = array(
            'username' => $this->username,
            'password' => $this->password,
            'serverewbcode' =>$this->airwayBillNumber,//1994957226
        );
        $url = $this->_pdfRequestUrl . '?' . http_build_query($pdfRequestInfo);
        $result = self::http_request($url);
        if(preg_match('/<script\s*>[^<>]+<.*script>$/iu',$result)){
            $error=preg_replace('/<script\s*>\s*alert\(([^<>]+)\).*<.*script>$/iu','$1',$result);
            $this->error=trim($error,'\'');
            return false;
        }else{
            Service_OrdersLabel::add(
                    array(
                        'order_code'=>$this->order_code,
                        'ol_time'=>date('Y-m-d H:i:s'),
                        'ol_content'=>  base64_encode($result)
                    )
                    );
			file_put_contents($pdfPath, $result);
            return true;
        }
        return false; 
    }

    public static  function queryAwbCode($orderCcode){
        $url = "http://www.1001000.com/predictOrderquery.xsv";
        $post = array(
            'customerwbCodes'=>$orderCcode,
            'username'=>'1042901API',
            'password'=>'1042901'
        );
        $ch = curl_init();
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //支持跳转
        curl_setopt($ch, CURLOPT_MAXREDIRS, 2); //可跳转的次数
        // curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 300);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
        $data = curl_exec($ch);
        if ($data == false) {
            curl_close($ch);
        }

        @curl_close($ch);
        return $data;
    }

    public static function reGetPdf($orderCode,$trackingNumber){
        $pdfRequestUrl = 'http://www.1001000.cc/PrintPDFLableServlet.xsv';
        $pdfRequestInfo = array(
            'username'=>'1042901API',
            'password'=>'1042901',
            'serverewbcode'=>$trackingNumber,//1994957226
        );
        $ch = curl_init();
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //支持跳转
        curl_setopt($ch, CURLOPT_MAXREDIRS, 2); //可跳转的次数
        // curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_URL, $pdfRequestUrl);
        curl_setopt($ch, CURLOPT_TIMEOUT, 300);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($pdfRequestInfo));

        $data = curl_exec($ch);
        if ($data == false) {
            curl_close($ch);
        }

        @curl_close($ch);

        if(preg_match('/<script\s*>[^<>]+<.*script>$/iu',$data)){
            //$error=preg_replace('/<script\s*>\s*alert\(([^<>]+)\).*<.*script>$/iu','$1',$data);
            //$this->error=trim($error,'\'');
            return false;
        }else{
            Service_OrdersLabel::add(
                array(
                    'order_code'=>$orderCode,
                    'ol_time'=>date('Y-m-d H:i:s'),
                    'ol_content'=>  base64_encode($data)
                )
            );
            $pdfPath = APPLICATION_PATH . '/../data/pdf/BHHKDHL/'.$orderCode . '.pdf';
            file_put_contents($pdfPath, $data);
            return $pdfPath;
        }
    }

    /**
     * 记录发送接口情况
     * @param int $status
     */
    private function updateApiDhl($status) {
        $ad_id = $this->apiDhlRow['ad_id'];
        unset($this->apiDhlRow['ad_id']);
        $this->apiDhlRow['comment'] = $this->error;
        $this->apiDhlRow['status'] = $this->statusKV[$status];
        $this->apiDhlRow['update_time'] = date('Y-m-d H:i:s');
        if ($status == 'success') {
            $this->apiDhlRow['airway_Bill_number'] = $this->airwayBillNumber;
            //$this->apiDhlRow['license_plate'] = implode(',', $this->aLicensePlate);
        }
        
        Service_ApiDhl::update($this->apiDhlRow, $ad_id);
    }

    /**
     * 返回结果
     * @param int $ask
     * @return array
     */
    private function getResult($ask = 0) {
        $this->result['message'] = $this->error;
        $this->result['ask'] = $ask;
        if ($ask == 1) {
            $this->result['PDF'] =  $this->getPdfFilePath();
            $this->result['AirwayBillNumber'] = $this->airwayBillNumber;
            $this->result['LicensePlates'] ='';
        }
        return $this->result;
    }

    /*
     * 生成请求接口xml文件 
     */

    public function cn_substr_utf8($str, $length, $append = '...', $start = 0) {
        if (strlen($str) < $start + 1) {
            return '';
        }
        preg_match_all("/./su", $str, $ar);
        $str2 = '';
        $tstr = '';
        //www.phpernote.com 
        for ($i = 0; isset($ar[0][$i]); $i++) {
            if (strlen($tstr) < $start) {
                $tstr.=$ar[0][$i];
            } else {
                if (strlen($str2) < $length + strlen($ar[0][$i])) {
                    $str2.=$ar[0][$i];
                } else {
                    break;
                }
            }
        }
        return $str == $str2 ? $str2 : $str2 . $append;
    }

    private function createRequestXml() {
        $ordersInfo = Service_Orders::getByField($this->order_code, 'order_code');
        $orderAddressInfo = Service_OrderAddressBook::getByField($this->order_code, 'order_code');
        $country = Service_Country::getByField($orderAddressInfo['oab_country_id']);
        $customerAddressCondition = array(
            'customer_code' => $ordersInfo['customer_code'],
            'cab_type' => 2
        );
        $customerAddress = Service_CustomerAddressBook::getByCondition($customerAddressCondition, '*', 1, 1);
        $customerAddress = $customerAddress[0];
        $sendContryCode = '';
//        $senderAddressArray=array('.','.','.');
//        if (!empty($customerAddress)) {
//            $sendCountry = Service_Country::getByField($customerAddress['cab_country_id']);
//            $sendContryCode = $sendCountry['country_code'];
//            $sendAddressArray= preg_split('/ /', $customerAddress['cab_street_address1'].$customerAddress['cab_street_address2']);
//             $splitSenderAddress = '';
//            $senderTmpAddressArray = array();
//            foreach ($sendAddressArray as $key => $address) {
//                $splitSenderAddress.=$address;
//                if (strlen($splitSenderAddress) >= 60 || strlen($splitSenderAddress) + strlen($sendAddressArray[$key + 1]) > 60) {
//                    $senderTmpAddressArray[] = $splitSenderAddress;
//                    $splitSenderAddress = '';
//                }
//                if ($key == (count($sendAddressArray) - 1)&&$splitAddress) {
//                    $senderTmpAddressArray[] = $splitSenderAddress;
//                }
//            }
//            $senderAddressArray = array_pad($senderTmpAddressArray, 3, '.');
//        }
        $personName = $orderAddressInfo['oab_firstname'] . $orderAddressInfo['oab_lastname'];
        $orderReceipAddress = $orderAddressInfo['oab_street_address1'] . $orderAddressInfo['oab_street_address2'];
        $addressArray = preg_split('//u', $orderReceipAddress);
        $splitAddress = '';
        $fomateAddressArray = array();
        foreach ($addressArray as $key => $address) {
            $splitAddress.=$address;
            if (strlen($splitAddress) >= 60 || strlen($splitAddress) + strlen($addressArray[$key + 1]) > 60) {
                $fomateAddressArray[] = $splitAddress;
                $splitAddress = '';
            }
            if ($key == (count($addressArray) - 1)&& $splitAddress) {
                $fomateAddressArray[] = $splitAddress;
            }
        }
        $fomateAddressArray = array_pad($fomateAddressArray, 3, '.');
        //泽西岛（AA9 9AA，补3位）根西岛（AA9 9AA补三位）加拿大（A9A9A9 补1位）
        $postCode=$orderAddressInfo['oab_postcode'];
        /*if(in_array($country['country_id'],array('119','473'))){
           
                 $postCode=  substr($postCode,0,-3).' '.substr($postCode, -3);
        }*/
        $reqeustInfoArray = array(
            'ServiceHeader' => array(
                'Usercode' =>$this->username,
                'Password' =>$this->password,
            ),
            'Consignee' => array(
                'PersonName' =>$personName, //收件人名
                'CompanyName' =>$orderAddressInfo['oab_company'], //收件公司
                'Address1' => $fomateAddressArray[0], //地址1
                'Address2' => $fomateAddressArray[1],
                'Address3' => $fomateAddressArray[2], //地址为空用.代替
                'City' =>$orderAddressInfo['oab_city'], //收件人城市
                'PostalCode' =>$postCode, //收件人邮编
                'CountryCode' =>$country['country_code'], //收件人国家二字代码
                'PhoneNumber' => $orderAddressInfo['oab_cell_phone'], //电话
                'FaxNumber' => '.', //传真
            ),
            'ShipmentDetails' => array(
                'Pieces' => array(
                    'Piece_1' => array(
                        'Weight' => '1',
                        'Length' => '1',
                        'Width' => '1',
                        'Height' => '1'
                    )
                ),
                'Contents' => array(
                    'Content_1' => array(
                        'Amount' => '1',
                        'UnitPrice' => '1',
                        'TotalPrice' => '1',
                        'Currency' => 'RMB',
                        'Description' => 'TEST T'
                    )
                ),
            ),
            'Shipper' => array(
                'ReferenceID' =>$this->order_code, //客户单号
                'Server' => 'HKD代理-BH', // 走货渠道
                'PersonName' =>'.',//PersonName', //发件人名
                'CompanyName' => $customerAddress['cab_company'],//'BAO HONG COMPANY', //发件人公司
                'Address1' => '.',//$senderAddressArray[0],//'address 2 home 3 test', //地址
                'Address2' =>'.',//$senderAddressArray[1],// '.', 
                'Address3' =>'.',//$senderAddressArray[2],// '.',
                'City' => '.', //发件人城市
                'PostalCode' => '.', //发件邮编
                'CountryCode' =>'.', //发件国家
                'PhoneNumber' =>'.',//$customerAddress['cab_cell_phone'],//'13952051478', //发件电话
                'FaxNumber' =>'.',//$customerAddress['cab_fax'],//'1542200', //发件传真
            ),
        );
        foreach ($this->pieces as $key => $pieces) {
            //$orderProduct=  Service_OrderProduct::getByField($pieces['op_id']);
            $itemKey = $key + 1;
            $reqeustInfoArray['ShipmentDetails']['Pieces']['Piece_' . $itemKey] = array(
                'Weight' => $pieces['weight'],
                'Width' => $pieces['width'],
                'Length' => $pieces['length'],
                'Height' => $pieces['height'],
            );
            /*$reqeustInfoArray['ShipmentDetails']['Contents']['Content_' . $itemKey] = array(
                'Amount' =>$orderProduct['op_quantity'],
                'UnitPrice' =>$orderProduct['op_purpose_declared_value'],
                'TotalPrice' =>sprintf('%.2f',$orderProduct['op_quantity']*$orderProduct['op_purpose_declared_value']),
                'Currency' => 'USD',
                'Description' => substr($pieces['op_description'], 0, 120),
            );*/
        }
        $orderProduct = Service_OrderProduct::getByCondition(array('order_code'=>$this->order_code),"*");
        $orderProductQuantity = count($orderProduct);
        $pieceQuantity = count($this->pieces);
        $diffQuantity = $orderProductQuantity - $pieceQuantity;
        $description = '';
	    //var_dump($this->pieces); 
        foreach($orderProduct as $key=>$op){
            $itemKey = $key + 1;
            //add by @Felix 1178
            if(($itemKey + $diffQuantity) <= $orderProductQuantity){
                $description = $this->pieces[$key]['op_description']; 
            }else{
                $description = substr($op['product_title_en'], 0, 120); 
            }
            $reqeustInfoArray['ShipmentDetails']['Contents']['Content_' . $itemKey] = array(
                'Amount' =>$op['op_quantity'],
                'UnitPrice' =>$op['op_purpose_declared_value'],
                'TotalPrice' =>sprintf('%.2f',$op['op_quantity']*$op['op_purpose_declared_value']),
                'Currency' => 'USD',
                'Description' => $description,
            );
        }
         
        $error = $this->validateColum($reqeustInfoArray);
        if (empty($customerAddress)) {
            array_push($error, '请联系客户维护发件人信息');
            
        }
        if(!empty($error)){
            return implode(',',$error);
        }
        $xml = self::assocArrayToXML($reqeustInfoArray, 0, 0, 'ShipmentRequestAP');
        file_put_contents($this->getReqFilePath(), $xml);
        return true;
    }

    private function validateColum($sendRow) {
        $consignee = array(
            'PersonName' => '收件人名',
            'CompanyName' => '收件公司',
            'Address1' => '地址1',
            'Address2' => '地址2',
            'Address3' => '地址3', //地址为空用.代替
            'City' => '收件人城市',
           // 'PostalCode' => '收件人邮编',
            'CountryCode' => '收件人国家二字代码',
            'PhoneNumber' => '电话',
            'FaxNumber' => '传真',
        );
        $errorInfo = array();
        foreach ($consignee as  $key => $consi) {
            if (empty($sendRow['Consignee'][$key])) {
                $errorInfo[] = $consi . '为空';
            }
        }
        $piecesItem = 0;
        foreach ($sendRow['ShipmentDetails']['Pieces'] as $key => $value) {
            $piecesItem+=1;
            if (empty($value['Weight'])) {
                $errorInfo[] = '第' . $piecesItem . '件物品重量为空';
            }
            if (empty($value['Length'])) {
                $errorInfo[] = '第' . $piecesItem . '件物品长为空';
            }
            if (empty($value['Width'])) {
                $errorInfo[] = '第' . $piecesItem . '件物品宽为空';
            }
            if (empty($value['Height'])) {
                $errorInfo[] = '第' . $piecesItem . '件物品高为空';
            }
            /*if (empty($sendRow['ShipmentDetails']['Contents']['Content_' . $piecesItem]['Description'])) {
                $errorInfo[] = '第' . $piecesItem . '件物品申报品名为空';
            }
           if (empty($sendRow['ShipmentDetails']['Contents']['Content_' . $piecesItem]['Amount'])) {
                $errorInfo[] = '第' . $piecesItem . '件物数量为空';
            }
            if (empty($sendRow['ShipmentDetails']['Contents']['Content_' . $piecesItem]['UnitPrice'])) {
                $errorInfo[] = '第' . $piecesItem . '件物申报单价为空';
            }*/
        }
        return $errorInfo;
    }

    public static function assocArrayToXML($arr, $dom = 0, $item = 0, $root = 'Request') {
        if (!$dom) {
            $dom = new DOMDocument("1.0", 'UTF-8');
        }
        if (!$item) {
            $item = $dom->createElement($root);
            $dom->appendChild($item);
        }
        foreach ($arr as $key => $val) {
            if (preg_match('/^.*_\d+?/', $key)) {
                $element = preg_replace('/^(.*)(_\d+)$/', '${1}', $key);
            } else {
                $element = $key;
            }
            $itemx = $dom->createElement(is_string($element) ? $element : "item");
            $item->appendChild($itemx);
            if (!is_array($val)) {
                $text = $dom->createTextNode($val);
                $itemx->appendChild($text);
            } else {
                self::assocArrayToXML($val, $dom, $itemx);
            }
        }
        return $dom->saveXML();
    }

    public function getTrackingInfo($orderCode) {
        $return = array();
        $orderInfo = Service_Orders::getByField($orderCode, 'order_code');
        if (empty($orderInfo)) {
            throw new Exception('订单信息不存在');
        }
        //运单类型（运单类型只能为C、S、E，其中 “C”表示客户单号，“S”表示服务商单号，“E”表示公司单号）
        $requestInfo = array(
            'username' => $this->username,
            'password' => $this->password,
            'hawbtype' => 'S'
        );
        if (!empty($orderInfo['ref_tracking_number'])) {
            $requestInfo['hawbno'] = $orderInfo['ref_tracking_number'];
        } else {
            $requestInfo['hawtype'] = 'C';
            $requestInfo['hawbno'] = $orderInfo['ref_tracking_number'];
        }
        $url = $this->_shipmentRequestUrl . '?' . http_build_query($requestInfo);
        $result = self::http_request($url);
        $parse = simplexml_load_string($result);
        if ((string) $parse->errcode != '') {
            throw new Exception((string) $parse->errorinfo);
        }
        foreach ($parse->tracklist as $t) {
            $item = array(
                'date' => $t->date,
                'area' => $t->area,
                'desc' => $t->desc
            );
            $return[] = $item;
        }
        return $return;
    }

    public function getTrackingInfoMulty($waybillArray) {
        //运单类型（运单类型只能为C、S、E，其中 “C”表示客户单号，“S”表示服务商单号，“E”表示公司单号）
        $return = array();
        if (empty($waybillArray)) {
            throw new Exception('运单号为空');
        }
        $requestInfo = array(
            'username' => $this->username,
            'password' => $this->password,
            'hawbtype' => 'S',
            'hawbno' => implode(',', $waybillArray)
        );

        $url = $this->_shipmentRequestUrl . '?' . http_build_query($requestInfo);
        $result = self::http_request($url);
        $parse = simplexml_load_string($result);
        //file_put_contents(APPLICATION_PATH . '/../data/pdf/BHHKDHL/tracking.xml', $result);
        if ((string) $parse->errcode != '') {
            throw new Exception((string) $parse->errorinfo);
        }
        foreach ($parse->awb as $trackList) {
            $orderCode = (string) $trackList->customerhawbno;
            foreach ($trackList->tracklist as $t) {
                $item = array(
                    'date' => (string)$t->date,
                    'area' => (string)$t->area,
                    'desc' => (string)$t->desc
                );
                $return[$orderCode][] = $item;
            }
        }
        return $return;
    }

    /**
     * 调用接口
     * @return array
     */
    public function runAPI() {
        $this->initDHLDataPath(); //文件路径
        $this->checkIsExistData(); //检查记录
        //生成请求xml文档
        $gResult = $this->createRequestXml();
        if ($gResult === true) {
            $this->apiDhlRow['request_xml_path'] = $this->getReqFilePath();
        } else {
            $this->error = $gResult;
            $this->updateApiDhl('failure');
            return $this->getResult();
        }
        
        //请求接口
        $rResult = $this->request();
        if ($rResult === false) {
            $this->updateApiDhl('failure');
            return $this->getResult();
        }
        //解析响应XML
        $pResult = $this->parseResFile();
        if ($pResult === true) {
            $this->apiDhlRow['response_xml_path'] = $this->getResFilePath();
        } else {
            $this->updateApiDhl('failure');
            return $this->getResult();
        }
        //获取pdf标签
        $lResult = $this->generatePdf();
        if ($lResult === true) {
            $this->apiDhlRow['label_pdf_path'] = $this->getPdfFilePath();
        } else {
            $this->updateApiDhl('failure');
            return $this->getResult();
        }
        //调用成功
        $this->updateApiDhl('success');
        //货物超长
        $this->orderWidthWigth();
        $this->sendfile();
        return $this->getResult(1);
    }

    /**
     * //货物超长
     */
    private function orderWidthWigth() {
        $width = 0;
        $weight = 0;
        foreach ($this->pieces AS $value) {
            if ($width < $value['length'])
                $width = $value['length'];
            if ($width < $value['width'])
                $width = $value['width'];
            if ($width < $value['height'])
                $width = $value['height'];

            if ($weight < $value['weight'])
                $weight = $value['weight'];
        }

        if ($width > 120 || $weight > 70) {
            Service_Exception::addExceptionByCode('orderWidthWigth', $this->order_code);
        }
    }

    /**
     * @发送标签和发票
     */
    private function sendfile(){
        if($this->sendfile=='1'){
            //只有是要发送给环球标示时候才会发送给环球。
            $label = new Service_LabelSendProcess();
            $label->sendLabel($this->getPdfFilePath(),$this->order_code);
            //发送发票,放在获取完运单更新ship_order的跟踪号的外面，要不ship_order表的信息不存在
            /*$invoice = new Service_InvoiceProcess($this->order_code);
            $invoice->getResult();*/
        }
    }
}
