<?php

namespace BYDAuto;

use GuzzleHttp\Client;

class CheryClueApi
{
    protected $appId;

    protected $appSecret;

    protected $endpoint;

    protected $httpClient;

    private static $instance;

    private function __construct()
    {
        $this->appId = config('chery-crm.scrm.app_id');
        $this->appSecret = config('chery-crm.scrm.secret');
        $this->endpoint = config('chery-crm.scrm.endpoint');
        $this->httpClient = new Client(['base_uri' => $this->endpoint, 'timeout' => 10]);
    }

    public static function getInstance(): self
    {
        if (!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 线索推送
     *
     * @param array $data
     * @return CheryResult
     */
    public function cluePush($data)
    {
        $token = $this->getToken();
        $response = $this->httpClient->post('/api/app/chery-clue/api/clue/push/channel', ['json' => $data, 'headers' => ['x-csrf-token' => $token]]);
        $content = json_decode($response->getBody()->getContents(), true);
        $result = new CheryResult($content);
        if ($result->code !== '0') {
            $message = $result->get('msg', '推送线索失败');
            throw new \Exception($message);
        }
        return $result;
    }

    public function getToken($force = false)
    {
        $token = cache('pkg:chery-scrm-token');
        if ($force || !$token) {
            $response = $this->httpClient->get('/api/app/chery-clue/api/clue/channel/getToken', ['query' => ['appId' => $this->appId, 'appSecret' => $this->appSecret]]);
            $json = json_decode($response->getBody()->getContents(), true);
            if ($json['code'] === '0') {
                $token = $json['data'];
                // 有效期4小时，提前10分钟刷新
                cache(['pkg:chery-scrm-token' => $token], now()->addSeconds(4 * 3600 - 600));
            } else {
                $message = $json['msg'] ?? 'pkg:chery-scrm-token 获取失败';
                throw new \Exception($message);
            }
        }
        return $token;
    }
}
