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


import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.BeginOperationTransactionArgs;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

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

/**
 *
 * @author Tyx
 * @date  2025/5/8
 * 年度招聘计划操作插件
 *
 */
public class YearCrApplyPlanOperatePlugin extends AbstractOperationServicePlugIn {



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

    public void beginOperationTransaction(BeginOperationTransactionArgs args) {
        super.beginOperationTransaction(args);
        DynamicObject[] regBillObjs = args.getDataEntities();

        switch (args.getOperationKey()) {
            case "wfauditnotpass":
            case "delete":
                // 审批不通过,删除

                updateYearcrapplyPlan(regBillObjs, "A");
                break;
            case "wfauditpass":
                // 审批通过
            case "audit":
                // 审批
                updateYearcrapplyPlan(regBillObjs, "C");
                updatePersonNum(regBillObjs);
                break;
            case "unsubmit":
                // 校验是否存在下级单据
                String errorMsg = validateYearcrapplyPlan(regBillObjs);
                if(StringUtils.isNoneBlank(errorMsg)){

                }


                updateYearcrapplyPlan(regBillObjs, "B");
                break;
                // 反审批
            case "save":
                // 保存
                updateYearcrapplyPlan(regBillObjs, "B");
                break;
            default:
                break;
        }

    }

    private String validateYearcrapplyPlan(DynamicObject[] yearcrapplyPlanObj){

        return null;
    }


    // 更新年度招聘申请核定人数
    private void updatePersonNum(DynamicObject[] yearcrapplyPlanObjs){
        List<DynamicObject> yearcrapplyPlanObjsList = new ArrayList<>();
        Set<Long> yearcrapplyPlanIds = new HashSet<>();
        for (DynamicObject yearcrapplyPlanObj : yearcrapplyPlanObjs) {
            DynamicObjectCollection entryentity = yearcrapplyPlanObj.getDynamicObjectCollection("entryentity");
            for (DynamicObject dynamicObject : entryentity) {
                yearcrapplyPlanObjsList.add(dynamicObject);
                yearcrapplyPlanIds.add(dynamicObject.getLong("nckd_yearapplyid"));
            }
        }
        Map<Object, DynamicObject> resultMap = yearcrapplyPlanObjsList.stream()
                .collect(Collectors.toMap(
                        obj -> obj.get("nckd_yearapplyentryid"), // 获取key
                        obj -> obj // 获取value
                ));

        QFilter qFilter = new QFilter("id", QCP.in, yearcrapplyPlanIds);
        DynamicObject[] nckdYearapplies = BusinessDataServiceHelper.load("nckd_yearapply", "id,entryentity,entryentity.nckd_summary,entryentity.nckd_approvednum", new QFilter[]{qFilter});
        for (DynamicObject nckdYearapply : nckdYearapplies) {
            DynamicObjectCollection entryentity = nckdYearapply.getDynamicObjectCollection("entryentity");
            for (DynamicObject dynamicObject : entryentity) {
                DynamicObject dynamicObjectentry = resultMap.get(dynamicObject.getPkValue());
                if(ObjectUtils.isNotEmpty(dynamicObjectentry)){
                    dynamicObject.set("nckd_approvednum", dynamicObjectentry.get("nckd_approvednum"));
                }
            }
        }
        if(nckdYearapplies.length>0){
            SaveServiceHelper.save(nckdYearapplies);
        }
    }

    private void updateYearcrapplyPlan(DynamicObject[] yearcrapplyPlanObjs, String status) {
        //  获取单据单内 年度招聘申请id和申请分录id

        for (DynamicObject yearcrapplyPlanObj : yearcrapplyPlanObjs) {
            Set<Long> yearcrapplyPlanIds = new HashSet<>();
            Set<Long> yearcrapplyPlanEntryIds = new HashSet<>();
            DynamicObjectCollection entryentity = yearcrapplyPlanObj.getDynamicObjectCollection("entryentity");
            for (DynamicObject entry : entryentity) {
                yearcrapplyPlanEntryIds.add(entry.getLong("nckd_yearapplyentryid"));
                yearcrapplyPlanIds.add(entry.getLong("nckd_yearapplyid"));
            }

            List<Long> yearcrapplyPlanEntryIdsList = new ArrayList<>(yearcrapplyPlanEntryIds);
            List<Long> yearcrapplyPlanIdsList = new ArrayList<>(yearcrapplyPlanIds);
            QFilter qFilter = new QFilter("id", QCP.in, yearcrapplyPlanIdsList);
            QFilter qFilter1 = new QFilter("entryentity.id", QCP.in, yearcrapplyPlanEntryIdsList);

            DynamicObject[] loads = BusinessDataServiceHelper.load("nckd_yearapply","id,nckd_summarstatus,entryentity,entryentity.id,entryentity.,entryentity.nckd_summary,entryentity.nckd_casreplanid",new QFilter[]{qFilter,qFilter1});
            for (DynamicObject load : loads) {
                load.set("nckd_summarstatus", status);
                DynamicObjectCollection entryentity1 = load.getDynamicObjectCollection("entryentity");
                for (DynamicObject dynamicObject : entryentity1) {
                    if(yearcrapplyPlanEntryIdsList.contains(dynamicObject.getLong("id"))){
                        dynamicObject.set("nckd_summary", status);
                        if(status.equals("A")){
                            dynamicObject.set("nckd_casreplanid", null);
                        }else{
                            dynamicObject.set("nckd_casreplanid", yearcrapplyPlanObj.getPkValue());
                        }
                    }
                }
            }
            SaveServiceHelper.save(loads);
        }
    }
}
