package nckd.jxccl.swc.init.plugin.other;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.exception.KDException;
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.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 延迟退休业务，回写核心人力人信息，依赖延迟退休计算任务 类名为DelayedRetirementDateCalcTask
 * 员工：hrpi_employee实体的三个字段
 * 原法定拟退休日期	nckd_origplanretdt
 * 新法定拟退休日期	nckd_newplanretdt
 * 员工确认退休日期	nckd_empcfmretdt
 * @author turborao
 * @date 2025/12/26 11:09
 *
 */
public class RetirementDateWriteHrpiTask extends AbstractTask implements Plugin {

    private static Log logger = LogFactory.getLog(RetirementDateWriteHrpiTask.class);
    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {

        logger.info("延迟退休回写  开始执行任务");
        /**
         * 将员工社保档案（hcsi_sinsurfile）单据中延迟退休时间回写到hrpi_employee实体中
         */
        syncRetirementDatesToEmployee();
        /**
         * 将退休人员信息（nckd_retirewarning）单据中确认延迟退休时间回写到hrpi_employeet和hcsi_sinsurfile实体中
         */
        syncEmployeeConfirmRetirementDate();

        logger.info("延迟退休回写完成  任务执行完成");

    }

    @Override
    public boolean isSupportReSchedule() {
        return true;
    }

    /**
     * 将员工社保档案（hcsi_sinsurfile）单据中延迟退休时间回写到hrpi_employee实体中
     * @return
     * @throws KDException
     */
    public void syncRetirementDatesToEmployee() throws KDException {
        // 假设你有一个 Date 对象
        Date currentDate = new Date(); // 当前日期
        // 将 Date 转换为 Instant 并减去8天
        Instant threeDaysAgoInstant = currentDate.toInstant().minus(8, ChronoUnit.DAYS);
        // 将 Instant 转换回 Date
        Date threeDaysAgoDate = Date.from(threeDaysAgoInstant);

        // 查询hcsi_sinsurfile中的退休日期信息
        QFilter filter1 = new QFilter("iscurrentversion", QCP.equals, "1"); // 启用
        QFilter filter2 = new QFilter("datastatus", QCP.equals, "1"); // 启用
        QFilter filter3 = new QFilter("modifytime", QCP.large_equals, threeDaysAgoDate);

        String selectFields = "id,employee.id,nckd_recorddate,nckd_legaldate,nckd_newlegaldate";
        DynamicObject[] employeeFileRecords = BusinessDataServiceHelper.load(
                FormConstant.HCSI_SINSURFILE,
                selectFields,
                new QFilter[]{filter1, filter2, filter3}
        );

        Map<Long, DynamicObject> employeeFileMaps = Arrays.stream(employeeFileRecords).collect(
                Collectors.toMap(
                        obj -> obj.getLong("employee.id"),
                        obj -> obj,
                        (k1, k2) -> k1
                )
        );
        //将Map转换为List
        List<Long> employeeIDs = employeeFileMaps.keySet().stream().collect(Collectors.toList());

        // 查询hrpi_employee实体中对应的员工信息
        QFilter empFilter = new QFilter("id", QCP.in, employeeIDs);
        QFilter empFilter1 = new QFilter("iscurrentversion", QCP.equals, "1"); // 启用
        QFilter empFilter2 = new QFilter("datastatus", QCP.equals, "1"); // 启用
        QFilter empFilter3 = new QFilter("isdeleted", QCP.equals, "0"); // 启用

        DynamicObject[] employeeRecords = BusinessDataServiceHelper.load(
                FormConstant.HRPI_EMPLOYEE,
                "id,nckd_origplanretdt,nckd_newplanretdt,nckd_empcfmretdt",
                new QFilter[]{empFilter,empFilter1,empFilter2,empFilter3}
        );

        // 将员工记录转换为Map便于查找
        Map<Long, DynamicObject> employeeMap = Arrays.stream(employeeRecords).collect(
                Collectors.toMap(
                        obj -> obj.getLong("id"),
                        obj -> obj,
                        (k1, k2) -> k1
                )
        );

        // 更新员工实体中的退休日期字段
        ArrayList<DynamicObject> updatedEmployees = new ArrayList<>();

        for (DynamicObject fileRecord : employeeFileRecords) {
            Long employeeId = fileRecord.getLong("employee.id");
            DynamicObject employee = employeeMap.get(employeeId);

            if (employee != null) {

                Date legalDate = fileRecord.getDate("nckd_legaldate");
                Date newLegalDate = fileRecord.getDate("nckd_newlegaldate");

                // 设置到hrpi_employee实体中
                employee.set("nckd_origplanretdt", legalDate);           // 原法定拟退休日期
                employee.set("nckd_newplanretdt", newLegalDate);        // 新法定拟退休日期
                // 注意：员工确认退休日期nckd_empcfmretdt在hcsi_sinsurfile中没有对应字段，
                // 如果需要，可能需要从其他地方获取或保持为空

                updatedEmployees.add(employee);
            }
        }

        // 保存更新
        if (!updatedEmployees.isEmpty()) {
            Object[] saved = SaveServiceHelper.save(updatedEmployees.toArray(new DynamicObject[0]));
            logger.info("同步退休日期到员工实体完成，更新数量：{}", saved.length);

        }

    }

    /**
     * 将退休人员信息（nckd_retirewarning）单据中确认延迟退休时间回写到hrpi_employee实体中
     * @return
     * @throws KDException
     */
    public void syncEmployeeConfirmRetirementDate() throws KDException {

        // 假设你有一个 Date 对象
        Date currentDate = new Date(); // 当前日期
        // 将 Date 转换为 Instant 并减去8天
        Instant threeDaysAgoInstant = currentDate.toInstant().minus(8, ChronoUnit.DAYS);
        // 将 Instant 转换回 Date
        Date threeDaysAgoDate = Date.from(threeDaysAgoInstant);

        // 查询nckd_retirewarning中的员工确认退休日期
        QFilter filter1 = new QFilter("modifytime", QCP.large_equals, threeDaysAgoDate);
        QFilter filter2 = new QFilter("nckd_commitdate", QCP.not_equals, null);
        String selectFields = "id,nckd_person.id,nckd_commitdate";
        DynamicObject[] retireWarningRecords = BusinessDataServiceHelper.load(
                FormConstant.NCKD_RETIREWARNING,
                selectFields,
                new QFilter[]{filter1, filter2}
        );
        Map<Long, DynamicObject> retireWarningMaps = Arrays.stream(retireWarningRecords).collect(
                Collectors.toMap(
                        obj -> obj.getLong("nckd_person.id"),
                        obj -> obj,
                        (k1, k2) -> k1
                )
        );
        List<Long> employeeIDs = retireWarningMaps.keySet().stream().collect(Collectors.toList());

        // 查询hrpi_employee实体中对应的员工信息
        QFilter empFilter = new QFilter("id", QCP.in, employeeIDs);
        DynamicObject[] employeeRecords = BusinessDataServiceHelper.load(
                FormConstant.HRPI_EMPLOYEE,
                "id,nckd_empcfmretdt",
                new QFilter[]{empFilter}
        );

        // 将员工记录转换为Map便于查找
        Map<Long, DynamicObject> employeeMap = Arrays.stream(employeeRecords).collect(
                Collectors.toMap(
                        obj -> obj.getLong("id"),
                        obj -> obj,
                        (k1, k2) -> k1
                )
        );

        // 更新员工实体中的员工确认退休日期字段
        ArrayList<DynamicObject> updatedEmployees = new ArrayList<>();

        for (DynamicObject warningRecord : retireWarningRecords) {
            Long employeeId = warningRecord.getLong("nckd_person.id");
            DynamicObject employee = employeeMap.get(employeeId);
            Date commitDate = warningRecord.getDate("nckd_commitdate");

            if (employee != null && commitDate != null) {
                // 设置员工确认退休日期到hrpi_employee实体
                employee.set("nckd_empcfmretdt", commitDate);
                updatedEmployees.add(employee);
            }
        }


        // 保存更新
        if (!updatedEmployees.isEmpty()) {
            Object[] saved = SaveServiceHelper.save(updatedEmployees.toArray(new DynamicObject[0]));
            logger.info("同步员工确认退休日期到员工实体完成，更新数量：{}", saved.length);

        }

        // 查询hcsi_sinsurfile实体中对应的员工信息
        QFilter filter3 = new QFilter("iscurrentversion", QCP.equals, "1"); // 启用
        QFilter filter4 = new QFilter("datastatus", QCP.equals, "1"); // 启用
        QFilter filter5 = new QFilter("employee.id", QCP.in, employeeIDs);
        DynamicObject[] sinsurfileRecords = BusinessDataServiceHelper.load(
                FormConstant.HCSI_SINSURFILE,
                "id,employee.id,nckd_commitdate",
                new QFilter[]{filter3, filter4, filter5}
        );

        // 将社保档案记录转换为Map便于查找
        Map<Long, DynamicObject> sinsurfileMap = Arrays.stream(sinsurfileRecords).collect(
                Collectors.toMap(
                        obj -> obj.getLong("employee.id"),
                        obj -> obj,
                        (k1, k2) -> k1
                )
        );

        // 更新社保档案实体中的员工确认退休日期字段
        ArrayList<DynamicObject> updatedSinsurfiles = new ArrayList<>();

        for (DynamicObject warningRecord : retireWarningRecords) {
            Long employeeId = warningRecord.getLong("nckd_person.id");
            DynamicObject sinsurfile = sinsurfileMap.get(employeeId);
            Date commitDate = warningRecord.getDate("nckd_commitdate");

            if (sinsurfile != null && commitDate != null) {
                // 设置员工确认退休日期到hcsi_sinsurfile实体
                sinsurfile.set("nckd_commitdate", commitDate);
                updatedSinsurfiles.add(sinsurfile);
            }
        }

        // 保存更新
        if (!updatedSinsurfiles.isEmpty()) {
            Object[] saved = SaveServiceHelper.save(updatedSinsurfiles.toArray(new DynamicObject[0]));
            logger.info("同步员工确认退休日期到社保档案实体完成，更新数量：{}", saved.length);
        }

    }

}