package com.zcloud.basic.info.plan;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.jjb.saas.framework.job.Job;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.zcloud.basic.info.command.RzUserRecordAddExe;
import com.zcloud.gbscommon.utils.Tools;
import com.zcloud.gbscommon.utils.UuidUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Component
@Slf4j
public class DockingRZUserPlanJob implements Job {

    private static final String BASE_URL = "http://192.168.10.56:8090";

    @Resource
    private final RzUserRecordAddExe rzUserRecordAddExe;

//    @JobRegister(cron = "0 30 0 * * ?", jobDesc = "超期未检查记录",triggerStatus = 1)
//    @XxlJob("com.zcloud.zcGbsServicer.plan.CheckRecordPlanJob")
    public ReturnT<String> execute(String param) {
        System.out.println("开始执行计划任务");
        XxlJobHelper.log( "============定时获取人资人员信息开始==========");
        // 获取总页数
        Integer userInfoCount = getUserInfoCount();
        // 定义每页大小
        int pageSize = 200;
        // 计算总页数
        int totalPages = (int) Math.ceil((double) userInfoCount / pageSize);

        for (int pageNum = 1; pageNum <= totalPages; pageNum++) {
            try {
                XxlJobHelper.log("正在获取第 " + pageNum + "/" + totalPages + " 页数据...");

                // 调用接口
                getUserInfo(pageNum, pageSize);

                XxlJobHelper.log("第 " + pageNum + " 页数据获取成功");

                // 可选：添加延时，避免请求过快
                if (pageNum < totalPages) {
                    Thread.sleep(1000); // 1000毫秒间隔
                }

            } catch (Exception e) {
                XxlJobHelper.log("第 " + pageNum + " 页获取失败: " + e.getMessage());
                // 可以选择继续执行下一页，或者中断
                // break; // 如果需要失败就停止
            }
        }
        XxlJobHelper.log( "============定时获取人资人员信息结束==========");
        return ReturnT.SUCCESS;
    }


//    @JobRegister(cron = "0 30 0 * * ?", jobDesc = "超期未检查记录",triggerStatus = 1)
//    @XxlJob("com.zcloud.zcGbsServicer.plan.CheckRecordPlanJob")
    public ReturnT<String> executeChange(String param) {
        System.out.println("开始执行计划任务");
        XxlJobHelper.log( "============定时获取人资变动信息开始==========");

        JSONArray userChangeInfo = getUserChangeInfo();
        // 处理数据
        rzUserRecordAddExe.executeJsonArray(userChangeInfo);

        XxlJobHelper.log( "============定时获取人资变动信息结束==========");
        return ReturnT.SUCCESS;
    }

    /**
     * 获取人资人员信息总数
     * @return
     */
    public static Integer getUserInfoCount(){
        String url = BASE_URL + "/docking/rz/getUserInfoCount";

        // 发送 POST 请求
        String result = HttpRequest.post(url)
                .timeout(30000)  // 30秒超时
                .execute()
                .body();

        System.out.println("响应结果：" + result);
        if(result == null || StringUtils.isEmpty(result)){
            return 0;
        }
        return Integer.valueOf(result);
    }

    public static String getUserInfo(Integer pageNum, Integer pageSize) {
        // 方式1：GET 请求（如果接口是GET方式）
        String url = BASE_URL + "/docking/rz/getUserInfo";

        // 构建请求参数
        Map<String, Object> params = new HashMap<>();
        params.put("pageNum", pageNum);
        params.put("pageSize", pageSize);

        // 发送 POST 请求
        String result = HttpRequest.post(url)
                .form(params)  // 表单参数
                .timeout(30000)  // 30秒超时
                .execute()
                .body();

        System.out.println("响应结果：" + result);
        JSONArray jsonArray = JSONUtil.parseArray(result);

        if(jsonArray == null){
            return null;
        }

        return result;
    }

    public static JSONArray getUserChangeInfo() {
        // 方式1：GET 请求（如果接口是GET方式）
        String url = BASE_URL + "/docking/rz/getUserChangeInfo";

        // 发送 POST 请求
        String result = HttpRequest.post(url)
                .timeout(30000)  // 30秒超时
                .execute()
                .body();

        System.out.println("响应结果：" + result);
        JSONArray jsonArray = JSONUtil.parseArray(result);

        if(jsonArray == null){
            return null;
        }

        return jsonArray;
    }
}
