<?php

/**
 * Class 万欧接口
 */
class Service_OneWorldExpressApiProcess
{
	/*测试
    private $hosts = 'http://api-sbx.oneworldexpress.cn';
    private $accountNo = 'OW00039';
    private $token = 'Ivt6mllVIg6SsUY';
	*/
	//正式
	private $hosts = 'http://api.oneworldexpress.cn/';
    private $accountNo = 'OW01194';
    private $token = 'B5THHXRKOK0Njfp';
	
    private $timeStamp = 0;
    private $path;
    private $orderCode;
    private $shipMethods = array(
        'BH-3HPA' => '3HPA',
        'BH-3H' => '3H',
        'BH-UKECSLTYD' => 'UKECSLTYD',
        'BH-UKECSLTRM' => 'UKECSLTRM',
        'BH-CORREOS' => 'CORREOS',
        'BH-19EURDPDDE' => '19EURDPDDE',
        'BH-DAC' => 'DAC',
        'BH-SL018' => 'SL018',
        'BH-IESLTANPOST' => 'IESLTANPOST',
    );

    public function __construct()
    {
        $this->initPathforSavePDF();
        $this->path = APPLICATION_PATH . '/../data/pdf/oneWorldExpress/';
        $this->timeStamp = time();
    }

    private function initPathforSavePDF()
    {
        $base = APPLICATION_PATH.'/../data/pdf';
        if(!file_exists($base)) {
            mkdir($base, 0777, true);
        }
        $base .= '/oneWorldExpress';
        if(!file_exists($base)) {
            mkdir($base, 0777, true);
        }
    }
    // 创建包裹
    public function parcels($orderCode, $piecesDetail)
    {
        $this->orderCode = $orderCode;
        // 订单信息
        $orderRow = Service_Orders::getByField($orderCode, 'order_code', '*');

        if ($orderRow == NULL) {
            throw new Exception('订单号不存在');
        }
        // 收货地址
        $orderReceiveAddress = Service_OrderAddressBook::getByCondition(array('order_code' => $orderCode, 'oab_type' => '0'), "*");
        $reCountry = Service_Country::getByField($orderReceiveAddress[0]['oab_country_id'], "country_id", "*");
        $shippingAddress = array(
            'Company' => $orderReceiveAddress[0]['oab_company'],
            'Street1' => $orderReceiveAddress[0]['oab_street_address1'],
            'Street2' => $orderReceiveAddress[0]['oab_street_address2'],
            'Street3' => $orderReceiveAddress[0]['oab_street_address3'],
            'City' => $orderReceiveAddress[0]['oab_city'],
            'Province' => $orderReceiveAddress[0]['oab_state'],
            'CountryCode' => $reCountry['country_code'],
            'PostCode' => $orderReceiveAddress[0]['oab_postcode'],
            'Contacter' => trim($orderReceiveAddress[0]['oab_firstname'] . ' ' . $orderReceiveAddress[0]['oab_lastname']),
            'Tel' => $orderReceiveAddress[0]['oab_cell_phone'] ? $orderReceiveAddress[0]['oab_cell_phone'] : $orderReceiveAddress[0]['oab_phone'],
            'Email' => $orderReceiveAddress[0]['oab_email'],
        );

        // 订单物品
        $itemDetails = array();
        $orderProduct = Service_OrderProduct::getByCondition(array('order_code' => $orderCode), "*");
        $isWithBattery = 0;
        $totalValue = 0;
        foreach ($orderProduct as $key => $val) {
            $p = Service_Product::getByField($val['product_id'], "product_id", "*");
            $item = array();
            $item['GoodsTitle'] = $p['hs_goods_name'];
            $item['DeclaredNameEn'] = $p['product_title_en'];
            $item['DeclaredNameCn'] = $p['product_title'];
            $item['DeclaredValue'] = array(
                'Code' => 'USD',
                'Value' => (float)$val['op_purpose_declared_value'],
            );
            $item['WeightInKg'] = (float)$p['product_weight'];
            $item['Quantity'] = (int)$val['op_quantity'];
            $item['HSCode'] = $p['hs_code'];
            $itemDetails[] = $item;
            $totalValue += $val['op_purpose_declared_value'] * $val['op_quantity'];
            if ($p['with_battery'] == 1) {
                $isWithBattery = 1;
            }
        }
        $params = array(
            'ReferenceId' => $orderCode,
            'ShippingAddress' => $shippingAddress,
            'WeightInKg' => (float)number_format($piecesDetail[0]['weight'], 1, '.', ''),
            'ItemDetails' => $itemDetails,
            'TotalValue' => array(
                'Code' => 'USD',
                'Value' => (float)$totalValue,
            ),
            'TotalVolume' => array(
                'Length' => (float)number_format($piecesDetail[0]['length'], 1, '.', ''),
                'Width' => (float)number_format($piecesDetail[0]['width'], 1, '.', ''),
                'Height' => (float)number_format($piecesDetail[0]['height'], 1, '.', ''),
                'Unit' => 'CM',
            ),
            'WithBatteryType' => $isWithBattery == 1 ? 'WithBattery' : 'NOBattery',
            'Notes' => $orderRow['remark'],
            'WarehouseCode' => 'SZ',
            'ShippingMethod' => $this->shipMethods[$orderRow['sm_code']],
            'ItemType' => 'SPX',
            'AutoConfirm' => true,
        );
        $result = $this->push('/api/parcels', $params, 'POST');
        return json_decode($result, true);
    }

    // 获取包裹 轮询至运单号存在
    public function getParcels($processCode)
    {
        $result = $this->push('/api/parcels/' . $processCode, array(), 'GET');
        return json_decode($result, true);
    }

    // 获取包裹标签
    public function getParcelsLabel($orderCode, $processCode)
    {
        $fileContent = $this->push('/api/parcels/' . $processCode . '/label', array(), 'GET');
        $filePath = $this->path . $orderCode . '.pdf';
        if (file_exists($filePath)) {
            unlink($filePath);
        }
        file_put_contents($filePath, $fileContent);
        return $filePath;
    }

    // 获取物流轨迹
    public function trackPoints($orderCode)
    {
        $result = $this->push('/api/trackPoints?trackingNumber=' . $orderCode, array(), 'GET');
        return json_decode($result, true);
    }

    // api验证授权
    private function authorization()
    {
        return 'Hc-OweDeveloper ' . $this->accountNo . ';' . $this->token . ';' . json_encode(time());
    }

    private function push($url, $params = array(), $method = 'GET')
    {
        $header = array();
        $header[] = 'Accept: application/json';
        $header[] = 'Content-Type: application/json';
        $header[] = 'Authorization: ' . $this->authorization();

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_URL, $this->hosts . $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // post数据
        if ($method == 'GET') {
            curl_setopt($ch, CURLOPT_POST, 0);
        } else {
            curl_setopt($ch, CURLOPT_POST, 1);
        }
        // post的变量
        if (count($params) > 0) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
        }

        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    private function log($str)
    {
        $logger = new Zend_Log();
        $writer = new Zend_Log_Writer_Stream('D:\phpStudy\WWW\globex\log\export_wms.log');
        $logger->addWriter($writer);
        $logger->info($str);
        $logger = null;
    }
}
