package nckd.jxccl.swc.mas.plugin.form.assessmentmgm;

import kd.bos.common.enums.EnableEnum;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.constant.StatusEnum;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.utils.ConvertUtil;
import nckd.jxccl.base.common.utils.DateUtil;
import nckd.jxccl.base.common.utils.QueryFieldBuilder;
import nckd.jxccl.swc.constants.MasConstant;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
* 企业负责人经理层业绩考核-表单插件
* 实体标识：nckd_entldrmgrperfassmt
* @author W.Y.C
* @date 2025/12/2 18:31
* @version 1.0
*/
public class EntldrMgrPerfAssmtFormPlugin extends AbstractFormPlugin implements Plugin {

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        String fieldKey = e.getProperty().getName();
        ChangeData[] changeSet = e.getChangeSet();
        int rowIndex = changeSet[0].getRowIndex();
        Object oldValue = changeSet[0].getOldValue();
        Object newValue = changeSet[0].getNewValue();
        if(Stream.of(MasConstant.NCKD_PAYUNIT, MasConstant.NCKD_LAWENTITY, MasConstant.NCKD_YEAR)
                .anyMatch(op -> op.equalsIgnoreCase(fieldKey))){
            if(!Objects.equals(oldValue, newValue)){
                DynamicObjectCollection entryEntities = getModel().getEntryEntity(FormConstant.NCKD_ENTRYENTITY);
                load();
            }
        }
    }

    private void load(){

        DynamicObject payUnit = ConvertUtil.toDynamicObjectOrNull(this.getModel().getValue(MasConstant.NCKD_PAYUNIT));
        DynamicObject lawEntity =  ConvertUtil.toDynamicObjectOrNull(this.getModel().getValue(MasConstant.NCKD_LAWENTITY));
        Date year = ConvertUtil.toDate(this.getModel().getValue(MasConstant.NCKD_YEAR));
        if(payUnit != null && lawEntity != null && year != null){

            LocalDateTime localDateTime = DateUtil.toLocalDateTime(year);
            LocalDateTime beginOfYear = DateUtil.beginOfYear(localDateTime);
            LocalDateTime endOfYear = DateUtil.endOfYear(localDateTime);

            QFilter filter = new QFilter(MasConstant.NCKD_PAYUNIT, QCP.equals, payUnit.getLong(FormConstant.ID_KEY))
                    .and(MasConstant.NCKD_LAWENTITY, QCP.equals, lawEntity.getLong(FormConstant.ID_KEY))
                    .and(MasConstant.NCKD_YEAR, QCP.large_equals, DateUtil.toDate(beginOfYear))
                    .and(MasConstant.NCKD_YEAR, QCP.less_equals, DateUtil.toDate(endOfYear))
                    .and(FormConstant.STATUS, QCP.in, new String[]{StatusEnum.C.toString(), StatusEnum.B.toString()});

            //====================================== 获取子企业负责人任职情况 begin ======================================
            QueryFieldBuilder subCoHeadServiceQueryFieldBuilder = QueryFieldBuilder.create()
                    .add(MasConstant.NCKD_EMPLOYEE)
                    .add(MasConstant.NCKD_POSNAME)
                    .add(MasConstant.NCKD_SERVICEMONTHS)
                    .add(MasConstant.NCKD_ISDIRCADRE)
                    .add(MasConstant.NCKD_ISPROFMAN)
                    .add(MasConstant.NCKD_ISMANAGER)
                    .add(MasConstant.NCKD_MGTLVLDTL)
                    .add(MasConstant.NCKD_SALNEGOT)
                    .add(MasConstant.NCKD_SALCALCPOST)
                    .add(MasConstant.NCKD_YEAR)
                    .add(MasConstant.NCKD_STARTDATE)
                    .add(MasConstant.NCKD_ENDDATE);
            DynamicObject[] dbSubCoHeadServiceArray = BusinessDataServiceHelper.load(MasConstant.SUBCOHEADSERVICE_ENTITYID, subCoHeadServiceQueryFieldBuilder.buildSelect(), new QFilter[]{filter});
            if(dbSubCoHeadServiceArray == null || dbSubCoHeadServiceArray.length == 0){
                this.getView().showTipNotification("未加载到数据，根据【所属二级单位】、【法人组织】及【年度】未加载到对应“子企业负责人任职情况”数据！");
            }
            DynamicObjectCollection entryEntities = getModel().getEntryEntity(FormConstant.NCKD_ENTRYENTITY);
            entryEntities.clear();
            if(dbSubCoHeadServiceArray != null && dbSubCoHeadServiceArray.length > 0) {
                // 获取所有人员ID
                List<Long> employeeIds = Arrays.stream(dbSubCoHeadServiceArray)
                        .map(obj -> obj.getDynamicObject(MasConstant.NCKD_EMPLOYEE).getLong(FormConstant.ID_KEY))
                        .collect(Collectors.toList());
                //====================================== 获取子企业负责人任职情况 end ======================================

                //查询企业负责人信息
                QueryFieldBuilder entHeadFieldBuilder = QueryFieldBuilder.create()
                        .add(MasConstant.ID_KEY)
                        .add(MasConstant.STARTDATE)
                        .add(MasConstant.ENDDATE)
                        .addIdNumberName(MasConstant.NCKD_TERM)
                        .addIdNumberName(MasConstant.EMPLOYEE_KEY)
                        .orderDesc(MasConstant.STARTDATE, MasConstant.ENDDATE);
                //用于判断该批人员是否为：实行任期制和契约化管理
                QFilter allEntHeadFilter = new QFilter(FormConstant.EMPLOYEE_KEY, QCP.in, employeeIds)
                        //是否实行任期制和契约化管理
                        .and(MasConstant.NCKD_TERMCONT, QCP.equals, EnableEnum.YES.getCode());
                //查询出人员所有的企业负责人信息
                DynamicObjectCollection allEntHeadQuery = QueryServiceHelper.query(FormConstant.NCKD_HRPI_ENTHEAD, entHeadFieldBuilder.buildSelect(), new QFilter[]{allEntHeadFilter});
                Map<Long, List<DynamicObject>> groupedEntHeadQuery = allEntHeadQuery.stream()
                        .collect(Collectors.groupingBy(
                                obj -> obj.getLong(String.join(".", MasConstant.EMPLOYEE_KEY, FormConstant.ID_KEY))
                        ));


                if (dbSubCoHeadServiceArray != null && dbSubCoHeadServiceArray.length > 0) {
                    for (DynamicObject dbSubCorpSalary : dbSubCoHeadServiceArray) {
                        DynamicObject employee = dbSubCorpSalary.getDynamicObject(MasConstant.NCKD_EMPLOYEE);
                        List<DynamicObject> entHead = groupedEntHeadQuery.get(employee.getLong(FormConstant.ID_KEY));
                        // 根据 STARTDATE 和 ENDDATE 查找在 NCKD_STARTDATE 和 NCKD_ENDDATE 范围内的数据，取最新一条
                        Date dbYear = dbSubCorpSalary.getDate(MasConstant.NCKD_YEAR);
                        // 筛选出在dbYear范围内的记录，然后取STARTDATE最新的那一条
                        Optional<DynamicObject> latestEntHead = Optional.empty();
                        if (entHead != null && !entHead.isEmpty()) {
                            LocalDateTime dbYearBegin = DateUtil.beginOfYear(DateUtil.toLocalDateTime(dbYear));
                            LocalDateTime dbYearEnd = DateUtil.endOfYear(DateUtil.toLocalDateTime(dbYear));

                            latestEntHead = entHead.stream()
                                    .filter(record -> {
                                        Date startDate = record.getDate(MasConstant.STARTDATE);
                                        Date endDate = record.getDate(MasConstant.ENDDATE);
                                        // 判断记录是否在当年范围内
                                        return startDate != null && !startDate.after(DateUtil.toDate(dbYearEnd)) &&
                                                (endDate == null || !endDate.before(DateUtil.toDate(dbYearBegin)));
                                    })
                                    .max(Comparator.comparing(record -> record.getDate(MasConstant.STARTDATE),
                                            Comparator.nullsFirst(Comparator.naturalOrder())));
                        }
                        if (latestEntHead.isPresent()) {
                            DynamicObject entry = entryEntities.addNew();
                            entry.set(MasConstant.NCKD_EMPLOYEE, dbSubCorpSalary.get(MasConstant.NCKD_EMPLOYEE));
                            entry.set(MasConstant.NCKD_POSNAME, dbSubCorpSalary.get(MasConstant.NCKD_POSNAME));
                            entry.set(MasConstant.NCKD_STARTDATE, dbSubCorpSalary.get(MasConstant.NCKD_STARTDATE));
                            entry.set(MasConstant.NCKD_ENDDATE, dbSubCorpSalary.get(MasConstant.NCKD_ENDDATE));
                        }

                    }
                    this.getView().showSuccessNotification("数据加载成功！");
                } else {
                    this.getView().showTipNotification("未加载到数据，根据【所属二级单位】、【法人组织】及【任期区间】未加载到对应“子企业负责人薪酬结构”数据！");
                }
            }
            getModel().updateEntryCache(entryEntities);
            getView().updateView(FormConstant.NCKD_ENTRYENTITY);

        }
    }
}