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

import kd.bos.dataentity.entity.DynamicObject;
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.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.utils.StrFormatter;
import nckd.jxccl.opmc.pm.common.PerfManagerFormConstant;
import nckd.jxccl.opmc.pm.helper.PerfManagerHelper;

import java.util.ArrayList;
import java.util.List;

/**
* 考核周期删除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(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() {
                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) ? "已锁定":"已结束"));
                    }
                }
            }
        });
    }

    @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));
    }
}