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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.algo.DataSet;
import kd.bos.algo.Row;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.db.DB;
import kd.bos.db.DBRoute;
import kd.bos.exception.KDException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.schedule.executor.AbstractTask;
import kd.sdk.plugin.Plugin;

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

/**
 * 2025-04-16 Tyx
 * 人员变动数据同步MDM
 */
public class SyncPersonTask extends AbstractTask implements Plugin {
    private static final Log log = LogFactory.getLog(SyncPersonTask.class);
    private static String person_entity = "hrpi_person";                //人员主表
    private static String perNonTsProp_entity = "hrpi_pernontsprop";    //人员非时序性属性 维护完一般不会变动的数据，民族性别血型等；
    private static String perTsProp_entity = "hrpi_pertsprop";          //人员时序性属性 维护完会发生变动的数据，婚姻/生育/健康状况等；
    private static String empPosOrg_entity = "hrpi_empposorgrel";       //员工任职经历 取岗位组织等信息
    private static String perRegion_entity = "hrpi_perregion";          //员工区域信息 籍贯等信息
    private static String perContact_entity = "hrpi_percontact";        //员工联系方式，用于取电话号码和邮箱等
    private static String quitBill_entity = "htm_quithandle";           //离职办理单，用于取离职日期及离职单号
    private static String perCre_entity = "hrpi_percre";                //员工证件信息，用于取身份证/证照
    private static String startTime = "";
    private static String endTime = "";
    private static Set changePersonSet = new HashSet<>();
    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        log.info("-------- SyncPositionTask 开始执行同步人员 --------");
        try {
            JSONObject ob = new JSONObject();
            initDateRange(map);
            //sql查出来数据
            DataSet dataSet = getChangePerson();
            //dataSet.print(true);
            //处理组织长名称
            Map<Long, DynamicObject> orgDyxMap = SyncUtil.initOrgInfo();
            //获取调用接口地址
            String url = SyncUtil.getUrl("person_url");
            log.info("-------- 人员同步调用url : " + url + " --------");
            //处理兼职
            Map<Long, JSONArray> partTimeMap = SyncUtil.getPartTimeInfo(orgDyxMap);
            //构建入参
            buildJSON(ob, dataSet, orgDyxMap, partTimeMap);
            if(ob.getJSONArray("obj").size() == 0) {
                SyncUtil.createLog(SyncUtil.v_success, startTime, endTime, "未查询到变化人员", "未调用", SyncUtil.SyncPerson);
                return;
            }
            //Tyx 2025-05-07 改成分批传输
            SyncUtil.batchPost(url, ob, SyncUtil.SyncPerson, startTime, endTime);
        } catch (ParseException e) {
            SyncUtil.createLog(SyncUtil.v_error, startTime, endTime, null, e.getMessage(), SyncUtil.SyncPerson);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void buildJSON(JSONObject ob, DataSet dataSet, Map<Long, DynamicObject> orgDyxMap, Map<Long, JSONArray> partTimeMap) {
        JSONArray obj = new JSONArray();
        String[] fieldNames = dataSet.getRowMeta().getFieldNames();
        while(dataSet.hasNext()) {
            JSONObject data = new JSONObject(true);
            Row rowData = dataSet.next();
            //循环put数据
            for (String field : fieldNames) {
                data.put(field.toUpperCase(), rowData.get(field));
            }
            //处理组织长名称
            data.put("EMP_W_DEPLNAME", orgDyxMap.get(rowData.getLong("orgid")).getString("structure.fullname"));
            //data.put("EMP_W_EMPLOYNUMBER", "test-20250401-0011");
            changePersonSet.add(rowData.getLong("PERSONID"));

            //处理兼职
            JSONArray partJob = partTimeMap.get(rowData.getLong("PERSONID"));
            if(partJob != null) {
                data.put("partJob", partJob);
            }
            obj.add(data);
        }
        ob.put("obj", obj);
    }


        /**
         * 受不了了直接写sql语句de
         * @return
         */
    public DataSet getChangePerson() {
        //获取人员查询sql
        StringBuilder sb = SyncUtil.getPersonQuerySql();
        StringBuilder updatePartSb = SyncUtil.getPersonPartTimeChangeSql(startTime, endTime);
        //修改日期
        sb.append("   and (");
        sb.append("   (to_char(person.fmodifytime,'yyyy-MM-dd hh24:mi:ss') <= '"+endTime+"' and to_char(person.fmodifytime,'yyyy-MM-dd hh24:mi:ss') >=  '"+startTime+"' ) or \n");
        sb.append("   (to_char(a.fmodifytime,'yyyy-MM-dd hh24:mi:ss') <= '"+endTime+"' and to_char(a.fmodifytime,'yyyy-MM-dd hh24:mi:ss') >=  '"+startTime+"' ) or \n");
        sb.append("   (to_char(b.fmodifytime,'yyyy-MM-dd hh24:mi:ss') <= '"+endTime+"' and to_char(b.fmodifytime,'yyyy-MM-dd hh24:mi:ss') >=  '"+startTime+"' ) or \n");
        sb.append("   (to_char(c.fmodifytime,'yyyy-MM-dd hh24:mi:ss') <= '"+endTime+"' and to_char(c.fmodifytime,'yyyy-MM-dd hh24:mi:ss') >=  '"+startTime+"' ) or \n");
        sb.append("   (to_char(d.fmodifytime,'yyyy-MM-dd hh24:mi:ss') <= '"+endTime+"' and to_char(d.fmodifytime,'yyyy-MM-dd hh24:mi:ss') >=  '"+startTime+"' ) or \n");
        sb.append("   (to_char(e.fmodifytime,'yyyy-MM-dd hh24:mi:ss') <= '"+endTime+"' and to_char(e.fmodifytime,'yyyy-MM-dd hh24:mi:ss') >=  '"+startTime+"' ) or \n");
        sb.append("   (to_char(f.fmodifytime,'yyyy-MM-dd hh24:mi:ss') <= '"+endTime+"' and to_char(f.fmodifytime,'yyyy-MM-dd hh24:mi:ss') >=  '"+startTime+"' ) or \n");
        sb.append("   (to_char(g.fmodifytime,'yyyy-MM-dd hh24:mi:ss') <= '"+endTime+"' and to_char(g.fmodifytime,'yyyy-MM-dd hh24:mi:ss') >=  '"+startTime+"' ) or \n");
        sb.append("   (to_char(g1.fmodifytime,'yyyy-MM-dd hh24:mi:ss') <= '"+endTime+"' and to_char(g1.fmodifytime,'yyyy-MM-dd hh24:mi:ss') >=  '"+startTime+"' ) or \n");
        sb.append("   (to_char(h.fmodifytime,'yyyy-MM-dd hh24:mi:ss') <= '"+endTime+"' and to_char(h.fmodifytime,'yyyy-MM-dd hh24:mi:ss') >=  '"+startTime+"' ) or \n");
        sb.append("   (to_char(m.fmodifytime,'yyyy-MM-dd hh24:mi:ss') <= '"+endTime+"' and to_char(m.fmodifytime,'yyyy-MM-dd hh24:mi:ss') >=  '"+startTime+"' ) or \n");
        sb.append("   (to_char(pos.fmodifytime,'yyyy-MM-dd hh24:mi:ss') <= '"+endTime+"' and to_char(pos.fmodifytime,'yyyy-MM-dd hh24:mi:ss') >=  '"+startTime+"' ) or \n");
        sb.append("   (to_char(pos1.fmodifytime,'yyyy-MM-dd hh24:mi:ss') <= '"+endTime+"' and to_char(pos1.fmodifytime,'yyyy-MM-dd hh24:mi:ss') >=  '"+startTime+"' ) or \n");
        sb.append("   (a.fid in (select fpersonid from t_hrpi_ermanfile where to_char(fmodifytime,'yyyy-MM-dd hh24:mi:ss') <= '"+endTime+"' and to_char(fmodifytime,'yyyy-MM-dd hh24:mi:ss') >= '"+startTime+"')) or \n");
        sb.append("   (a.fid in (" + updatePartSb.toString() + ")) \n");
        sb.append("   )");
        log.info("-------- 查询人员sql :" + sb.toString() + " -------- ");
        DataSet dataSet = DB.queryDataSet(this.getClass().getName(), DBRoute.of("hr"), sb.toString());
        return dataSet;
    }

    /**
     * 根据调度作业上配置的参数初始化时间范围
     * @param map
     */
    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.SyncPerson));
            endTime = sdf.format(new Date());
        }
    }
}