<?php

namespace App\Utils;

use App\Constants\HttpEnumCode;
use App\Exception\BusinessException;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Hyperf\Guzzle\CoroutineHandler;
use GuzzleHttp\HandlerStack;
use Hyperf\Redis\Redis;
use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerInterface;
use Hyperf\Di\Annotation\Inject;

/**
 * 处方平台对接类
 */
class Prescription
{
    #[Inject]
    protected ContainerInterface $container;
    #[Inject]
    protected Client $client;

    #[Inject]
    protected Redis $redis;

    protected string $api_url;
    protected string $client_id;
    protected string $client_secret;
    protected string $access_token;
    protected array $header;
    public string $version = "v1";


    public function __construct()
    {
//        $container = ApplicationContext::getContainer();
//        $this->redis = $container->get(Redis::class);

        // 请求地址
        $this->api_url = "http://49.233.3.200:6304/api/thridapi/";
        $this->client_id = "ZD-004";
        $this->client_secret = "0baa5927164710b9f800bf33546b6da3";

        // 启动时redis已注入，此处不会出现问题。
        $this->access_token = $this->redis->get("prescription_token");
        if (empty($access_token)){
            $this->access_token = $this->getToken();
        }

        $this->header = [
            "Authorization" => "Bearer " . $this->access_token
        ];
    }

    /**
     * 获取token接口
     * @return string token数据
     */
    protected function getToken(): string
    {
        $option = [
            "json" => array(
                "clientId" => $this->client_id,
                "clientSecret" => $this->client_secret,
            )
        ];

        try {
            $response = $this->httpRequest($this->api_url . $this->version . '/user_thrid/token', $option);

            if (empty($response['result'])){
                // 返回值为空
                throw new BusinessException(HttpEnumCode::getMessage(HttpEnumCode::SERVER_ERROR));
            }

            if (empty($response['result']['token'])){
                // 返回值为空
                throw new BusinessException(HttpEnumCode::getMessage(HttpEnumCode::SERVER_ERROR));
            }

        } catch (GuzzleException $e) {
            throw new BusinessException($e->getMessage());
        }

        return $response['result']['token'];
    }

    // 获取药品
    public function getProd(){
        $option = [
            "json" => array(
                "page" => 1,
                "pageSize" => 1,
            ),
            "headers" => $this->header
        ];

        try {
            $response = $this->httpRequest($this->api_url . $this->version . '/drug/syncDrugCatalogue', $option);
            if (empty($response['result'])){
                // 返回值为空
                throw new BusinessException(HttpEnumCode::getMessage(HttpEnumCode::SERVER_ERROR));
            }

            if (empty($response['result']['rows'])){
                return true;
            }
            dump($response);
            // 获取总数
//            $count
        } catch (GuzzleException $e) {
            throw new BusinessException($e->getMessage());
        }

//        return $response['token'];
    }

    // 查询商品库存
    public function getProdStock(){
        $option = [
            "json" => array(
                "pharmacyCode" => "JG-10009",
                "drugCode" => "105860",
            ),
            "headers" => $this->header
        ];

        try {
            $response = $this->httpRequest($this->api_url . $this->version . '/pharmacy/pharmacyInventory', $option);
            dump($response);

        } catch (GuzzleException $e) {
            throw new BusinessException($e->getMessage());
        }
    }

    // 获取运费
    public function getExpressPrice(){
        $option = [
            "json" => array(
                "pharmacyCode" => "JG-10009",
            ),
            "headers" => $this->header
        ];

        try {
            $response = $this->httpRequest($this->api_url . $this->version . '/pharmacy/transportationExpenses', $option);
            dump($response);

        } catch (GuzzleException $e) {
            throw new BusinessException($e->getMessage());
        }
    }

    /**
     * 请求封装
     * @param string $path
     * @param array $option
     * @return array
     * @throws GuzzleException
     */
    protected function httpRequest(string $path,array $option = []): array
    {
        $response = $this->client->post($path, $option);

        if ($response->getStatusCode() != '200'){
            // 请求失败
            throw new BusinessException($response->getBody()->getContents());
        }

        $body = json_decode($response->getBody(),true);
        if (empty($body)){
            // 返回值为空
            throw new BusinessException(HttpEnumCode::getMessage(HttpEnumCode::SERVER_ERROR));
        }
        dump($body);

        if (empty($body['data'])){
            // 返回值为空
            if (!empty($body['message'])){
                throw new BusinessException($body['message']);
            }
            throw new BusinessException(HttpEnumCode::getMessage(HttpEnumCode::SERVER_ERROR));
        }

        return $body['data'];
    }
}