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.QueryFieldBuilder;
import nckd.jxccl.swc.constants.MasConstant;

import java.util.Arrays;
import java.util.Comparator;
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_entldrmgrtermassmt
* @author W.Y.C
* @date 2025/12/2 19:49
* @version 1.0
*/
public class EntldrMgrTermAssmtFormPlugin 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_TERM)
                .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));
        DynamicObject term =  ConvertUtil.toDynamicObjectOrNull(this.getModel().getValue(MasConstant.NCKD_TERM));
        if(payUnit != null && lawEntity != null && term != null){
            //====================================== 获取任期人员名单 begin ======================================
            QueryFieldBuilder queryFieldBuilder = QueryFieldBuilder.create()
                    .addIdNumberName(MasConstant.NCKD_PAYUNIT)
                    .addIdNumberName(MasConstant.NCKD_LAWENTITY)
                    .addIdNumberName(MasConstant.NCKD_TERM)
                    .addIdNumberName(MasConstant.NCKD_EMPLOYEE)
                    .add(FormConstant.NCKD_STARTDATE)
                    .add(FormConstant.NCKD_ENDDATE)
                    .add(MasConstant.NCKD_POSNAME)
                    .add(MasConstant.NCKD_SERVICEMONTHS);

            QFilter qFilter = 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_TERM, QCP.equals, term.getLong(FormConstant.ID_KEY))
                    .and(FormConstant.STATUS, QCP.in, new String[]{StatusEnum.C.toString(), StatusEnum.B.toString()});
            DynamicObject[] dbSubCorpSalaryArray = BusinessDataServiceHelper.load(MasConstant.TENUREPERSONLIST_ENTITYID, queryFieldBuilder.buildSelect(), new QFilter[]{qFilter});
            // 获取所有人员ID
            List<Long> employeeIds = Arrays.stream(dbSubCorpSalaryArray)
                    .map(obj -> obj.getDynamicObject(MasConstant.NCKD_EMPLOYEE).getLong(FormConstant.ID_KEY))
                    .collect(Collectors.toList());
            //====================================== 获取任期人员名单 end ======================================

            //====================================== 查询企业负责人信息 begin ======================================
            //查询企业负责人信息
            QueryFieldBuilder entHeadFieldBuilder = QueryFieldBuilder.create()
                    .add(MasConstant.ID_KEY)
                    .add(MasConstant.NCKD_TERM)
                    .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))
                    ));
            //====================================== 查询企业负责人信息 end ======================================


            DynamicObjectCollection entryEntities = getModel().getEntryEntity(FormConstant.NCKD_ENTRYENTITY);
            entryEntities.clear();
            if(dbSubCorpSalaryArray != null && dbSubCorpSalaryArray.length > 0) {
                for (DynamicObject dbSubCorpSalary : dbSubCorpSalaryArray) {
                    long dbSubCorpSalaryTermId = dbSubCorpSalary.getLong(String.join(".", MasConstant.NCKD_TERM, MasConstant.ID_KEY));
                    DynamicObject employee = dbSubCorpSalary.getDynamicObject(MasConstant.NCKD_EMPLOYEE);
                    List<DynamicObject> entHead = groupedEntHeadQuery.get(employee.getLong(FormConstant.ID_KEY));
                    Optional<DynamicObject> latestEntHead = Optional.empty();
                    if (entHead != null && !entHead.isEmpty()) {

                        latestEntHead = entHead.stream()
                                .filter(record -> {
                                    long termId = record.getLong(String.join(".", MasConstant.NCKD_TERM, MasConstant.ID_KEY));
                                    // 判断记录是否在当年范围内
                                    return termId == dbSubCorpSalaryTermId;
                                })
                                .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);

        }
    }
}