package nckd.jxccl.opmc.pm.plugin.operate.cycle;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.ExtendedDataEntity;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.AddValidatorsEventArgs;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.BeginOperationTransactionArgs;
import kd.bos.entity.validate.AbstractValidator;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
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.base.common.utils.StrFormatter;
import nckd.jxccl.opmc.pm.common.PerfManagerFormConstant;
import nckd.jxccl.opmc.pm.helper.PerfManagerHelper;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* 考核周期删除OP
* 实体标识：nckd_perfmanager
* @author W.Y.C
* @date 2025/11/5 15:46
* @version 1.0
*/
public class PerfManagerDeleteOpPlugin extends AbstractOperationServicePlugIn implements Plugin {

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        e.getFieldKeys().add(PerfManagerFormConstant.NCKD_BEGINYEAR);
        e.getFieldKeys().add(PerfManagerFormConstant.NCKD_ENDYEAR);
        e.getFieldKeys().add(FormConstant.NCKD_PERSON);
        e.getFieldKeys().add(FormConstant.NCKD_PERSON);
        e.getFieldKeys().add(PerfManagerFormConstant.NCKD_THESTATUS);
        e.getFieldKeys().add(PerfManagerFormConstant.NCKD_ISCURRENTNEWEST);
    }

    @Override
    public void onAddValidators(AddValidatorsEventArgs e) {
        e.addValidator(new AbstractValidator() {
            @Override
            public void validate() {
                List<Long> personIds = new ArrayList<>();
                for (ExtendedDataEntity rowDataEntity : getDataEntities()) {
                    DynamicObject data = rowDataEntity.getDataEntity();
                    long personId = data.getLong(String.join(".", FormConstant.NCKD_PERSON, FormConstant.ID_KEY));
                    personIds.add(personId);
                }

                //获取已归档人员，已归档人员不能修改考核结果
                QueryFieldBuilder perfArchiveRecordQueryFieldBuilder = QueryFieldBuilder.create()
                        .addIdNumberName(FormConstant.NCKD_PERSON)
                        .add(PerfManagerFormConstant.NCKD_YEAR);
                QFilter perfArchiveRecordFilter = new QFilter(FormConstant.NCKD_PERSON, QCP.in, personIds);
                //查找已归档的记录（状态为1）
                perfArchiveRecordFilter = perfArchiveRecordFilter.and(new QFilter(PerfManagerFormConstant.NCKD_ARCHIVESTATUS, QCP.equals, "1"));
                DynamicObjectCollection perfArchiveRecordQuery = QueryServiceHelper.query(PerfManagerFormConstant.PERFARCHIVERECORD_ENTITYID, perfArchiveRecordQueryFieldBuilder.buildSelect(), new QFilter[]{perfArchiveRecordFilter});
                // 创建已归档人员ID和年度的映射集合
                Map<Long, List<Date>> archivedPersonYearPairs = perfArchiveRecordQuery.stream()
                        .collect(Collectors.groupingBy(
                                obj -> obj.getLong(String.join(".", FormConstant.NCKD_PERSON, FormConstant.ID_KEY)),
                                Collectors.mapping(obj -> obj.getDate(PerfManagerFormConstant.NCKD_YEAR), Collectors.toList())
                        ));


                for (ExtendedDataEntity rowDataEntity : getDataEntities()) {
                    DynamicObject data = rowDataEntity.getDataEntity();
                    boolean isCurrentNewest = data.getBoolean(PerfManagerFormConstant.NCKD_ISCURRENTNEWEST);
                    if(!isCurrentNewest){
                        // addMessage(rowDataEntity,"不能删除历史周期，只能删除最新考核周期");
                    }
                    String theStatus = data.getString(PerfManagerFormConstant.NCKD_THESTATUS);
                    if(!"1".equalsIgnoreCase(theStatus)){
                        addMessage(rowDataEntity, StrFormatter.format("考核周期状态【{}】，不能删除","2".equals(theStatus) ? "已锁定":"已结束"));
                    }


                    //校验已归档不能删除
                    LocalDateTime beginYear = ConvertUtil.toLocalDateTime(data.getDate(PerfManagerFormConstant.NCKD_BEGINYEAR));
                    LocalDateTime endYear = ConvertUtil.toLocalDateTime(data.getDate(PerfManagerFormConstant.NCKD_ENDYEAR));
                    DynamicObject person = data.getDynamicObject(FormConstant.NCKD_PERSON);
                    long personId = person.getLong(FormConstant.ID_KEY);
                    String personName = person.getString(FormConstant.NAME_KEY);
                    List<Date> dates = archivedPersonYearPairs.get(personId);
                    // 获取dates中年份最大的日期
                    if(dates != null) {
                        Date maxDate = dates.stream()
                                .filter(Objects::nonNull)
                                .max(Comparator.comparing(date -> DateUtil.toLocalDateTime(date).getYear()))
                                .orElse(null);
                        if (maxDate != null) {
                            LocalDateTime maxLocalDate = DateUtil.toLocalDateTime(maxDate);
                            if (maxLocalDate.getYear() >= beginYear.getYear() || maxLocalDate.getYear() >= endYear.getYear()) {
                                addFatalErrorMessage(rowDataEntity,
                                        StrFormatter.format("人员【{}】考核周期已归档，不能修改删除【{}】年及之前的考核周期。",
                                                personName,
                                                maxLocalDate.getYear()));
                            }

                        }
                    }
                }
            }
        });
    }

    @Override
    public void beginOperationTransaction(BeginOperationTransactionArgs e) {

        List<Long> personIds = new ArrayList<>();
        List<Long> ids = new ArrayList<>();
        for (DynamicObject data : e.getDataEntities()) {
            DynamicObject person = data.getDynamicObject(FormConstant.NCKD_PERSON);
            long personId = person.getLong(FormConstant.ID_KEY);
            personIds.add(personId);
            ids.add(data.getLong(FormConstant.ID_KEY));
        }
        //将人员所有周期标记为非最新
        PerfManagerHelper.markAsNotCurrentNewest(personIds.toArray(new Long[0]));
        //将当前人员最新周期（周期开始时间最近的一条）标记为最新的，并将最新一条“结束”状态标记为“正常”状态
        PerfManagerHelper.markAsCurrentNewestAndUpdateStatus(personIds,new QFilter(FormConstant.ID_KEY, QCP.not_in,ids));
    }
}