<?php

namespace App\Utils\API;

use GuzzleHttp\Client;
use support\Log;

/**
 * 第三方 前端 小火箭api
 * 网址
 * https://dx1.rocketgo.vip/setting/account/account
 */
class Rocketgo
{
    /**
     * TOKEN    
     */
    protected static  $token = null;

    protected static  $baseurl = "https://dx1.rocketgo.vip";  // URL前缀

    // 单例复用 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;
    }
    // /**
    //  * 获取 token
    //  * 用于复用 客户端常驻内存
    //  *
    //  * @return object
    //  */
    // protected static function get_token()
    // {
    //     if (self::$token == null) {
    //         self::$token = 
    //     }
    //     return self::$token;
    // }

    /**
     * 获取 base64 图形验证码
     *
     * @return mixed
     */
    protected static function get_captchaImage()
    {
        $client = self::get_client(); // 创建 Guzzle 客户端

        // 发送 GET 请求
        try {
            $response = $client->get("https://dx1.rocketgo.vip/prod-api3/captchaImage");

            // 获取响应体内容
            $body = $response->getBody();
            $responseData = json_decode($body, true);

            if ($responseData['code'] == 200) {
                return $responseData;
            }
        } catch (\Exception $e) {
            Log::error("请求验证码失败: " . $e->getMessage());
        }

        return -1;
    }

    /**
     * 获取第三方 API 可识别成功的验证码
     *
     * @return mixed
     */
    protected static function get_captchaImage_available()
    {
        $captchaImage = self::get_captchaImage();

        if ($captchaImage == -1) {
            Log::error("请求验证码失败: " . json_encode($captchaImage));
            return -1;
        }

        $uuid = $captchaImage['uuid'];
        $img = $captchaImage['img'];

        // 调用验证码识别接口
        $code = Verification::get_captchaImage($img)['data'];


        if ($code == -1) {
            Log::error("调用接口验证码识别失败: ");
            return -1;
        }

        // 验证验证码是否是2位数字
        if (preg_match('/^\d{2}$/', $code)) {
            return [
                'code' => $code,
                'uuid' => $uuid
            ];
        }

        return -1;
    }

    /**
     * 登录方法
     *
     * @param string $username
     * @param string $password
     * @return array
     */
    public static function login($username, $password)
    {
        $code = "";
        $uuid = "";

        // 获取有效验证码并循环尝试直到成功
        while (true) {
            $captchaImage = self::get_captchaImage_available();
            if ($captchaImage != -1) {
                $code = $captchaImage['code'];
                $uuid = $captchaImage['uuid'];
                break;
            }
        }

        $client = self::get_client(); // 创建 Guzzle 客户端

        // 请求数据
        $data = [
            "username" => $username,
            "password" => $password,
            "code" => $code,
            "uuid" => $uuid,
        ];

        try {
            // 发送 POST 请求
            $response = $client->post("https://dx1.rocketgo.vip/prod-api3/login", [
                'json' => $data, // 以 JSON 格式发送数据
            ]);

            // 获取响应体内容
            $body = $response->getBody();
            $responseData = json_decode($body, true);
            if ($responseData['code'] == 200) {
                self::$token = $responseData['token'];
                return $responseData['token'];
            }else{
                Log::error("登录失败 未知错误: " . json_encode($responseData));
            }
            // return $responseData;
        } catch (\Exception $e) {
            Log::error("登录失败: " . $e->getMessage());
        }
    }

    protected static function get_token()
    {
        return self::$token;
    }
    protected static function set_token($token)
    {
        self::$token = $token;
    }
    /**
     * 测试token是否有效
     *
     * @return void
     */
    public static function test_login()
    {
        $client = self::get_client(); // 创建 Guzzle 客户端
        try {
            // 发送 GET 请求
            $response = $client->get("https://dx1.rocketgo.vip/prod-api2/biz/account/getLoginUserInfo", [
                'headers' => [
                    'Authorization' => 'Bearer ' . self::$token,
                    'Accept' => 'application/json', // 设置其他头信息
                ]
            ]);

            // 获取响应体内容
            $body = $response->getBody();
            $responseData = json_decode($body, true);
            // var_dump($responseData);
            if(!empty($responseData['code'])){
                if ($responseData['code'] == 401) {
                    Log::info("登录过期需要重新登录");
                    self::login('h102067452', 'yBQnfuBShGl1MTBN');
            }
            }else{
                Log::info("登录没有过期可以继续使用token");
            }

        } catch (\Exception $e) {
            Log::error("检测登录是否过期失败: " . $e->getMessage());
        }
    }

    /**
     * 获取账号列表(分页)
     *
     * @param int $pageSize 每页数据量,默认为 1000
     * @return array
     * logged 1 在线 0不在线
     * failedReason 失败类型 正常为空
     * username ws号码
     */
    public static function account_list($pageSize = 1000)
    {
        $client = self::get_client(); // 创建 Guzzle 客户端
        $allData = []; // 用来存储所有分页的数据
        $pageNum = 1; // 从第一页开始

        try {
            // 首次请求,获取 total 数据量
            $response = $client->get(self::$baseurl . "/prod-api2/biz/account/list", [
                'query' => [
                    'pageNum' => $pageNum,
                    'pageSize' => $pageSize,
                    'sendCount' => 0,
                    'isAll' => 1,
                ],
                'headers' => [
                    'Authorization' => 'Bearer ' . self::$token,
                    'Accept' => 'application/json', // 设置其他头信息
                ]
            ]);

            // 获取响应体内容
            $body = $response->getBody();
            $responseData = json_decode($body, true);

            // 检查响应是否成功
            if ($responseData['code'] == 200) {
                $total = $responseData['total']; // 获取总数据量
                $totalPages = ceil($total / $pageSize); // 计算总页数

                // 合并第一页数据
                $allData = array_merge($allData, $responseData['rows']);

                // 循环获取其他页的数据
                for ($pageNum = 2; $pageNum <= $totalPages; $pageNum++) {
                    $response = $client->get(self::$baseurl . "/prod-api2/biz/account/list", [
                        'query' => [
                            'pageNum' => $pageNum,
                            'pageSize' => $pageSize,
                            'sendCount' => 0,
                            'isAll' => 1,
                        ],
                        'headers' => [
                            'Authorization' => 'Bearer ' . self::$token,
                            'Accept' => 'application/json',
                        ]
                    ]);

                    // 获取响应体内容
                    $body = $response->getBody();
                    $responseData = json_decode($body, true);

                    if ($responseData['code'] == 200) {
                        // 合并当前页的数据
                        $allData = array_merge($allData, $responseData['rows']);
                    } else {
                        Log::error("获取账号列表失败,错误信息: " . $responseData['msg']);
                        break;
                    }
                }
            } else {
                Log::error("获取账号列表失败,错误信息: " . $responseData['msg']);
            }

            return $allData; // 返回所有数据

        } catch (\Exception $e) {
            Log::error("获取账号列表失败: " . $e->getMessage());
            return []; // 返回空数组,表示请求失败
        }
    }


    /**
     * 获取仓库账号列表(分页)
     *
     * @param int $pageSize 每页数据量,默认为 1000
     * @return array
     */
    public static function account_storehouse_list($pageSize = 1000)
    {
        $client = self::get_client(); // 创建 Guzzle 客户端
        $allData = []; // 用来存储所有分页的数据
        $pageNum = 1; // 当前页数从 1 开始

        try {
            // 发送初始请求,获取 total 数据量
            $response = $client->get(self::$baseurl . "/prod-api2/biz/account/list", [
                'query' => [
                    'pageNum' => $pageNum,
                    'pageSize' => $pageSize,
                    'accountType' => 2, // 只查询仓库类型的账号
                    'isAll' => 1, // 查询所有账号
                ],
                'headers' => [
                    'Authorization' => 'Bearer ' . self::$token,
                    'Accept' => 'application/json', // 设置其他头信息
                ]
            ]);

            // 获取响应体内容
            $body = $response->getBody();
            $responseData = json_decode($body, true);

            // 检查响应是否成功
            if ($responseData['code'] == 200) {
                $total = $responseData['total']; // 获取总数据量
                $totalPages = ceil($total / $pageSize); // 计算总页数

                // 循环获取分页数据
                for ($pageNum = 1; $pageNum <= $totalPages; $pageNum++) {
                    // 发送 GET 请求,带上分页参数
                    $response = $client->get(self::$baseurl . "/prod-api2/biz/account/list", [
                        'query' => [
                            'pageNum' => $pageNum,
                            'pageSize' => $pageSize,
                            'accountType' => 2,
                            'isAll' => 1,
                        ],
                        'headers' => [
                            'Authorization' => 'Bearer ' . self::$token,
                            'Accept' => 'application/json', // 设置其他头信息
                        ]
                    ]);

                    // 获取响应体内容
                    $body = $response->getBody();
                    $responseData = json_decode($body, true);

                    // 检查响应是否成功
                    if ($responseData['code'] == 200) {
                        $allData = array_merge($allData, $responseData['rows']); // 合并当前页的数据
                    } else {
                        Log::error("获取仓库账号列表失败,错误信息: " . $responseData['msg']);
                        break; // 如果请求失败,退出循环
                    }
                }

                return $allData; // 返回所有数据
            } else {
                Log::error("获取仓库账号列表失败,错误信息: " . $responseData['msg']);
                return []; // 返回空数组,表示请求失败
            }
        } catch (\Exception $e) {
            Log::error("获取仓库账号列表失败: " . $e->getMessage());
            return []; // 返回空数组,表示请求失败
        }
    }
}