<?php

namespace App\Services;

use App\OrderPackage;
use App\Traits\ServiceAppAop;
use Carbon\Carbon;
use Doctrine\DBAL\Connection;
use Illuminate\Support\Facades\Http;

class LogisticYTOService
{
    use ServiceAppAop;


    public function query($logistic_number)
    {
        $app_key = config('api_logistic.YTO.prod.app-key');
        $app_secret = config('api_logistic.YTO.prod.app-secret');
        $user_id = config('api_logistic.YTO.prod.user_id');
        $method = config('api_logistic.YTO.prod.method');
        $format = config('api_logistic.YTO.prod.format');
        $v = config('api_logistic.YTO.prod.v');
        $url = config('api_logistic.YTO.prod.search.url');
        $body = [
            "Number" => $logistic_number
        ];
        $secret=$app_secret.'app_key'.$app_key.'format'.$format.'method'.$method.'timestamp'.Carbon::now()->toDateTimeString().'user_id'.$user_id.'v'.$v;
        $sign = strtoupper(md5($secret));
        $headers = [
            'sign' => $sign,
            'app_key' => $app_key,
            'format' => $format,
            'method' => $method,
            'timestamp' => Carbon::now()->toDateTimeString(),
            'user_id' => $user_id,
            'v' => $v,
            'param'=>json_encode($body, JSON_UNESCAPED_UNICODE)
        ];

        $response = Http::asForm()->post($url,$headers);
        return json_decode($response->body());
    }

    public function format($response): array
    {
        $result = [];
        if (is_object($response) && $response->code=='1001') {return [];}
        else {
            $result['logistic_number'] = $response[0]->waybill_No;
            if (!empty($response)) {
                $lastNativeRoute = $response[count($response) - 1];
                $result['status'] = $this->getStatus($lastNativeRoute);
                if ($result['status'] == '已收件') $result['received_at'] = $lastNativeRoute->upload_Time;
                $result['transfer_status'] = $this->getTransferStatus($response);
                $result['routes_length'] = array_key_exists('transfer_status', $result) ? count($result['transfer_status']) : 0;
                $orderPackageReceivedSyncService = app('OrderPackageReceivedSyncService');
                $exceptionData = $orderPackageReceivedSyncService->setExceptionType($result, $lastNativeRoute ? $lastNativeRoute->upload_Time : null);
                $result['exception_type'] = $exceptionData['exception_type'];
                $result['exception'] = $exceptionData['exception'];

            } else {
                $result['status'] = null;
                $result['transfer_status'] = [];
            }
            if (!array_key_exists('status', $result)) {$result['status'] = null;$result['transfer_status'] = [];}
            //如果没有发现额外的异常，且查询到物流轨迹，将异常置为无
            if (!array_key_exists('exception', $result)
                && !array_key_exists('exception_type', $result)
                && array_key_exists('transfer_status', $result)
            ) {$result['exception_type'] = '无';$result['exception'] = '否';}
            return $result;
        }
    }
    /**
     * @param $nativeData
     * @return string
     */
    private function getStatus($nativeData): string
    {
        $status = null;
        switch ($nativeData->infoContent) {
            case 'ARRIVAL':
            case 'GOT':
                $status = '已揽收';
                break;
            case 'DEPARTURE':
            case 'PACKAGE':
                $status = '在途';
                break;
            case 'SENT_SCAN':
            case 'INBOUND':
                $status = '派送中';
                break;
            case 'SIGNED':
                $status = '已收件';
                break;
            case 'TMS_RETURN':
                $status = '返回中';
                break;
            default:
                $status = '无';
        }
        return $status;
    }
    /**
     * @param $nativeRoutes
     * @return array
     */
    private function getTransferStatus($nativeRoutes): array
    {
        $transferStatus = [];
        foreach ($nativeRoutes as $nativeRoute) {
            $item = [];
            $item['accept_time'] = $nativeRoute->upload_Time;
            $item['accept_address'] = $nativeRoute->processInfo;
            $item['remark'] = "";
            $transferStatus[] = $item;
        }
        return $transferStatus;
    }
}
