<?php
/**
 * Created by JetBrains PhpStorm.
 * User: user
 * Date: 14-5-21
 * Time: 下午4:50
 * To change this template use File | Settings | File Templates.
 */
class Service_EpacketWebService extends Common_Service
{
    private $param = array();

    private $PostMethod = "POST";

    private $GetMethod = "GET";

    private $DeleteMethod = "DELETE";

    private $postHeader = array("Content-type: text/xml","version: international_eub_us_1.1","authenticate: CSCMe_10ac44eb0d863fd1b86fae6daaf95fab");

    private $getHeader = array("version: international_eub_us_1.1","authenticate: CSCMe_10ac44eb0d863fd1b86fae6daaf95fab");

    private $validateUrl = "http://shipping.ems.com.cn/partner/api/public/p/validate";

    private $orderUrl = "http://shipping.ems.com.cn/partner/api/public/p/order/";


    public static function getOrderContent($orderCode){
        $oderRow = Service_Orders::getByField($orderCode,'order_code',"*");
        $orderReceiveAddress = Service_OrderAddressBook::getByCondition(array('order_code'=>$orderCode,'oab_type'=>'0'),"*");
        $receiver = $orderReceiveAddress[0];
        $operationtype = 0;
        if($oderRow['sm_code']=="SZY-ETK"){
            $operationtype = 2;
        }
        $receiAddress = $receiver['oab_street_address1'];
        if($receiver['oab_street_address2']!=""){
            $receiAddress = $receiAddress." ".$receiver['oab_street_address2'];
        }
        $reCountry = Service_Country::getByField($receiver['oab_country_id'],"country_id","*");
        $orderProduct = Service_OrderProduct::getByCondition(array('order_code'=>$orderCode),"*");
        $items ="<items>";
        foreach($orderProduct as $opk=>$opv){
            $p = Service_Product::getByField($opv['product_id'],"product_id","*");
            $weight = round($p['product_weight'],3);
            $items.="<item>".
                        "<cnname>".$p['product_title']."</cnname>".
                        "<enname><![CDATA[".$opv['product_title_en']."]]></enname>".
                        "<count>".$opv['op_quantity']."</count>".
                        "<weight>".$opv["op_quantity"]*$weight."</weight>".
                        "<delcarevalue>".$opv['op_purpose_declared_value']*$opv['op_quantity']."</delcarevalue>".
                        "<origin>CN</origin>".
                    "</item>";
        }
        $items .="</items>";
        $xmlData = "<?xml version='1.0'?>".
                    "<orders xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>".
                        '<order>'.
                            '<orderid>'.$oderRow['order_id'].'</orderid>'.
                            '<operationtype>'.$operationtype.'</operationtype>'.
                            '<producttype>0</producttype>'.
                            '<customercode>CSCMe</customercode>'.
                            '<vipcode></vipcode>'.
                            '<clcttype>0</clcttype>'.
                            '<pod>false</pod>'.
                            '<untread>Returned</untread>'.
                            '<volweight>0</volweight>'.
                            '<startdate>'.date("Y-m-d")."T".date("H:i:s").'</startdate>'.
                            '<enddate>'.date("Y-m-d",strtotime("+2 day")).'T'.date("H:i:s").'</enddate>'.
                            '<printcode>01</printcode>'.
                            '<sender>'.
                                '<name>Cherry Zhou</name>'.
                                '<postcode>518000</postcode>'.
                                '<phone>18718573382</phone>'.
                                '<mobile>18718573382</mobile>'.
                                '<country>CN</country>'.
                                '<province>440000</province>'.
                                '<city>440300</city>'.
                                '<county>440305</county>'.
                                '<company>深圳市招海国际货运代理有限公司</company>'.
                                '<street>4/F, Block 5,Qianhaiwan Free Trade Port Area,No.53  Linhai Rd. Nanshan  District, Shenzhen, P.R.C.</street>'.
                                '<email>szsc_baiban@china-fec.com</email>'.
                            '</sender>'.
                            '<receiver>'.
                                '<name>'.$receiver['oab_firstname'].'</name>'.
                                '<postcode>'.$receiver['oab_postcode'].'</postcode>'.
                                '<phone>'.$receiver['oab_phone'].'</phone>'.
                                '<mobile>'.$receiver['oab_cell_phone'].'</mobile>'.
                                '<country>'.$reCountry['country_code'].'</country>'.
                                '<province>'.html_entity_decode($receiver['oab_state']).'</province>'.
                                '<city>'.html_entity_decode($receiver['oab_city']).'</city>'.
                                '<county>'.html_entity_decode($receiver['oab_suburb']).'</county>'.
                                '<street>'.html_entity_decode($receiAddress).'</street>'.
                            '</receiver>'.
                            '<collect>'.
                                '<name>Cherry Zhou</name>'.
                                '<postcode>518000</postcode>'.
                                '<phone>18718573382</phone>'.
                                '<mobile>18718573382</mobile>'.
                                '<country>CN</country>'.
                                '<province>440000</province>'.
                                '<city>440300</city>'.
                                '<county>440305</county>'.
                                '<company/>'.
                                '<street>4/F, Block 5,Qianhaiwan Free Trade Port Area,No.53  Linhai Rd. Nanshan  District, Shenzhen, P.R.C.</street>'.
                                '<email>szsc_baiban@china-fec.com</email>'.
                            '</collect>'.
                            $items.
                            '<remark/>'.
                        '</order>'.
                    '</orders>';
        return $xmlData;
    }

    public function validate($content){
        /*$opts = array(
            'http'=>array(
                'method'  => $this->PostMethod,
                'header'  => $this->postHeader,
                'content' =>$content,
            )
        );
        $context = stream_context_create($opts);
        $response = file_get_contents($this->validateUrl, false, $context);
        $obj = simplexml_load_string($response);
        $result = Common_Common::objectToArray($obj);
        return $result;*/

        $ch = curl_init($this->validateUrl);
        curl_setopt($ch, CURLOPT_URL, $this->validateUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $this->postHeader);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
        $response = curl_exec($ch);
        if(curl_errno($ch)){
            print curl_error($ch);
        }
        $obj = simplexml_load_string($response);
        $result = Common_Common::objectToArray($obj);
        if(empty($result)){
            echo $response."</br>";
        }
        return $result;
    }

    public function createEpacketOrder($content){
        /*$opts = array(
            'http'=>array(
                'method'  => $this->PostMethod,
                'header'  => $this->postHeader,
                'content' =>$content,
            )
        );
        $context = stream_context_create($opts);
        $response = file_get_contents($this->orderUrl, false, $context);
        $obj = simplexml_load_string($response);
        $result = Common_Common::objectToArray($obj);
        return $result;*/

        $ch = curl_init($this->orderUrl);
        curl_setopt($ch, CURLOPT_URL, $this->orderUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $this->postHeader);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
        $response = curl_exec($ch);
        if(curl_errno($ch)){
            print curl_error($ch);
        }
        $obj = simplexml_load_string($response);
        $result = Common_Common::objectToArray($obj);
        return $result;
    }

    public function cancellOrder($mailnum){
        $opts = array(
            'http'=>array(
                'method'  => $this->DeleteMethod,
                'header'  => $this->getHeader,
            )
        );
        $url = "http://www.ems.com.cn/partner/api/public/p/order/".$mailnum;
        $context = stream_context_create($opts);
        $response = file_get_contents($url, false, $context);
        $obj = simplexml_load_string($response);
        $result = Common_Common::objectToArray($obj);
        return $result;
    }

    public function getEpacketOrderInfo($mailnum){
        $url = "http://www.ems.com.cn/partner/api/public/p/order/".$mailnum;
        $opts = array(
            'http'=>array(
                'method'=>$this->GetMethod,
                'header'=>$this->getHeader
            )
        );
        $context = stream_context_create($opts);
        $response = file_get_contents($url, false, $context);
        $obj = simplexml_load_string($response);
        $result = Common_Common::objectToArray($obj);
        return $result;
    }

    public function getTrackingInfo($mailnum){
        $url = "http://www.ems.com.cn/partner/api/public/p/track/query/cn/".$mailnum;
        $opts = array(
            'http'=>array(
                'method'=>$this->GetMethod,
                'header'=>$this->getHeader
            )
        );
        $context = stream_context_create($opts);
        $response = file_get_contents($url, false, $context);
        $obj = simplexml_load_string($response);
        $result = Common_Common::objectToArray($obj);
        return $result;
    }

    /*$fromCountry 始起国家
     *$fromProvince 始起省份
     *$toCountry 目的国家
     *$weight 重量
     *$operationtype 业务类型  0:e邮宝  1:标识国际包裹  2：在线ems
    */
    public function getRate($fromCountry,$fromProvince,$toCountry,$weight,$operationtype="0"){
        $xmlData='<?xml version="1.0" encoding="UTF-8"?>'.
                "<rate>".
                "<operationtype>".$operationtype."</operationtype>".
                "<weight>".$weight."</weight>".
                "<recvcountry>".$toCountry."</recvcountry>".
                "<sendcountry>".$fromCountry."</sendcountry>".
                "<sdprov>".$fromProvince."</sdprov>".
                "</rate>";
        $url = "http://www.ems.com.cn/partner/api/public/p/rate/epacket/";
        $opts = array(
            'http'=>array(
                'method'=>$this->PostMethod,
                'header'=>$this->postHeader,
                'content'=>$xmlData
            )
        );
        $context = stream_context_create($opts);
        $response = file_get_contents($url, false, $context);
        $obj = simplexml_load_string($response);
        $result = Common_Common::objectToArray($obj);
        return $result;
    }

    //获取国内省份
    public function getProvinceList(){
        $url = "http://www.ems.com.cn/partner/api/public/p/area/cn/province/list";
        $opts = array(
            'http'=>array(
                'method'  => 'GET',
                'header'  => $this->getHeader,
            )
        );
        $context = stream_context_create($opts);
        $response = file_get_contents($url, false, $context);
        $obj = simplexml_load_string($response);
        $result = Common_Common::objectToArray($obj);
        return $result;
    }

    //获取城市列表 参数 省代码
    public function getCityList($no){
        $url = "http://www.ems.com.cn/partner/api/public/p/area/cn/city/list/".$no;
        $opts = array(
            'http'=>array(
                'method'  => 'GET',
                'header'  => $this->getHeader,
            )
        );
        $context = stream_context_create($opts);
        $response = file_get_contents($url, false, $context);
        $obj = simplexml_load_string($response);
        $result = Common_Common::objectToArray($obj);
        return $result;
    }

    public function getCountyList($no){
        $url = "http://www.ems.com.cn/partner/api/public/p/area/cn/county/list/".$no;
        $opts = array(
            'http'=>array(
                'method'  => 'GET',
                'header'  => $this->getHeader,
            )
        );
        $context = stream_context_create($opts);
        $response = file_get_contents($url, false, $context);
        $obj = simplexml_load_string($response);
        $result = Common_Common::objectToArray($obj);
        return $result;
    }

    //批量获取标签
    public function BatchDownloadLabel($mailnumArr){
        $xmlData = '<?xml version="1.0" encoding="UTF-8"?>';
        //<orders xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        $xmlData.='<orders  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
        $xmlData.="<printcode>01</printcode><filetype>1</filetype>";
        foreach($mailnumArr as $val){
            $xmlData.="<order>";
            $xmlData.="<mailnum>".$val."</mailnum>";
            $xmlData.="</order>";
        }
        $xmlData.="</orders>";
        $url = "http://www.ems.com.cn/partner/api/public/p/print/downloadLabels";
        $opts = array(
            'http'=>array(
                'method'  => $this->PostMethod,
                'header'  => $this->postHeader,
                'content' =>$xmlData,
            )
        );
        $context = stream_context_create($opts);
        $response = file_get_contents($url, false, $context);
        $obj = simplexml_load_string($response);
        $result = Common_Common::objectToArray($obj);
        return $result;
    }

    public function getAddressPdf($mailnum){
        $str = "CSCMe_10ac44eb0d863fd1b86fae6daaf95fab".$mailnum;
        $md5auth = md5($str);
        $url = "http://labels.ems.com.cn/partner/api/public/p/static/label/download/".$md5auth."/".$mailnum.".pdf";
        $opts = array(
            'http'=>array(
                'method'  => 'GET',
                'header'  => $this->getHeader,
            )
        );
        $context = stream_context_create($opts);
        $response = file_get_contents($url, false, $context);
        return $response;
        //$obj = simplexml_load_string($response);
        //$result = Common_Common::objectToArray($obj);
        //$result['pdf_url'] = $url;
        //return $result;
    }

    public function getOneLableByMailnum($mailnum){
        $xmlData = '<?xml version="1.0" encoding="UTF-8"?>';
        $xmlData.='<orders  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
        $xmlData.="<printcode>01</printcode><filetype>1</filetype>";
        $xmlData.="<order>";
        $xmlData.="<mailnum>".$mailnum."</mailnum>";
        $xmlData.="</order>";
        $xmlData.="</orders>";
        $url = "http://www.ems.com.cn/partner/api/public/p/print/downloadLabels";
        $opts = array(
            'http'=>array(
                'method'  => $this->PostMethod,
                'header'  => $this->postHeader,
                'content' =>$xmlData,
            )
        );
        $context = stream_context_create($opts);
        $response = file_get_contents($url, false, $context);
        $obj = simplexml_load_string($response);
        $result = Common_Common::objectToArray($obj);
        return $result;
    }

    public function getETKLableByMailnum($mailnum){
        $xmlData = '<?xml version="1.0" encoding="UTF-8"?>';
        $xmlData.='<orders  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
        $xmlData.="<printcode>00</printcode><filetype>1</filetype>";
        $xmlData.="<order>";
        $xmlData.="<mailnum>".$mailnum."</mailnum>";
        $xmlData.="</order>";
        $xmlData.="</orders>";
        $url = "http://www.ems.com.cn/partner/api/public/p/print/downloadLabels";
        $opts = array(
            'http'=>array(
                'method'  => $this->PostMethod,
                'header'  => $this->postHeader,
                'content' =>$xmlData,
            )
        );
        $context = stream_context_create($opts);
        $response = file_get_contents($url, false, $context);
        $obj = simplexml_load_string($response);
        $result = Common_Common::objectToArray($obj);
        return $result;
    }

  /**
   * 整合创建EUB订单流程，此为备用方法
   * 
   * @param string $orderCode 订单号
   * @return boolean | string
   */
  public function createOrder($orderCode) {
    $orderCode = trim($orderCode);
return TRUE;
    if ('' === $orderCode) {
      return '订单号不能为空';
    }

    $order = Service_Orders::getByField($orderCode, 'order_code');

    if (empty($orderCode)) {
      return '检索不到订单【' . $orderCode . '】相关信息';
    }
    elseif ('SZY-EUB' !== strtoupper(trim($order['sm_code']))) {
      return '订单【' . $orderCode . '】运输方式不是SZY-EUB';
    }
    elseif (4 !== (int) $order['order_status']) { // 不是已提交状态
      return '订单【' . $orderCode . '】不是已提交状态';
    }

    $orderXml = self::getOrderContent($orderCode);
    $response = $this->validate($orderXml);

    if ('success' === strtolower(trim($response['status']))) {
      $response = $this->createEpacketOrder($orderXml);

      if (isset($response['mailnum']) && '' !== $response['mailnum']) {
        $orderLog = array(
          'order_id'          => $order['order_id'],
          'order_code'        => $order['order_code'],
          'ol_type'           => 1,
          'order_status_from' => $order['order_status'],
          'order_status_to'   => $order['order_status'],
          'ol_add_time'       => date("Y-m-d H:i:s"),
          'user_id'           => 0,
          'ol_comments'       => 'EUB自动取单号以及标签->Service_EpacketWebService',
        );
        Service_OrderLog::add($orderLog);
        Service_Orders::update(array(
          'ref_tracking_number' => $response['mailnum'],
        ), $order['order_id'], 'order_id');

        $labelResponse = $eub->getOneLableByMailnum($response['mailnum']);
        $zipFileStream = file_get_contents($labelResponse['url'], FALSE, NULL);
        $zipFileName   = APPLICATION_PATH . '/../data/pdf/EUB/' . $order['order_code'] . '.zip';
        $zip           = new ZipArchive();
        file_put_contents($zipFileName, $zipFileStream);

        if (TRUE === $zip->open($zipFileName)) {
          $zip->extractTo(APPLICATION_PATH . '/../data/pdf/EUB/');
          $pdfFileName = $zip->getNameIndex(0);
          rename(APPLICATION_PATH . '/../data/pdf/EUB/' . $pdfFileName, APPLICATION_PATH . '/../data/pdf/EUB/' . $order['order_code'] . '.pdf');
          $zip->close();
        }

        unlink($zipFileName);

        return TRUE;
      }
    }

    return isset($response['description']) ? 'SZY-EUB调用接口创建订单失败，原因：' . $response['description'] : 'SZY-EUB调用接口创建订单失败';
  }

    public function getPdfByOrderCode($orderCode){
        $orderRow = Service_Orders::getByField($orderCode,'order_code',"*");
        if($orderRow['ref_tracking_number']=="") return false;
        $str = "CSCMe_10ac44eb0d863fd1b86fae6daaf95fab".$orderRow['ref_tracking_number'];
        $md5auth = md5($str);
        $url = "http://labels.ems.com.cn/partner/api/public/p/static/label/download/".$md5auth."/".$orderRow['ref_tracking_number'].".pdf";
        $opts = array(
            'http'=>array(
                'method'  => 'GET',
                'header'  => $this->getHeader,
            )
        );
        $context = stream_context_create($opts);
        $fileContent = file_get_contents($url, false, $context);
        if($fileContent!=""){
            $file = APPLICATION_PATH . '/../data/pdf/EUB/' . $orderRow['order_code'] . '.pdf';
            if(!file_exists($file)){
                $fp=fopen($file, "w+");
            }
            file_put_contents($file,$fileContent);
        }
        return true;
        //$obj = simplexml_load_string($response);
        //$result = Common_Common::objectToArray($obj);
        //$result['pdf_url'] = $url;
        //return $result;
    }
}
