package top.continew.admin.common.util;

import cn.dev33.satoken.error.SaErrorCode;
import cn.dev33.satoken.exception.NotLoginException;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.continew.admin.common.util.helper.LoginHelper;
import top.continew.starter.core.util.validate.CheckUtils;
import top.continew.starter.extension.crud.model.resp.PageResp;

import java.util.List;

import static cn.dev33.satoken.exception.NotLoginException.INVALID_TOKEN;
import static cn.dev33.satoken.exception.NotLoginException.INVALID_TOKEN_MESSAGE;

/**
 * @author 张波
 * @since 2024/10/26 14:19
 */
public class AiBotUtil {
    private static final Logger logger = LoggerFactory.getLogger(AiBotUtil.class);
    public static final String AI_BOT_URL;
    public static final String ACCESS_KEY;

    static {
        AI_BOT_URL = SpringUtil.getProperty("ai-bot.url");
        ACCESS_KEY = SpringUtil.getProperty("ai-bot.Wxcz-Access-Key");
    }

    /**
     * 注册
     *
     * @param username 账户
     * @param password 密码
     */
    public static void usersRegister(String username, String password) {
        // 创建请求体
        JSONObject requestBody = new JSONObject(2);
        requestBody.put("username", username);
        requestBody.put("password", password);

        // 创建请求
        HttpRequest request = HttpRequest.post(AI_BOT_URL + "/users/register")
            .header("Wxcz-Access-Key", ACCESS_KEY)
            .setConnectionTimeout(2000)
            .setReadTimeout(2000)
            .body(requestBody.toJSONString());

        // 执行请求
        try (HttpResponse execute = request.execute()) {
            String responseBody = execute.body();

            // 将请求返回转为Json
            JSONObject responseJson = JSONObject.parse(responseBody);
            logger.info("responseJson:{}", responseJson);

            // 判断注册是否成功
            if (!"user is exists".equals(responseJson.getString("message"))) {
                CheckUtils.throwIf(responseJson.getIntValue("code") != 0, responseJson.getString("message"));
            }
        } catch (cn.hutool.core.io.IORuntimeException e) {
            logger.error("用户注册请求超时: {}", e.getMessage());
            //throw new RuntimeException("用户注册请求超时，请稍后重试");
        }
    }

    /**
     * 登录
     */
    public static String login(String username, String password) {
        // 创建请求体
        JSONObject requestBody = new JSONObject(2);
        requestBody.put("username", username);
        requestBody.put("password", password);

        // 创建请求
        HttpRequest request = HttpRequest.post(AI_BOT_URL + "/users/login")
            .header("Wxcz-Access-Key", ACCESS_KEY)
            .setConnectionTimeout(2000)
            .setReadTimeout(2000)
            .body(requestBody.toJSONString());

        // 执行请求
        try (HttpResponse execute = request.execute()) {
            String responseBody = execute.body();

            // 将请求返回转为Json
            JSONObject responseJson = JSONObject.parse(responseBody);

            // 判断登录是否成功
            CheckUtils.throwIf(!"true".equals(responseJson.getString("success")), "AI Bot登录失败！");

            // 返回Token
            return responseJson.getJSONObject("data").getString("token");
        } catch (cn.hutool.core.io.IORuntimeException e) {
            logger.error("用户登录超时: {}", e.getMessage());
            //throw new RuntimeException("用户注册请求超时，请稍后重试");
        }
        return "";
    }

    /**
     * 修改密码
     *
     * @param oldPassword 原密码
     * @param newPassword 新密码
     */
    public static void modifyPassword(String oldPassword, String newPassword) {
        // 创建请求体
        JSONObject requestBody = new JSONObject(2);
        requestBody.put("oldPassword", oldPassword);
        requestBody.put("newPassword", newPassword);

        // 创建请求
        HttpRequest request = HttpRequest.post(AI_BOT_URL + "/users/password")
            .header("Wxcz-Access-Key", ACCESS_KEY)
            .header("Authorization", "Bearer " + LoginHelper.getLoginUser().getAiBotToken())
            .body(requestBody.toJSONString());

        // 执行请求
        try (HttpResponse execute = request.execute()) {
            String responseBody = execute.body();

            // 将请求返回转为Json
            JSONObject responseJson = JSONObject.parse(responseBody);

            // 判断注册是否成功
            CheckUtils.throwIf(responseJson.getIntValue("code") != 0, "修改失败！");
        }
    }

    /**
     * 个人图库列表
     *
     * @param page  当前页
     * @param size  每页数量
     * @param isAsc 是否升序
     * @return 图片URL
     */
    public static PageResp<String> getImagePage(Integer page, Integer size, Boolean isAsc) {
        // 创建请求参数
        JSONObject requestParamsMap = new JSONObject(4);
        requestParamsMap.put("category", "generated");
        requestParamsMap.put("sort", isAsc ? "+id" : "-id");
        requestParamsMap.put("page", page);
        requestParamsMap.put("size", size);

        // 创建请求
        HttpRequest request = HttpRequest.get(AI_BOT_URL + "/resources/private/many?" + HttpUtil
            .toParams(requestParamsMap))
            .header("Wxcz-Access-Key", ACCESS_KEY)
            .header("Authorization", "Bearer " + LoginHelper.getLoginUser().getAiBotToken());

        // 执行请求
        try (HttpResponse execute = request.execute()) {
            String responseBody = execute.body();

            // 将请求返回转为Json
            JSONObject responseJson = JSONObject.parse(responseBody);

            // 判断查询是否成功
            if (!"true".equals(responseJson.getString("success"))) {
                throw NotLoginException.newInstance("AI-BOT", INVALID_TOKEN, INVALID_TOKEN_MESSAGE, null)
                    .setCode(SaErrorCode.CODE_11012);
            }

            JSONArray items = responseJson.getJSONObject("data").getJSONArray("items");
            List<String> urlList = items.stream().map(item -> {
                JSONObject jsonObject = (JSONObject)item;
                return jsonObject.getString("url");
            }).toList();

            return new PageResp<>(urlList, responseJson.getJSONObject("data").getInteger("total"));
        }
    }

    /**
     * 获取图片拓展信息
     *
     * @param imageUrl 图片地址
     * @return 图片拓展信息
     */
    public static JSONObject getImageExif(String imageUrl) {
        if (StrUtil.startWith(imageUrl, AI_BOT_URL)) {
            return new JSONObject();
        }

        // 获取图片ID
        String imageId = Base64.decodeStr(StrUtil.removePrefix(imageUrl, AI_BOT_URL + "/resources/download/"));

        // 创建请求参数
        JSONObject requestParamsMap = new JSONObject(1);
        requestParamsMap.put("fields", "exif");

        // 创建请求
        HttpRequest request = HttpRequest.get(AI_BOT_URL + "/resources/" + imageId + "/private?" + HttpUtil
            .toParams(requestParamsMap))
            .header("Wxcz-Access-Key", ACCESS_KEY)
            .header("Authorization", "Bearer " + LoginHelper.getLoginUser().getAiBotToken());

        // 执行请求
        try (HttpResponse execute = request.execute()) {
            String responseBody = execute.body();

            // 将请求返回转为Json
            JSONObject responseJson = JSONObject.parse(responseBody);

            // 判断查询是否成功
            if (!"true".equals(responseJson.getString("success"))) {
                throw NotLoginException.newInstance("AI-BOT", INVALID_TOKEN, INVALID_TOKEN_MESSAGE, null)
                    .setCode(SaErrorCode.CODE_11012);
            }

            // 获取拓展信息
            return responseJson.getJSONObject("data").getJSONObject("exif");
        }
    }
}
