package org.jk.job.snailjob;

import com.aizuda.snailjob.client.job.core.annotation.JobExecutor;
import com.aizuda.snailjob.client.job.core.dto.JobArgs;
import com.aizuda.snailjob.model.dto.ExecuteResult;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.jk.common.core.config.DeepseekConfig;
import org.jk.common.json.utils.JsonUtils;
import org.jk.job.entity.BillDto;
import org.jk.rag.domain.bo.SysTokenLogBo;
import org.jk.rag.service.IJkRagService;
import org.jk.rag.service.ISysTokenLogService;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * DAG工作流任务-模拟支付宝账单任务
 * <a href="https://juejin.cn/post/7487860254114644019"></a>
 *
 * @author 老马
 */
@Slf4j
@Component
@RequiredArgsConstructor
@JobExecutor(name = "tokenTask")
public class TokenAddTask {

    private final ISysTokenLogService sysTokenLogService;

    private final DeepseekConfig deepseekConfig;
    public ExecuteResult jobExecute(JobArgs jobArgs) throws InterruptedException {
        // 1. 核心业务逻辑（替换为你的实际代码）
        log.info("===== 每2小时任务开始执行 =====");
        log.info("当前时间：{}", LocalDateTime.now());
        // 示例：执行业务操作（如数据同步、报表生成、接口调用等）
        doBusinessLogic();
        log.info("===== 每2小时任务执行完成 =====\n");
        log.info("我进来了！");
        return ExecuteResult.success("");
    }

    private void doBusinessLogic() {
        SysTokenLogBo sysTokenLogBo = new SysTokenLogBo();
        String url = deepseekConfig.getBaseurl() + deepseekConfig.getTokenSpeed();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("query","你好");
        jsonObject.put("model","Qwen3-30B");
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toJSONString());
        Request request = buildPostRequest(url, requestBody);
        OkHttpClient client = buildOkHttpClient();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String body = response.body().string();
                if (isJsonObject(body)) {
                    JSONObject result = JSONObject.parseObject(body);
                    if(result.getString("code").equals("200")) {
                        JSONObject data = JSONObject.parseObject(result.getString("data"));
                        sysTokenLogBo.setTokenSpeed(data.getString("token_speed"));
                        sysTokenLogBo.setElapsedTime(data.getString("elapsed_time"));
                        sysTokenLogService.insertByBo(sysTokenLogBo);
                    }

                }
            }
        } catch (IOException e) {
            log.info("deepseek Request URL: {}", e.getMessage());
        }

    }

    private Request buildPostRequest(String url, RequestBody requestBody) {
        return new Request.Builder()
            .addHeader("User-Agent", "insomnia/10.3.1")
            .addHeader("Content-Type", "application/json")
            .url(url).post(requestBody).build();
    }

    private OkHttpClient buildOkHttpClient() {
        return new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(50, TimeUnit.SECONDS)
            .readTimeout(20, TimeUnit.MINUTES)
            .build();
    }

    private boolean isJsonObject(String data) {
        try {
            JSON.parseObject(data);
            return true;
        } catch (Exception e) {
            return false;
        }
    }



}
