package com.cyksj.service.claude.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.mapper.ClaudeSessionMapper;
import com.cyksj.model.entity.ClaudeSession;
import com.cyksj.service.claude.ClaudeSessionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author chan
 * @date 2024/8/9 10:46
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class ClaudeSessionServiceImpl extends ServiceImpl<ClaudeSessionMapper, ClaudeSession> implements ClaudeSessionService {


    private static final String MIRROR_CLAUDE_DOMAIN = "https://claudeplus.com.cn";

    @Override
    public void getSession(String email, String password, String officialSession, Boolean isPlus) {
        ClaudeSession one = this.getOne(Wrappers.lambdaQuery(ClaudeSession.class).orderByDesc(ClaudeSession::getId).last(" limit 1"));
        if (isPlus == null) {
            isPlus = true;
        }
        try {
            JSONObject loginResult = getLoginResult(email, password, officialSession, isPlus ? "Claude-PRO-" + one.getId() + 1 : "Claude-" + one.getId() + 1);

            //{
            //    "code": 1000,
            //        "message": "BaseResMessage",
            //        "data": {
            //    "id": 1
            //}
            //}

            if (!loginResult.getInt("code").equals(1000)) {
                log.error("新增claude 镜像账号异常，res:{}", loginResult);
            }
        } catch (Exception e) {
            throw BusinessRuntimeException.getInstance("登录获取token错误 error:" + e.getMessage());
        }
    }

    /**
     * 获取登录结果
     */
    private JSONObject getLoginResult(String email, String password, String officialSession, String carId) throws Exception {
        HttpRequest request = new HttpRequest(MIRROR_CLAUDE_DOMAIN + "/adminapi/chatgpt/session/add");
        request.form("email", email);
        request.form("password", password);
        request.form("officialSession", officialSession);
        request.form("carID", carId);
        HttpResponse execute = request.method(Method.POST).execute();
        return new JSONObject(execute.body());
    }

}
