package nckd.jimin.jyyy.hr.swc.hcdm.formplugin.validator;

import com.google.common.collect.Lists;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.entity.ExtendedDataEntity;
import kd.bos.entity.validate.AbstractValidator;
import kd.bos.orm.query.QFilter;
import kd.hr.hbp.common.util.HRArrayUtils;
import kd.hr.hbp.common.util.HRCollUtil;
import kd.hr.hbp.common.util.HRMapUtils;
import kd.hr.hbp.common.util.HRStringUtils;
import kd.hr.hbp.opplugin.validator.HRDataBaseValidator;
import kd.tdc.tjga.business.domain.repository.BatchChangeJobRepository;
import kd.tdc.tjga.business.domain.repository.TalentFileRepository;
import kd.tdc.tjga.business.formservice.BatchChangeGradeLevelFormService;
import kd.tdc.tjga.common.util.CommUtils;

import java.util.*;
import java.util.stream.Collectors;

public class AdjustJobBillSaveValidator extends HRDataBaseValidator {
    @Override
    public void validate() {
        super.validate();
        ExtendedDataEntity[] dataEntities = this.getDataEntities();
        if (!HRArrayUtils.isEmpty(dataEntities)) {
            DynamicObject dataEntity = dataEntities[0].getDataEntity();
            DynamicObjectCollection entryObjs = dataEntity.getDynamicObjectCollection("changeentry");
            if (!HRCollUtil.isEmpty(entryObjs)) {
                BatchChangeGradeLevelFormService fromService = new BatchChangeGradeLevelFormService();
                String dimissionName = fromService.empDimission(entryObjs);
                String billStatus;
                if (HRStringUtils.isNotEmpty(dimissionName)) {
                    billStatus = ResManager.loadKDString("员工“{0}”已经离职，无法继续调整职级职等。", "BatchChangeGradeLevelSaveValidator_0", "tdc-tjga-opplugin", new Object[]{dimissionName});
                    this.addErrorMessage(dataEntities[0], billStatus);
                } else {
                    billStatus = dataEntity.getString("billstatus");
                    String billno = HRStringUtils.isEmpty(billStatus) ? null : dataEntity.getString("billno");
                    String errorMsg = this.isInProcessing(entryObjs, billno);
                    if (HRStringUtils.isNotEmpty(errorMsg)) {
                        this.addErrorMessage(dataEntities[0], errorMsg);
                    } else {
                        String nameNumStr = fromService.gradeAndLevelBothEmpty(entryObjs);
                        String nameNumSameStr;
                        if (HRStringUtils.isNotEmpty(nameNumStr)) {
                            nameNumSameStr = ResManager.loadKDString("员工“{0}”调整后的职级和职等不能同时为空。", "BatchChangeGradeLevelSaveValidator_1", "tdc-tjga-opplugin", new Object[]{nameNumStr});
                            this.addErrorMessage(dataEntities[0], nameNumSameStr);
                        } else {
                            nameNumSameStr = fromService.sameValue(entryObjs);
                            if (HRStringUtils.isNotEmpty(nameNumSameStr)) {
                                String sameStr = ResManager.loadKDString("员工“{0}”调整前后的职级职等信息没有变化，请重新确认。", "BatchChangeGradeLevelSaveValidator_2", "tdc-tjga-opplugin", new Object[]{nameNumSameStr});
                                this.addErrorMessage(dataEntities[0], sameStr);
                            }
                        }
                    }
                }
            }
        }
    }

    public String isInProcessing(DynamicObjectCollection entryObj, String billno) {
        List<Long> talentFiles = (List)entryObj.stream().map((obj) -> {
            return obj.getLong("employee.id");
        }).collect(Collectors.toList());
        Map<Long, String> allErrorMsgMap = this.getProcessingDataErrorMsg(talentFiles, billno);
        if (HRMapUtils.isEmpty(allErrorMsgMap)) {
            return "";
        } else {
            Iterator var5 = entryObj.iterator();

            String errorMsg;
            do {
                if (!var5.hasNext()) {
                    return "";
                }

                DynamicObject row = (DynamicObject)var5.next();
                errorMsg = (String)allErrorMsgMap.get(row.getLong("employee.id"));
            } while(!HRStringUtils.isNotEmpty(errorMsg));

            return errorMsg;
        }
    }

    public Map<Long, String> getProcessingDataErrorMsg(Collection<Long> talentFileIds, String billno) {
        Map<Long, String> resultMap = new HashMap();
        Map<Long, String> batchChangeMap = this.batchChangeJob(talentFileIds, billno);
        String inBatchProcssingErrMsg = ResManager.loadKDString("{0}：员工已处于批量职级职等调整流程中，单据编码为{1}，请重新选择。", "BatchChangeGradeLevelFromService_2", "tdc-tjga-business", new Object[0]);
        resultMap.putAll(this.appendErrorMsg(batchChangeMap, inBatchProcssingErrMsg));
        return resultMap;
    }

    public Map<Long, String> batchChangeJob(Collection<Long> talentFileIds, String billno) {
        QFilter status = new QFilter("billstatus", "not in", "");
        QFilter talentFile = new QFilter("changeentry.employee.id", "in", talentFileIds);
        QFilter changeStatus = new QFilter("changeentry.changestatus", "=", "0");
        List<QFilter> filters = Lists.newArrayList(new QFilter[]{status, talentFile, changeStatus});
        if (HRStringUtils.isNotEmpty(billno)) {
            filters.add(new QFilter("billno", "not in", billno));
        }

        Set<Long> talentFileSet = (Set)talentFileIds.stream().collect(Collectors.toSet());
        List<DynamicObject> entryObjs = this.batchJobEntry((QFilter[])filters.toArray(new QFilter[0]), talentFileSet);
        return (Map)(HRCollUtil.isEmpty(entryObjs) ? new HashMap() : (Map)entryObjs.stream().collect(Collectors.toMap((k) -> {
            return k.getLong("employee.id");
        }, (v) -> {
            return v.getString("billnoentry");
        }, (k1, k2) -> {
            return k1;
        })));
    }

    public List<DynamicObject> batchJobEntry(QFilter[] filters, Set<Long> talentFileSet) {
        DynamicObject[] dynamicObjects = BatchChangeJobRepository.queryBatchJob((String)null, filters);
        if (HRArrayUtils.isEmpty(dynamicObjects)) {
            return null;
        } else {
            List<DynamicObject> allEntryObj = new ArrayList(16);
            Arrays.stream(dynamicObjects).forEach((d) -> {
                String billno = d.getString("billno");
                DynamicObjectCollection dynamicObjectCollection = d.getDynamicObjectCollection("changeentry");
                if (HRCollUtil.isNotEmpty(dynamicObjectCollection)) {
                    List<DynamicObject> collect = (List)dynamicObjectCollection.stream().filter((row) -> {
                        return talentFileSet.contains(row.getLong("employee.id"));
                    }).peek((row) -> {
                        row.set("billnoentry", billno);
                    }).collect(Collectors.toList());
                    allEntryObj.addAll(collect);
                }

            });
            return allEntryObj;
        }
    }


    public Map<Long, String> appendErrorMsg(Map<Long, String> map, String errorMsg) {
        Map<Long, String> errorMsgMap = new HashMap(16);
        if (!HRMapUtils.isEmpty(map)) {
            Map<Long, String> nameAndNumberMap = this.queryTalentFile(map.keySet());
            Iterator var5 = map.entrySet().iterator();

            while(var5.hasNext()) {
                Map.Entry<Long, String> entry = (Map.Entry)var5.next();
                String nameAndNumber = (String)nameAndNumberMap.get(entry.getKey());
                if (HRStringUtils.isNotEmpty(nameAndNumber)) {
                    errorMsgMap.put(entry.getKey(), errorMsg.replace("{0}", nameAndNumber).replace("{1}", (CharSequence)entry.getValue()));
                }
            }
        }

        return errorMsgMap;
    }

    private Map<Long, String> queryTalentFile(Collection<Long> talentFileIds) {
        DynamicObject[] talentFileObjs = (new TalentFileRepository()).queryTalentFileInfoById(talentFileIds, "name,number");
        return (Map)(HRArrayUtils.isEmpty(talentFileObjs) ? new HashMap() : (Map) Arrays.stream(talentFileObjs).collect(Collectors.toMap((k) -> {
            return k.getLong("id");
        }, (v) -> {
            return CommUtils.appendStr(new String[]{v.getString("name"), " ", v.getString("number")});
        }, (k1, k2) -> {
            return k1;
        })));
    }


}
