package nckd.jxccl.swc.init.plugin.operate;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.args.AfterOperationArgs;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;

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

/**
 * 定调薪清单回写 删除与审核时，回写状态，定调薪申请单ID
 * @author: turborao
 * @date: 2025/12/5 9:05
 */
public class ApplyBillBackPendSalaryAdjOpPlugin extends AbstractOperationServicePlugIn implements Plugin {

    /**
     * 员工待定调薪清单
     */
    private static final String SelectFields = "id,billno,billstatus,nckd_applybillid";

    @Override
    public void afterExecuteOperationTransaction(AfterOperationArgs e) {
        super.afterExecuteOperationTransaction(e);
        switch (e.getOperationKey()) {
            case "submiteffect":
                this.writeBackPendSalaryAdj(e, e.getOperationKey());
                break;
            case "delete":
                this.writeBackPendSalaryAdj(e, e.getOperationKey());
                break;
        }
    }

    /**
     * 定调薪清单回写 删除与审核时，回写状态，定调薪申请单ID
     * @param e
     * @param operationKey
     */
    public void writeBackPendSalaryAdj(AfterOperationArgs e, String operationKey) {
        DynamicObject[] dataEntities = e.getDataEntities();

        Map<Long, DynamicObject> billMap =
                Arrays.stream(dataEntities)
                        .collect(Collectors.toMap(
                                detail -> detail.getLong("id"),
                                detail -> detail, // 整个 DynamicObject 作为 value
                                (existing, replacement) -> existing // 保留前面的值
                        ));
        List<Long> billIDs = billMap.keySet().stream().collect(Collectors.toList());

        QFilter qFilter = new QFilter("nckd_applybillid", QCP.in, billIDs);
        DynamicObject[] pendSalaryAdjDyns = BusinessDataServiceHelper.load(FormConstant.NCKD_PENDINGSALARYADJ,SelectFields, new QFilter[]{qFilter});
        for (DynamicObject pendSalaryAdjDyn : pendSalaryAdjDyns) {
            if(operationKey.equals("delete")) {
                pendSalaryAdjDyn.set("nckd_applybillid", 0L);  ///更新为 0
                pendSalaryAdjDyn.set("billstatus", "A");  ///更新为 暂存状态
            }
            if(operationKey.equals("submiteffect")) {
                pendSalaryAdjDyn.set("billstatus", "C");  ///更新为 已处理 状态
            }
        }
        if(pendSalaryAdjDyns != null && pendSalaryAdjDyns.length > 0) {
            SaveServiceHelper.save(pendSalaryAdjDyns);
        }

    }


}