package nckd.jimin.jyyy.hr.task.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.exception.KDBizException;
import kd.bos.ext.fi.plugin.ArApConvert.util.EmptyUtils;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.sdk.util.KHttpClientUtils;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.util.StringUtils;
import kd.hr.hbp.business.application.impl.newhismodel.HisModelController;
import kd.hr.hbp.business.domain.model.newhismodel.HisResponse;
import kd.hr.hbp.business.domain.model.newhismodel.HisVersionParamBo;
import kd.hr.hbp.business.domain.model.newhismodel.VersionChangeRespData;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import kd.hr.hbp.common.constants.newhismodel.EnumHisOperateType;
import nckd.base.helper.CommonHelperUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

public class SyncOAHelper {
    private static final Log log = LogFactory.getLog(SyncOAHelper.class);
    private static final String PERSON_ENTITY = "hrpi_person";
    public static final String PERFORMANCE_ENTITY = "nckd_hrpi_performan";

    public static Map<String, String> syncPerformanceData(Map<String, Object> map) {
        Map<String, String> result = new HashMap<>();
        Map<String, String> mapentity = CommonHelperUtils.getCommonParams("OA-Performance");
        String code = getCode(mapentity);
        String accessToken = getToken(mapentity, code);
        JSONArray totalJSONArray = getData(mapentity, accessToken, map);
        dealPerformanceData(totalJSONArray);
        return result;
    }

    public static String getCode(Map<String, String> mapentity) {
        String code = null;
        try {
            if(mapentity == null){
                throw new KDBizException("相关客户化参数未配置");
            }
            String param_corpid = mapentity.get("corpid");
            String param_response = mapentity.get("response_type");
            String param_state = mapentity.get("state");
            String param_app_key = mapentity.get("app_key");
            String param_app_secret = mapentity.get("app_secret");
            String param_code_url = mapentity.get("getcode");
            String param_token_url = mapentity.get("gettoken");

            if( StringUtils.isEmpty(param_corpid) || StringUtils.isEmpty(param_app_secret)
                    || StringUtils.isEmpty(param_code_url) || StringUtils.isEmpty(param_token_url)
                    ||  StringUtils.isEmpty(param_app_key)){
                throw new KDBizException("相关客户化参数未配置");
            }

            Map<String, String> header = new HashMap<>();
            header.put("Content-Type", "application/json");

            //获取token
            StringBuilder authorizeUrl = new StringBuilder();
            authorizeUrl.append(param_code_url);
            authorizeUrl.append("?corpid=");
            authorizeUrl.append(param_corpid);
            authorizeUrl.append("&response_type=");
            authorizeUrl.append(param_response);
            authorizeUrl.append("&state=");
            authorizeUrl.append(param_state);

            String bodyJSONString = getBody();

            log.info("请求泛微 接口：" + authorizeUrl);
            String response = KHttpClientUtils.postjson(authorizeUrl.toString().toString(),header,bodyJSONString);
            JSONObject codeJson = JSONObject.parseObject(response);
            code = codeJson.getString("code");
            log.info("请求泛微 authorizeUrl Return：" + code );
        } catch (IOException e) {
            throw new KDBizException("请求泛微authorizeUrl接口失败：" + e.getMessage());
        }
        return code;
    }

    public static String getToken(Map<String, String> mapentity, String code) {
        String token = null;
        try {
            String param_app_key = mapentity.get("app_key");
            String param_grant_type = mapentity.get("grant_type");
            String param_app_secret = mapentity.get("app_secret");
            String param_token_url = mapentity.get("gettoken");

            StringBuilder tokenUrl = new StringBuilder();
            tokenUrl.append(param_token_url);
            tokenUrl.append("?app_key=");
            tokenUrl.append(param_app_key);
            tokenUrl.append("&app_secret=");
            tokenUrl.append(param_app_secret);
            tokenUrl.append("&grant_type=");
            tokenUrl.append(param_grant_type);
            tokenUrl.append("&code=");
            tokenUrl.append(code);

            Map<String, String> header = new HashMap<>();
            header.put("Content-Type", "application/json");
            String bodyJSONString = getBody();
            log.info("请求泛微 接口：" + tokenUrl);
            String reToken = KHttpClientUtils.postjson(tokenUrl.toString(), header, bodyJSONString);
            log.info("请求泛微 TokenUrl Return：" + reToken);
            JSONObject tokenJson = JSONObject.parseObject(reToken);
            token = tokenJson.getString("accessToken");
        } catch (IOException e) {
            throw new KDBizException("请求泛微authorizeUrl接口失败：" + e.getMessage());
        }
        return token;
    }

    public static JSONArray getData (Map<String, String> mapentity, String token, Map<String, Object> map) {
        try {
            String post_getperformance_url = mapentity.get("getperformance");
            String param_secretkey = mapentity.get("secret_key");
            String param_operator = mapentity.get("operator");
            Map<String, String> header = new HashMap<>();
            header.put("Content-Type", "application/json");

            StringBuilder performanceUrl = new StringBuilder();
            performanceUrl.append(post_getperformance_url);
            performanceUrl.append("?access_token=");
            performanceUrl.append(token);
            performanceUrl.append("&secret_key=");
            performanceUrl.append(param_secretkey);

            JSONArray totalDataArr = new JSONArray();
            boolean status = true;
            int pageNo = 1;
            int pageSize = 200;
            while(status) {
                String response = getPerformanceData(performanceUrl, param_operator, header, pageNo, pageSize, map, mapentity);
                JSONObject responseData = JSONObject.parseObject(response);
                JSONObject dataJson = responseData.getJSONObject("datajson");
                JSONArray datas = dataJson.getJSONArray("datas");
                if(datas.size() < pageSize) {
                    status = false;
                }
                totalDataArr.addAll(datas);
                pageNo++;
            }
            return totalDataArr;

        } catch (Exception e) {
            throw new KDBizException("请求OA接口失败：" + e.getMessage());
        }
    }

    public static String getPerformanceData (StringBuilder performanceUrl, String operator, Map<String, String> header, int pageNo, int pageSize, Map<String, Object> map, Map<String, String> mapentity) throws IOException {
        String param = getPerformanceBody(operator, pageNo, pageSize, map, mapentity);
        log.info("请求OA 接口：" + performanceUrl.toString());
        log.info("请求OA data：" + param);
        String response = KHttpClientUtils.postjson(performanceUrl.toString(), header, param);
        log.info("请求OA Performance Return：" + response);
        return response;
    }

    private static void dealPerformanceData(JSONArray datas) {
        List<DynamicObject> dynList = new ArrayList<>();
        for(int i = 0; i < datas.size(); i++) {
            HRBaseServiceHelper helper = HRBaseServiceHelper.create(PERFORMANCE_ENTITY);
            DynamicObject dyn = helper.generateEmptyDynamicObject();
            JSONObject data = datas.getJSONObject(i);
            JSONObject mainTable = data.getJSONObject("mainTable");
            //判断是否存在过
            //主键    id
            String oaId = mainTable.getString("id");
            if(SyncOAUtil.checkIsExist(oaId))
                continue;
            String khpf = mainTable.getString("khpf");
            if("已自评".equals(khpf))
                continue;
            //如果
            //员工工号 yggh
            String personNumber = mainTable.getString("yggh");
            HRBaseServiceHelper personHelper = new HRBaseServiceHelper(PERSON_ENTITY);
            DynamicObject[] personDyn = personHelper.query(new QFilter[]{SyncOAUtil.getPersonFilter(personNumber)});
            if(personDyn.length == 0){
                log.info("未找到对应的员工：{}", personNumber);
                continue;
            }
            //考核方式 pgzq 月度/季度；考核年月 zq X月/第X季度
            String typeStr = mainTable.getString("pgzq");
            String type = "";
            if(typeStr.equals("月度")) {
                type = "2";
            }else if (typeStr.equals("季度")) {
                type = "1";
            }
            String year = mainTable.getString("nf");
            String value = mainTable.getString("zq");
            Date bizDate = SyncOAUtil.handleDate(year, type, value);
            //考核分数 khpf
            BigDecimal score = new BigDecimal(khpf);
            //备注    ?
            dyn.set("person", personDyn[0]);
            dyn.set("nckd_bizdate", bizDate);
            dyn.set("nckd_examinetype", type);
            dyn.set("nckd_score", score);
            dyn.set("nckd_oaid", oaId);
            //2025-09-08 Tyx 前台无法显示，这里给initstatus默认赋值‘2’
            dyn.set("initstatus", "2");
            dynList.add(dyn);
        }
        log.info("共查询：{}条，去重后：{}条", datas.size(), dynList.size());
        if(dynList.size() > 0) {
            DynamicObject[] dynCols = dynList.stream().toArray(DynamicObject[]::new);
            HisVersionParamBo hisVersionParamBo = new HisVersionParamBo();
            hisVersionParamBo.setOperateType(EnumHisOperateType.NO_TIME_SAVE_VERSION.getType());
            hisVersionParamBo.setEntityNumber(PERFORMANCE_ENTITY);
            hisVersionParamBo.setHisDyns(dynCols);
            HisModelController hisModelController = HisModelController.getInstance();
            HisResponse<VersionChangeRespData> hisResponse = hisModelController.noLineTimeHisVersionChange(hisVersionParamBo);
            log.info(hisResponse.toString());
        }
    }

    /**
     *
     * @param operator
     * @param pageNo
     * @param pageSize
     * @param param     调度作业上的参数
     * @param mapentity commonparam里的参数
     * @return
     */
    public static String getPerformanceBody(String operator, int pageNo, int pageSize, Map<String, Object> param, Map<String, String> mapentity)
    {
        // 构建 requestHead 对象
        JSONObject requestHead = new JSONObject();
        requestHead.put("mainBodyId", "JY");

        // 构建 pageInfo 对象
        JSONObject pageInfo = new JSONObject();
        pageInfo.put("pageNo", pageNo);
        pageInfo.put("pageSize", pageSize);

        // 构建 header 对象
        JSONObject header = new JSONObject();
        header.put("operator", operator);

        // 构建 datajson 对象
        JSONObject datajsonParent = new JSONObject();
        JSONObject datajson = new JSONObject();
        JSONObject mainTable = new JSONObject();
        getMainTable(mainTable, param, mapentity);
        datajson.put("mainTable", mainTable);
        datajson.put("pageInfo", pageInfo);
        datajson.put("header", header);
        datajsonParent.put("datajson", datajson);

        // 构建 requestData 数组
        JSONArray requestData = new JSONArray();
        requestData.add(datajsonParent);

        // 构建最终的根 JSON 对象
        JSONObject rootJson = new JSONObject();
        rootJson.put("requestHead", requestHead);
        rootJson.put("requestData", requestData);

        return rootJson.toString();
    }

    public static String getBody(){
        JSONObject requestHead = new JSONObject();
        requestHead.put("mainBodyId", "JY");

        JSONObject rootJson = new JSONObject();
        rootJson.put("requestHead", requestHead);
        return rootJson.toString();
    }

    public static void getMainTable(JSONObject mainTable, Map<String, Object> param, Map<String, String> mapentity) {
        //获取是年度还是季度
        String typeStr = param.get("type").toString();
        String typeId = mapentity.get(typeStr + "_type");
        mainTable.put("pgzq", typeId);

        String year = "";
        String zq = "";
        String zqId = "";
        boolean isAuto = Boolean.valueOf(param.get("isAuto").toString());
        //如果isAuto = true：year = 当前日期上月所在年份，zq = 当前日期上月 或者 当前日期上月所在季度
        if(isAuto) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            year = String.valueOf(calendar.get(Calendar.YEAR));
            if(typeStr.equals("month")) {
                zq = String.valueOf(calendar.get(Calendar.MONTH) + 1);
            }
            else if (typeStr.equals("season")) {
                int month = calendar.get(Calendar.MONTH);
                int quarter = (month / 3) + 1;
                zq = String.valueOf(quarter);
            }
            zqId = mapentity.get(typeStr + zq);
        }
        //如果isAuto = false; year和zq都取调度作业上参数值
        else {
            year = param.get("year").toString();
            zq = typeStr + param.get("zq").toString();
            zqId = mapentity.get(zq);
        }
        mainTable.put("nf", year);
        mainTable.put("zq", zqId);
    }


}
