package nckd.jxccl.hr.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.param.CustomParam;
import kd.bos.exception.KDException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.parameter.SystemParamServiceHelper;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.hr.ApiClient;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Tyx 2025-11-04
 * 获取党建系统政治面貌数据
 */
public class GetPoliticalPartyTask extends AbstractTask implements Plugin {

    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map){
        //获取token
        String tokenUri = getBaseURI("GET_TOKEN_URI");
        String appId = getBaseURI("APPID");
        String secret = getBaseURI("SECRET");
        String tokenAllUri = tokenUri + "?appid=" + appId + "&secret=" + secret;
        String accessToken = ApiClient.getToken(tokenAllUri);

        //获取党建系统数据
        String politicalUri = getBaseURI("GET_POLITICAL_PART_URI");
        String code = getBaseURI("CODE");
        String sysCode = getBaseURI("SYSCODE");
        JSONObject jsonData = new JSONObject();
        if (map != null && map.containsKey("updateTime")) {
            String updateTime = (String) map.get("updateTime");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if(!"".equals(updateTime)){
                updateTime = sdf.format(updateTime);
                jsonData.put("updateTime", updateTime);
            }
        }
        String data = jsonData.toJSONString();
        String result = ApiClient.getPoliticalPartyData(politicalUri, sysCode, accessToken, code, data);
        if (result == null || result.trim().isEmpty()) {
            return;
        }

        // 解析为JSONArray
        JSONArray jsonArray = JSON.parseArray(result);
        List<JSONObject> jsonObjectList = jsonArray.toJavaList(JSONObject.class);

        //查询hr系统
        HRBaseServiceHelper helper1 = new HRBaseServiceHelper("hrpi_employee");
        // 过滤条件
        QFilter filter = new QFilter("iscurrentversion", QCP.equals, "1");
        // 获取empnumber，可能为空
        DynamicObject[] employeeDyns = helper1.load(new QFilter[]{filter});

        //将Map转换为List
        List<Object> empnumbers = Arrays.stream(employeeDyns).map(x -> x.getPkValue()).collect(Collectors.toList());
        HRBaseServiceHelper helper2 = new HRBaseServiceHelper("hrpi_perregion");
        // 查询现有员工的区域信息
        filter = new QFilter("employee", QCP.in, empnumbers);
        DynamicObject[] perregionDyns = helper2.load("employee,politicalstatus,joinpartydate", new QFilter[]{filter});
        Map<String, DynamicObject> perregionMaps = Arrays.stream(perregionDyns).collect(
                Collectors.toMap(
                        obj -> obj.getString("employee.empnumber"),
                        obj -> obj,
                        (k1, k2) -> k1
                )
        );
        DynamicObject perRegionDyn = null;
        String politicalStatus = null;
        String politicalLandscapeDate = null;
        Date date = null;
        List<DynamicObject> dynamicObjectList = new ArrayList<>();
        String logincode = null;
        for(DynamicObject employeeDyn : employeeDyns){
            logincode = employeeDyn.getString("empnumber");
            DynamicObject perregionObject = perregionMaps.get(logincode);
            if(perregionObject != null) {
                // 查询原来的【区域信息】数据
                perRegionDyn = perregionObject;
            }
            else {
                // 生成一个空的【区域信息】数据包
                perRegionDyn = helper2.generateEmptyDynamicObject();
            }
            List<JSONObject> jsonObject = jsonObjectList.stream().filter(x -> x.getString("sapNo").equals(employeeDyn.getString("empnumber"))).collect(Collectors.toList());
            if(jsonObject.size() > 0){
                //获取政治面貌数据
                JSONArray detailList = jsonObject.get(0).getJSONArray("detailList");
                for (int j = 0; j < detailList.size(); j++) {
                    JSONObject detail = detailList.getJSONObject(j);
                    politicalStatus = detail.getString("politicalLandscape");
                    politicalLandscapeDate = detail.getString("politicalLandscapeDate");
                }

            }else{
                continue;
            }

            // 获取政治面貌基础数据：
            HRBaseServiceHelper helper3 = new HRBaseServiceHelper("hbss_politicalstatus");
            // 通过描述字段匹配党建系统的数据
            filter = new QFilter("description", QCP.like, "%" + politicalStatus + "%");
            DynamicObject politicalStatusDyn = helper3.loadOne(new QFilter[]{filter});
            if(politicalStatusDyn == null){
                continue;
            }
            // 赋值相关字段：
            // 员工
            perRegionDyn.set("employee", employeeDyn);
            // 政治面貌
            perRegionDyn.set("politicalstatus", politicalStatusDyn);
            // 入党日期
            if(politicalLandscapeDate != null && !"".equals(politicalLandscapeDate)){
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    date = formatter.parse(politicalLandscapeDate);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                perRegionDyn.set("joinpartydate", date);
            }


            // 落库
            dynamicObjectList.add(perRegionDyn);
        }
        DynamicObject[] list = dynamicObjectList.toArray(new DynamicObject[0]);
        helper2.save(list);
    }

    /**
     * 获取 公共自定义参数  GET_TOKEN_URI
     */
    public String getBaseURI(String key) {
        CustomParam customParam = new CustomParam();
        customParam.getSearchKeySet().add(key);
        Map<String, String> cusTomMap = SystemParamServiceHelper.loadCustomParameterFromCache(customParam);
        String value  = cusTomMap.get(key);
        return value;
    }
}