package nckd.jimin.jyyy.hr.tsrsc.plugin.operate;

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.validate.AbstractValidator;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;

import java.util.List;
import java.util.stream.Collectors;

/**
 * description: 年度招聘计划校验插件，反审核校验器
 * nckd_yearapply
 * @author Tyx
 * @date  2025/5/8
 */

public class CasRecrApplyUnAuditValidator extends AbstractOperationServicePlugIn {

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        // 提前加载表单里的字段
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.addAll(this.billEntityType.getAllFields().keySet());
    }

    @Override
    public void onAddValidators(AddValidatorsEventArgs e) {
        super.onAddValidators(e);
        e.addValidator(new AbstractValidator() {
            @Override
            public void validate() {
                ExtendedDataEntity[] dataEntities = this.getDataEntities();

                for (ExtendedDataEntity dataEntity : dataEntities) {
                    DynamicObject dynamicObject = dataEntity.getDataEntity();
                    DynamicObjectCollection entryentity = dynamicObject.getDynamicObjectCollection("entryentity");
                    if(entryentity.size() > 0){
                        List<String> objectList = entryentity.stream()
                                .map(entry -> {
                                    return String.valueOf(entry.getPkValue());
                                })
                                .collect(Collectors.toList());
                        DynamicObject[] load = BusinessDataServiceHelper.load("tstpm_srscarfmrsm", "id", (new QFilter("nckd_mokahcnum", QCP.in, objectList)).toArray());
                        if(load.length > 0){
                            this.addErrorMessage(dataEntity, "已存在候选人信息，不允许反审核！");
                            break;
                        }
                    }
                }
            }
        });
    }
}
