<?php
namespace Modules\Project\Services;

class ExpressService extends BaseService
{
    public static function query($kuaidi_code, $order_number)
    {
        return (new static)->kd100_api($kuaidi_code, $order_number);
    }

    public function kd100_api($kuaidi_code, $order_number)
    {
        $info = cache('order_kd100_db_'.$kuaidi_code.'_'.$order_number);
        if (!empty($info)) {
            return $info;
        }

        //参数设置
        $post_data = [];
        $post_data['customer'] = db_config('kuaidi_100_customer', '');
        $key = db_config('kuaidi_100_key', '');
        $post_data['param'] = '{"com":"'.$kuaidi_code.'","num":"'.$order_number.'"}';
        $url = 'http://poll.kuaidi100.com/poll/query.do';
        $post_data['sign'] = md5($post_data['param'].$key.$post_data['customer']);
        $post_data['sign'] = strtoupper($post_data['sign']);
        $o = '';
        foreach ($post_data as $k => $v) {
            $o .= "$k=".urlencode($v).'&';		//默认UTF-8编码格式
        }
        $post_data = substr($o, 0, -1);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $result = curl_exec($ch);
        $data = str_replace('"', '"', $result);
        $kuaidi_info = json_decode($data, true);
        if (isset($kuaidi_info['result']) && $kuaidi_info['result'] == false) {
            $kuaidi_info['info'] = '无数据';
            $kuaidi_info['data'] = [];
        //throw new \Exception($kuaidi_info['message']);
        } else {
            if ($kuaidi_info['status'] == 200) {
                switch ($kuaidi_info['state']) {
                    case 0:
                        $kuaidi_info['info'] = '在途中';
                        break;
                    case 1:
                        $kuaidi_info['info'] = '揽件中';
                        break;
                    case 2:
                        $kuaidi_info['info'] = '疑难件';
                        break;
                    case 3:
                        $kuaidi_info['info'] = '已签收';
                        break;
                    case 4:
                        $kuaidi_info['info'] = '退签中';
                        break;
                    case 5:
                        $kuaidi_info['info'] = '派件中';
                        break;
                    case 6:
                        $kuaidi_info['info'] = '已退回';
                        break;
                    case 7:
                        $kuaidi_info['info'] = '已发货';
                        break;
                }

                cache('order_kd100_db_'.$kuaidi_code.'_'.$order_number, $kuaidi_info, 3600);
            } else {
                $kuaidi_info['info'] = '无数据';
            }
        }

        return $kuaidi_info;
    }
}
