<?php
/**
 * Created by PhpStorm.
 * User: phperstar
 * Date: 2020/9/7
 * Time: 11:33 AM
 */

namespace Util\KDNiao;

use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Factory;

class KDNiaoQuery
{

    // 基础域名
    private $baseUrl = '';

    // 商户ID
    private $EBusinessID = '';

    // 授权KEY
    private $key = '';

    // 实时查询物流信息缓存key
    private $kdniaoQueryKey = 'kdniaoQuery';


    public function __construct($EBusinessID='', $key = '')
    {
        $this->EBusinessID = $EBusinessID;
        $this->key      = $key;
    }

    /**
     * 实时查询
     * 官方文档地址: https://www.kdniao.com/v2/API/Track.aspx
     */
    public function EbusinessOrderHandle($params)
    {
        if(empty($params['com']) || empty($params['num'])){
            return ResultWrapper::fail('请求参数为空', ErrorCode::$paramError);
        }

        $requestData = json_encode([
            'ShipperCode'  => $params['com'], // 快递公司编码
            'LogisticCode' => $params['num'], // 物流单号
        ]);

        $postData = [
            'EBusinessID' => $this->EBusinessID,
            'RequestType' => '1002', // 请求指令类型
            'DataType'    => 2, // 请求、返回数据类型 2-json
            'RequestData' => urlencode($requestData),
        ];

        $postData['DataSign']  = urlencode(base64_encode(md5($requestData.$this->key))); // 签名

        $pollQueryData = Factory::cache('default')->get($this->kdniaoQueryKey.':'.$params['num']);
        if (!empty($pollQueryData)) {
            return ResultWrapper::success($pollQueryData);
        }

        $response = request('http://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx', $postData, 30,  true);

        if ($response['httpcode'] != 200) {
            return ResultWrapper::fail('请求外部系统接口报错', ErrorCode::$apiNotResult);
        }
        $responseData = json_decode($response['content'], true);

        if(!$responseData['Success']){
            return ResultWrapper::fail($responseData['Reason'], ErrorCode::$notAllowAccess);
        }

        Factory::cache('default')->set($this->kdniaoQueryKey . ':' . $params['num'], $response['content'], 3600);
        return ResultWrapper::success($response['content']);

    }

    // 快递单当前状态
    public function getState($state)
    {
       $satateData = [
           2 => '在途',
           3 => '签收',
           4 => '问题件'
       ];

       return isset($satateData[$state]) ? $satateData[$state] : '';
    }
}