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://kelaode.nf.video";

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

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

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

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

}
