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

import kd.bos.common.enums.EnableEnum;
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.enums.psms.TypeStateEnum;
import nckd.jxccl.base.common.utils.QueryFieldBuilder;
import nckd.jxccl.base.common.utils.StrFormatter;
import nckd.jxccl.hr.psms.business.ManagerAllowanceService;
import nckd.jxccl.hr.psms.common.PositionStructureConstant;
import nckd.jxccl.hr.psms.helper.PositionFileHelper;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
* 职位档案删除OP
* @author W.Y.C
* @date 2025/10/13 10:06
* @version 1.0
*/
public class PersonPosFileDeleteOpPlugin extends AbstractOperationServicePlugIn implements Plugin {

    /** 需要生效的数据（key：id，value：生效日期）*/
    private Map<Long,Integer> idMaps = new HashMap<>();

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        e.getFieldKeys().add(FormConstant.NCKD_PERSON);
        e.getFieldKeys().add(PositionStructureConstant.NCKD_LASTPERSONPOSFILE);
        e.getFieldKeys().add(PositionStructureConstant.NCKD_TYPESTATE);
        e.getFieldKeys().add(PositionStructureConstant.NCKD_ADJUSSTATUS);
        e.getFieldKeys().add(PositionStructureConstant.NCKD_LOCKSTATUS);
        e.getFieldKeys().add(PositionStructureConstant.NCKD_DEP);
        e.getFieldKeys().add(PositionStructureConstant.NCKD_JOBLEVELHR);
        e.getFieldKeys().add(PositionStructureConstant.NCKD_JOBSEQHR);
        e.getFieldKeys().add(PositionStructureConstant.NCKD_PROTITLELEVEL);
        e.getFieldKeys().add(PositionStructureConstant.NCKD_EMPLOYMENTSTATUS);
    }

    @Override
    public void onAddValidators(AddValidatorsEventArgs e){
        e.addValidator(new AbstractValidator() {
            @Override
            public void validate() {
                for (ExtendedDataEntity rowDataEntity : getDataEntities()) {
                    DynamicObject data = rowDataEntity.getDataEntity();
                    long id = data.getLong(FormConstant.ID_KEY);
                    String adjustStatus = data.getString(PositionStructureConstant.NCKD_ADJUSSTATUS);
                    String typeState = data.getString(PositionStructureConstant.NCKD_TYPESTATE);
                    DynamicObject person = data.getDynamicObject(FormConstant.NCKD_PERSON);
                    TypeStateEnum typeStateEnum = TypeStateEnum.getByCode(typeState);

                    if (TypeStateEnum.ANNUAL_ADJUSTMENT.getCode().equalsIgnoreCase(typeState)) {
                        if (EnableEnum.YES.getCode().equals(adjustStatus)) {
                            addFatalErrorMessage(rowDataEntity, StrFormatter.format("【{}】的{}已“生效”，不能删除。请先“置回未生效”状态。", person.getString("name"), typeStateEnum.getName()));
                        }else{
                            idMaps.put(id,rowDataEntity.getDataEntityIndex());
                        }
                    }else if(StringUtils.equalsAny(typeState, TypeStateEnum.NEW_ENTRY.getCode(), TypeStateEnum.IN_SERVICE_LEVEL.getCode())){
                        idMaps.put(id,rowDataEntity.getDataEntityIndex());
                    }else if (TypeStateEnum.POSITION_TRANSFER.getCode().equalsIgnoreCase(typeState)) {
                        idMaps.put(id,rowDataEntity.getDataEntityIndex());
                    }else if(typeStateEnum == TypeStateEnum.MANAGEMENT_SEQUENCE_EMPLOYMENT){

                    }else if(typeStateEnum == TypeStateEnum.HIGH_PROFESSIONAL_EMPLOYMENT){
                        String employmentStatus = data.getString(PositionStructureConstant.NCKD_EMPLOYMENTSTATUS);
                        if(EnableEnum.YES.getCode().equalsIgnoreCase(employmentStatus)){
                            this.addFatalErrorMessage(rowDataEntity, StrFormatter.format("【{}】已“聘任”，不能删除", person.getString("name")));
                        }
                    }
                    else {
                        //其他类型不能置回未生效
                        addFatalErrorMessage(rowDataEntity, StrFormatter.format("【{}】不能删除", typeStateEnum.getName()));
                    }

                }
                if(!idMaps.isEmpty()){
                    //校验是否已被使用
                    QFilter qFilter = new QFilter(PositionStructureConstant.NCKD_DISABLE, QCP.equals, EnableEnum.NO.getCode())
                            .and(new QFilter(String.join(".", PositionStructureConstant.NCKD_LASTPERSONPOSFILE, FormConstant.ID_KEY), QCP.in, idMaps.keySet()));
                    QueryFieldBuilder queryFieldBuilder = QueryFieldBuilder.create()
                            .add(PositionStructureConstant.ID_KEY)
                            .addGroup(new String[]{FormConstant.NCKD_PERSON}, FormConstant.NAME_KEY)
                            .addGroup(new String[]{PositionStructureConstant.NCKD_LASTPERSONPOSFILE}, FormConstant.ID_KEY,PositionStructureConstant.NCKD_TYPESTATE)
                            .add(PositionStructureConstant.NCKD_EXECUTEYEAR)
                            .add(PositionStructureConstant.NCKD_TYPESTATE)
                            .orderDesc(PositionStructureConstant.NCKD_EXECUTEYEAR);
                    DynamicObjectCollection query = QueryServiceHelper.query(PositionStructureConstant.PERSONPOSFILE_ENTITYID, queryFieldBuilder.buildSelect(), new QFilter[]{qFilter},queryFieldBuilder.buildOrder());
                    if(!query.isEmpty()){
                        for (DynamicObject dynamicObject : query) {
                            long id = dynamicObject.getLong(String.join(".", PositionStructureConstant.NCKD_LASTPERSONPOSFILE, FormConstant.ID_KEY));
                            String executeYear = dynamicObject.getString(PositionStructureConstant.NCKD_EXECUTEYEAR);
                            String typeState = dynamicObject.getString(PositionStructureConstant.NCKD_TYPESTATE);
                            TypeStateEnum typeStateEnum = TypeStateEnum.getByCode(typeState);
                            String personName = dynamicObject.getString(String.join(".", FormConstant.NCKD_PERSON, FormConstant.NAME_KEY));
                            addFatalErrorMessage(getDataEntities()[idMaps.get(id)], StrFormatter.format("【{}】的档案已被【{}】年度的【{}】档案使用，不能删除",personName, executeYear,typeStateEnum.getName()));
                        }
                    }
                }
                //TODO 【待修改】-职位体系-校验有没有被下游使用（例如：薪酬）

                //所有情况校验完再校验是否被锁定，比较友好。不然先校验锁等用户解锁之后又发现其他情况而不能继续处理
                if(this.getValidateResult().isSuccess()) {
                    for (ExtendedDataEntity rowDataEntity : getDataEntities()) {
                        DynamicObject data = rowDataEntity.getDataEntity();
                        String typeState = data.getString(PositionStructureConstant.NCKD_TYPESTATE);
                        DynamicObject person = data.getDynamicObject(FormConstant.NCKD_PERSON);
                        TypeStateEnum typeStateEnum = TypeStateEnum.getByCode(typeState);
                        boolean lockStatus = data.getBoolean(PositionStructureConstant.NCKD_LOCKSTATUS);
                        if (lockStatus) {
                            addFatalErrorMessage(rowDataEntity, StrFormatter.format("【{}】的{}已“锁定”，不能删除。请先“解锁”。", person.getString("name"), typeStateEnum.getName()));
                        }
                    }
                }
            }
        });
    }

    @Override
    public void beginOperationTransaction(BeginOperationTransactionArgs e) {
        Long[] personIds = new Long[e.getDataEntities().length];
        Long[] ids = new Long[e.getDataEntities().length];
        for (int i = 0; i < e.getDataEntities().length; i++) {
            DynamicObject dataEntity = e.getDataEntities()[i];
            long id = dataEntity.getLong(FormConstant.ID_KEY);
            ids[i] = id;
            DynamicObject person = dataEntity.getDynamicObject(FormConstant.NCKD_PERSON);
            personIds[i] = person.getLong(FormConstant.ID_KEY);
        }
        //将人员所有职位档案标记为非最新
        PositionFileHelper.markAsNotCurrentNewest(personIds);
        //将当前人员最新档案（初定 或者 （年度调整 并且 已生效） 或者 (动态调整) 生效时间为最新的那一条）标记为最新的
        PositionFileHelper.markAsCurrentNewest(new QFilter(FormConstant.ID_KEY, QCP.not_in,ids),personIds);

        //失效职位津贴
        ManagerAllowanceService.expireMgrPostAllow(Arrays.asList(e.getDataEntities()));
    }
}