package nckd.jxccl.hr.psms.plugin.operate.other;

import com.grapecity.documents.excel.drawing.L;
import kd.bos.common.enums.EnableEnum;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.utils.ObjectUtils;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.ExtendedDataEntity;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.entity.operate.result.OperationResult;
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.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.exception.ValidationException;
import nckd.jxccl.hr.psms.common.PositionStructureConstant;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
* 高级人才聘任-解聘
* 实体标识：nckd_dismissappoint
* @author W.Y.C
* @date 2025/12/25 20:40
* @version 1.0
*/
public class DismissAppointOpPlugin extends AbstractOperationServicePlugIn implements Plugin {

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        e.getFieldKeys().addAll(this.billEntityType.getAllFields().keySet());
    }

    @Override
    public void onAddValidators(AddValidatorsEventArgs e) {
        e.addValidator(new AbstractValidator() {

            @Override
            public void validate() {
                List<Long> ids = new ArrayList<>();
                for (ExtendedDataEntity dataEntity : getDataEntities()) {
                    DynamicObject data = dataEntity.getDataEntity();
                    String idStrs = data.getString("nckd_ids");
                    List<Long> idList = Arrays.stream(idStrs.split(","))
                            .filter(StringUtils::isNotBlank)
                            .map(String::trim)
                            .map(Long::valueOf)
                            .collect(Collectors.toList());
                    ids.addAll(idList);
                    Date endDate = data.getDate(PositionStructureConstant.NCKD_ENDDATE);
                    if(endDate == null){
                        this.addFatalErrorMessage(dataEntity,"请选择解聘时间");
                    }else{
                        //聘任结束日期超出当前日期
                        if(endDate.after(new Date())){
                            this.addFatalErrorMessage(dataEntity,"解聘时间超出当前日期");
                        }
                    }
                }
                MainEntityType personPosFileEntityType = EntityMetadataCache.getDataEntityType(PositionStructureConstant.PERSONPOSFILE_ENTITYID);
                DynamicObject[] personPosFileList = BusinessDataServiceHelper.load(ids.toArray(), personPosFileEntityType);
                Map<Long, DynamicObject> personPosFileMap = Arrays.stream(personPosFileList)
                        .collect(Collectors.toMap(
                                obj -> obj.getLong(FormConstant.ID_KEY), // 以ID作为key
                                obj -> obj, // 以DynamicObject本身作为value
                                (existing, replacement) -> existing // 如果有重复key，保留现有的值
                        ));
                for (ExtendedDataEntity dataEntity : getDataEntities()) {
                    DynamicObject data = dataEntity.getDataEntity();
                    Date endDate = data.getDate(PositionStructureConstant.NCKD_ENDDATE);
                    if(endDate != null) {
                        String idStrs = data.getString("nckd_ids");
                        List<Long> idList = Arrays.stream(idStrs.split(","))
                                .filter(StringUtils::isNotBlank)
                                .map(String::trim)
                                .map(Long::valueOf)
                                .collect(Collectors.toList());
                        for (Long l : idList) {
                            DynamicObject dynamicObject = personPosFileMap.get(l);
                            Date date = dynamicObject.getDate(PositionStructureConstant.NCKD_BEGINDATE);
                            //聘任结束日期在聘任开始日期之前
                            if(endDate.before(date)){
                                this.addFatalErrorMessage(dataEntity,"聘任结束日期在聘任开始日期之前");
                            }
                            String employMentStatus = dynamicObject.getString(PositionStructureConstant.NCKD_EMPLOYMENTSTATUS);
                            if(!EnableEnum.YES.getCode().equalsIgnoreCase(employMentStatus)){
                                this.addFatalErrorMessage(dataEntity,"只能对【已聘任】状态记录进行此操作");
                            }
                        }
                    }
                }
            }
        });
    }

    @Override
    public void beginOperationTransaction(BeginOperationTransactionArgs e) {
        Map<Long, Date> idMap = new HashMap<>();
        for (DynamicObject dataEntity : e.getDataEntities()) {
            Date endDate = dataEntity.getDate(PositionStructureConstant.NCKD_ENDDATE);
            String idStrs = dataEntity.getString("nckd_ids");
            List<Long> idList = Arrays.stream(idStrs.split(","))
                    .filter(StringUtils::isNotBlank)
                    .map(String::trim)
                    .map(Long::valueOf)
                    .collect(Collectors.toList());
            for (Long id : idList) {
                idMap.put(id, endDate);
            }
        }
        MainEntityType personPosFileEntityType = EntityMetadataCache.getDataEntityType(PositionStructureConstant.PERSONPOSFILE_ENTITYID);
        DynamicObject[] personPosFileList = BusinessDataServiceHelper.load(idMap.keySet().toArray(new Long[0]), personPosFileEntityType);
        for (DynamicObject personPosFile : personPosFileList) {
            long id = personPosFile.getLong(FormConstant.ID_KEY);
            personPosFile.set(PositionStructureConstant.NCKD_EMPLOYMENTSTATUS,EnableEnum.NO.getCode());
            personPosFile.set(PositionStructureConstant.NCKD_ENDDATE,idMap.get(id));
        }
        OperationResult operationResult = SaveServiceHelper.saveOperate(PositionStructureConstant.PERSONPOSFILE_ENTITYID, personPosFileList, OperateOption.create());
        if (!operationResult.isSuccess()) {
            StringJoiner errorMsg = new StringJoiner("\n");
            for (IOperateInfo error : operationResult.getAllErrorOrValidateInfo()) {
                errorMsg.add(error.getMessage());
            }
            if (!ObjectUtils.isEmpty(operationResult.getMessage())) {
                errorMsg.add(operationResult.getMessage());
            }
            throw new ValidationException("解聘高级人才失败，原因：" + errorMsg.toString());
        }
    }
}