<?php

namespace App\Utils\API;

use GuzzleHttp\Client;
use support\Log;

/**
 * 验证码识别类
 * 官网 https://www.jfbym.com/
 */
class Verification
{
    /**
     * token
     *
     * @var string
     */
    protected static  $token = "WAUjOgpcS6KUtvIc1C4Uf0M1SICxtDC9beFetiCp9hk";
    /**
     * 接口请求url
     *
     * @var string
     */
    protected static  $baseurl = "http://api.jfbym.com/api/YmServer/customApi";
    /**
     * 识别类型
     * 10110  4位纯数字
     * 10103  加强版
     * @var string
     */
    protected static  $type = "10110";
    //单例复用http客户端
    protected static $client = null;
    /**
     * 获取 Guzzle 客户端
     * 用于复用 客户端常驻内存
     *
     * @return object
     */
    protected static function get_client()
    {
        if (self::$client == null) {
            self::$client = new Client([
                'curl' => [
                    CURLOPT_FRESH_CONNECT => false,
                    CURLOPT_FORBID_REUSE => false,
                ],
                'headers' => [
                    'Connection' => 'keep-alive',
                ],
            ]);
        }
        return self::$client;
    }
    /**
     * 获取验证码图片 识别结果
     *
     * @param string $image 待识别图的base64字符串
     * @return int 识别结果 -1 识别失败
     */
    public static function get_captchaImage($image)
    {
        $client = self::get_client(); // 创建 Guzzle 客户端
        $data = [
            "token" => self::$token,
            "type" =>  self::$type,
            "image" => $image,
        ];
        // 发送 POST 请求
        $response = $client->post(self::$baseurl, [
            'json' => $data, // 以 JSON 格式发送数据
        ]);
        // 获取响应体内容
        $body = $response->getBody();
        $responseData = json_decode($body, true); // 如果返回的是 JSON 格式,解析它
        if ($responseData['code'] == 10000) {
            return $responseData['data'];
        } else {
            Log::error("验证码识别失败: " ."code:". $responseData['code']);
            return -1;
        }
    }
}