<?php




namespace ln\services;


use app\common\repositories\store\shipping\ExpressRepository;
use think\facade\Cache;

class ExpressService
{
    const API = 'https://wuliu.market.alicloudapi.com/kdi';

    public static function query($no, $type = '')
    {
        $express = systemConfig('crmeb_serve_express');
        $cacheTime = 0;
        if($express == 2){
            $espressData = app()->make(ExpressRepository::class)->getWhere(['name' => $type]);
            //一号通
            $res = app()->make(CrmebServeServices::class)->express()->query($no,$espressData->code);

            if(!empty($res)){
                if($res['status'] == 3){
                    $cacheTime = 1800;
                }else{
                    $cacheTime = 0;
                }
            }
            $list = $res['content'] ?? [];
        } else {
            //阿里云
            $appCode = systemConfig('express_app_code');
            if (!$appCode) return false;
            $type = '';
            $res = HttpService::getRequest(self::API, compact('no', 'type'), ['Authorization:APPCODE ' . $appCode]);
            $result = json_decode($res, true) ?: null;
            if($result['status'] != 200){
                if (
                    is_array($result) &&
                    isset($result['result']) &&
                    isset($result['result']['deliverystatus']) &&
                    $result['result']['deliverystatus'] >= 3
                ){
                    $cacheTime = 0;
                } else {
                    $cacheTime = 1800;
                }
            }
            $list = $result['result']['list'] ?? [];
        }

        return compact('cacheTime','list');
    }

    public static function express($delivery_id,$com)
    {
        if (Cache::has('express_' . $delivery_id)) {
            $result = Cache::get('express_' . $delivery_id);
        } else {
            $result = self::query($delivery_id,$com);
            if(!empty($result)){
                Cache::set('express_' . $delivery_id, $result['list'], $result['cacheTime']);
                $result  =  $result['list'];
            }
        }
        return $result ?? [];
    }


}
