package nckd.jxccl.swc.stm.plugin.operate.unitst;

import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.metadata.IDataEntityProperty;
import kd.bos.dataentity.metadata.clr.DataEntityPropertyCollection;
import kd.bos.dataentity.utils.ObjectUtils;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.BeginOperationTransactionArgs;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.MetadataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.exception.ValidationException;
import nckd.jxccl.base.common.utils.StrFormatter;
import nckd.jxccl.swc.constants.StmConstant;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
* 回写单位工资总额-保存
* 实体标识：nckd_unitstbudgetadjust
* @author W.Y.C
* @date 2025/12/11 15:38
* @version 1.0
*/
public class BackUnitStBudgetOpPlugin extends AbstractOperationServicePlugIn implements Plugin {

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        e.getFieldKeys().addAll(this.billEntityType.getAllFields().keySet());
    }

    @Override
    public void beginOperationTransaction(BeginOperationTransactionArgs e) {
        MainEntityType billEntityType = this.billEntityType;
        if(billEntityType.getName().equalsIgnoreCase(StmConstant.UNITSTBUDGETADJUST_ENTITYID)) {
            List<Long> unitStBudgetApplyIds = new ArrayList<>();
            for (DynamicObject dataEntity : e.getDataEntities()) {
                DynamicObject unitStBudgetApply = dataEntity.getDynamicObject(StmConstant.UNITSTBUDGETAPPLY_ENTITYID);
                unitStBudgetApplyIds.add(unitStBudgetApply.getLong(FormConstant.ID_KEY));
            }
            Map<Long, DynamicObject> unitStBudgetApplyMap = new HashMap<>(unitStBudgetApplyIds.size());
            if (!unitStBudgetApplyIds.isEmpty()) {
                MainEntityType dataEntityType = MetadataServiceHelper.getDataEntityType(StmConstant.UNITSTBUDGETAPPLY_ENTITYID);
                DynamicObject[] load = BusinessDataServiceHelper.load(unitStBudgetApplyIds.toArray(new Long[0]), dataEntityType);
                unitStBudgetApplyMap = Arrays.stream(load)
                        .collect(Collectors.toMap(
                                obj -> obj.getLong(FormConstant.ID_KEY),
                                obj -> obj
                        ));
            }

            List<DynamicObject> saveUnitStBudgetApply = new ArrayList<>(unitStBudgetApplyIds.size());
            for (DynamicObject dataEntity : e.getDataEntities()) {
                DynamicObject unitStBudgetApply = dataEntity.getDynamicObject(StmConstant.UNITSTBUDGETAPPLY_ENTITYID);
                DynamicObject dbUnitStBudgetApply = unitStBudgetApplyMap.get(unitStBudgetApply.getLong(FormConstant.ID_KEY));
                DataEntityPropertyCollection properties = dataEntity.getDataEntityType().getProperties();
                for (IDataEntityProperty property : properties) {
                    String name = property.getName();
                    if (name.startsWith("nckd_")
                            && !name.endsWith("ls")
                            && !name.contains("nckd_year")
                            && !name.contains("nckd_payunit")
                            && !name.contains("nckd_unitstbudgetapply")) {
                        dbUnitStBudgetApply.set(name, dataEntity.get(name));
                    }
                }
                saveUnitStBudgetApply.add(dbUnitStBudgetApply);
            }

            //调用“单位工资总额预算申报”保存
            OperateOption option = OperateOption.create();
            //修改和删除不校验是否是暂存状态（只能修改暂存的数据。只能删除暂存的数据。）
            option.setVariableValue("forceNoAudit", "true");
            // 执行保存操作
            OperationResult saveResult = SaveServiceHelper.saveOperate(StmConstant.UNITSTBUDGETAPPLY_ENTITYID, saveUnitStBudgetApply.toArray(new DynamicObject[0]), option);
            if (saveResult != null && !saveResult.isSuccess()) {
                StringJoiner errorMsg = new StringJoiner("；");
                for (IOperateInfo error : saveResult.getAllErrorOrValidateInfo()) {
                    errorMsg.add(error.getMessage());
                }
                if (!ObjectUtils.isEmpty(saveResult.getMessage())) {
                    errorMsg.add(saveResult.getMessage());
                }
                throw new ValidationException(StrFormatter.format("回写【{}】失败，原因：{}", "单位工资总额预算申报", errorMsg.toString()));
            }
        }
    }
}