package nckd.jimin.jyyy.hr.hrmp.hbpm.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.exception.KDException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QFilter;
import kd.bos.orm.util.CollectionUtils;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.util.StringUtils;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import kd.sdk.plugin.Plugin;

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

/**
 * 2025-04-16 Tyx
 * 岗位变动数据同步MDM
 */
public class SyncPositionTask extends AbstractTask implements Plugin {
    private static final Log log = LogFactory.getLog(SyncPositionTask.class);
    private static String posChgRecord_entity = "hbpm_chgrecord";   //岗位变动明细
    private static String posDetail_entity = "homs_positionhis";    //岗位历史查询
    private static String startTime = "";
    private static String endTime = "";
    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        try {
            log.info("-------- SyncPositionTask 开始执行同步岗位 --------");
            JSONObject ob = new JSONObject();
            initDateRange(map);
            HRBaseServiceHelper helper = new HRBaseServiceHelper(posChgRecord_entity);
            String selectProperties = "position,evententry.changescene.number,evententry.operatetime";
            //String selectProperties = "aaa";
            //查出发生过变化的岗位
            DynamicObjectCollection changeOperateCol = helper.queryOriginalCollection(selectProperties, this.getQFilters());
            //查询出来为空直接返回
            if(CollectionUtils.isEmpty(changeOperateCol)) {
                log.info("-------- 未查询到变化岗位 -------- ");
                SyncUtil.createLog(SyncUtil.v_success, startTime, endTime, "未查询到变化岗位", "未调用", SyncUtil.SyncPosition);
            }
            else {
                //按岗位ID汇总，查询时间段内发生变化的岗位
                Map<Long, DynamicObject> changeOperateMap = (Map)changeOperateCol.stream().collect(Collectors.toMap((dyx) -> {
                    return dyx.getLong("position");
                }, (dyx) -> {
                    return dyx;
                }, (key1, key2) -> {
                    return key2;
                }));
                log.info("-------- 变化岗位数（不去重）：" + changeOperateCol.size() + " --------");
                log.info("-------- 变化岗位数（去重）：" + changeOperateMap.keySet().size() + " --------");
                log.info("-------- 变化岗位Id：" + changeOperateMap.keySet() + " --------");

                //查询出变化岗位之后，找到对应岗位数据以及所属组织数据
                selectProperties = "id,adminorg.id,adminorg.name,adminorg.number,adminorg.nckd_easid,parent.name,parent.id,parent.number,number,name,enable,isleader,modifytime,issensitive,nckd_isgxp";
                QFilter idQFilter = new QFilter("id", "in", changeOperateMap.keySet());
                DynamicObjectCollection posDyArr = new HRBaseServiceHelper(posDetail_entity).queryOriginalCollection(selectProperties, new QFilter[]{idQFilter});
                log.info("-------- 查询完岗位详细信息数：" + posDyArr.size() + " --------");
                //处理下组织长名称
                Map<Long, DynamicObject> orgMap = (Map)posDyArr.stream().collect(Collectors.toMap((dyx) -> {
                    return dyx.getLong("adminorg.id");
                }, (dyx) -> {
                    return dyx;
                }, (key1, key2) -> {
                    return key2;
                }));
                //工具类查询组织相关信息返回Map key为组织ID
                Map<Long, DynamicObject> orgDyxMap = SyncUtil.initOrgInfo(orgMap);
                //获取调用接口地址
                String url = SyncUtil.getUrl("position_url");
                log.info("-------- 岗位同步调用url : " + url + " --------");
                //构建入参
                buildJSON(ob, posDyArr, changeOperateMap, orgDyxMap);
                // 2025-05-07 Tyx 改为分批传输 默认300一批
                SyncUtil.batchPost(url, ob, SyncUtil.SyncPosition, startTime, endTime);
            }
        } catch (ParseException e) {
            SyncUtil.createLog(SyncUtil.v_error, startTime, endTime, e.getMessage(), "未调用", SyncUtil.SyncPosition);
        } catch (IOException e) {
            SyncUtil.createLog(SyncUtil.v_error, startTime, endTime, e.getMessage(), "未调用", SyncUtil.SyncPosition);
        }
    }

    /**
     * 构建调MDM接口的入参
     * @param ob                //最后调用的JSONObject
     * @param posDyArr          //岗位历史查询，查询出来的岗位相关信息
     * @param changeOperateMap  //岗位变动明细，备用，暂用不上
     * @param orgDyxMap         //组织信息，用于处理长名称
     */
    public void buildJSON(JSONObject ob, DynamicObjectCollection posDyArr, Map<Long, DynamicObject> changeOperateMap, Map<Long, DynamicObject> orgDyxMap) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //构造岗位的树形结构
        Map<Long, Integer> levelMap = SyncUtil.initPositionTree();
        JSONArray obj = new JSONArray();
        for(DynamicObject pos : posDyArr) {
            JSONObject data = new JSONObject(true);
            //主体标签
            data.put("MAIN_BODY_ID", "JY");
            //级别
            data.put("MD_LEVEL", levelMap.get(pos.getLong("id")));
            //所属行政组织名称
            data.put("POSI_SUB_DEP_NAME",pos.getString("adminorg.name"));
            //所属行政组织ID 老岗位用EASID 新岗位用星瀚ID
            String parentId = StringUtils.isBlank(pos.getString("adminorg.nckd_easid")) ? pos.getString("adminorg.id") : pos.getString("adminorg.nckd_easid");
            data.put("POSI_SUB_DEP_CODE",parentId);
            //所属行政组织全程 长名称
            data.put("POSI_SUB_DEP_LNAME",orgDyxMap.get(pos.getLong("adminorg.id")).getString("structure.fullname"));
            //汇报岗位名称
            data.put("POSI_REPPOST_NAME",pos.getString("parent.name"));
            //汇报岗位编码
            data.put("POSI_REPPOST_CODE",pos.getString("parent.number"));
            //岗位编码
            data.put("MD_CODE",pos.getString("number"));
            //岗位名称
            data.put("MD_DESCRIPTION",pos.getString("name"));
            //岗位状态 MDM:1-启用，2-禁用；星瀚：1-启用，0-禁用
            int enable = pos.getInt("enable");
            if(enable == 1) {
                data.put("POSI_STATE","1");
            }
            else if(enable == 0){
                data.put("POSI_STATE","2");
            }
            else {
                data.put("POSI_STATE","0");
            }
            //是否负责人职位
            int isLeader = pos.getInt("isleader");
            if(isLeader == 1) {
                data.put("POSI_POSIT_CHARGE","是");
            }
            else {
                data.put("POSI_POSIT_CHARGE","否");
            }
            //是否涉密岗位
            int isSecret = pos.getInt("issensitive");
            if(isSecret == 1) {
                data.put("POSI_IS_SECRET","是");
            }
            else {
                data.put("POSI_IS_SECRET","否");
            }
            //是否GXP
            int isGxp = pos.getInt("nckd_isgxp");
            if(isGxp == 1) {
                data.put("POSI_IS_GXP","是");
            }
            else {
                data.put("POSI_IS_GXP","否");
            }
            //最后更新时间
            data.put("POSI_LAST_UPTIME",sdf.format(pos.getDate("modifytime")));
            obj.add(data);
        }
        //入参排序
        SyncUtil.setJSONArraySorted(obj, "MD_LEVEL");
        ob.put("obj", obj);
    }





    public void initDateRange(Map<String, Object> map) throws ParseException {
        boolean isAuto = Boolean.valueOf(map.get("isAuto").toString());
        if(!isAuto) {
            startTime = map.get("startTime").toString();
            endTime = map.get("endTime").toString();
        }
        //取最近一次日志的时间
        else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            startTime = sdf.format(SyncUtil.getLastSyncEndTime(SyncUtil.SyncPosition));
            endTime = sdf.format(new Date());
        }
    }
    /**
     * 构建查询变化岗位的过滤条件
     * @return
     */
    public QFilter[] getQFilters() {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            QFilter filter = new QFilter("evententry.operatetime", ">=", sdf.parse(startTime));
            filter.and("evententry.operatetime", "<", sdf.parse(endTime));
            //filter.and("org.otclassify", "=", 1010L);
            //filter.and("position.number", QCP.equals, "JY-20250407-01772");
            log.info("-------- 查询岗位变化过滤条件：" + filter.toString() + " --------");
            return new QFilter[]{filter};
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }



}