<?php

namespace App\Handlers;

use App\Models\Order;
use GuzzleHttp\Client;

Class ExpressHandler
{
    //快递鸟获取订单物流信息
    public function getExpress($LogisticCode, $ShipperCode, $OrderCode, $CustomerName)
    {
        $client = new Client();
        $appKey = '321b74bb-84a3-4b9c-af1d-937583f9a3a0';
        $appId = 1640111;
//        $url = 'http://sandboxapi.kdniao.com:8080/kdniaosandbox/gateway/exterfaceInvoke.json';
        $url = 'http://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx';
        $requestData = $this->requestData($LogisticCode, $ShipperCode, $OrderCode, $CustomerName);
        $array = [
            'query' => [
                'RequestData' => urlencode($requestData),
                'EBusinessID' => $appId,
                'RequestType' => '8002',
                'DataSign' => urlencode($this->encrypt($requestData, $appKey)),
                'DataType' => '2'
            ]
        ];
        $result = $client->request('POST', $url, $array);
        $res = json_decode($result->getBody()->getContents());
        //保存订单物流信息
        if(isset($res->Traces) && !empty($res->Traces)){
            Order::where('order_no',$OrderCode)->update([
                'express_info'=>json_encode($res),
                'express_receive_time'=>array_pop($res->Traces)->AcceptTime,
                'express_state'=>$res->State
            ]);
        }
        return $res;
    }

    private function requestData($LogisticCode,$ShipperCode=null,$OrderCode=null,$CustomerName=null){
        if ($ShipperCode){
            $data['ShipperCode']=$ShipperCode;
        }
        if ($OrderCode){
            $data['OrderCode']=$OrderCode;
        }
        if ($CustomerName){
            $data['CustomerName']=$CustomerName;
        }
        $data['LogisticCode']=$LogisticCode;

        return json_encode($data);
    }

    public function encrypt($requireData,$appKey){
        return base64_encode(md5($requireData.$appKey));
    }

}
