package nckd.jxccl.hrmp.hbpm.plugin.operate.hr;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.constant.StatusEnum;
import kd.bos.entity.operate.OperateOptionConst;
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.args.BeginOperationTransactionArgs;
import kd.bos.exception.KDBizException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.service.operation.OperationServiceImpl;
import kd.bos.servicehelper.coderule.CodeRuleServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import kd.hr.hbp.common.constants.history.HisModelDataStatusEnum;
import kd.hr.hbp.common.util.HRStringUtils;
import nckd.jxccl.hrmp.hbpm.business.hr.service.impl.PositionBillServiceHelper;
import nckd.jxccl.hrmp.hbpm.common.hr.PositionBillConstant;

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

/**
 * 岗位申请-新增岗位保存操作插件
 * @entity: nckd_posbillentryadd
 * @from: kd.hr.homs.opplugin.web.orgbatch.OrgBatchChgBillNewOrgTempSaveOp
 * @author: jtd
 * @date: 2025-11-08 15:30
 */
public class PosBillEntryNewPositionTempSaveOpPlugin extends AbstractOperationServicePlugIn {

    @Override
    public void beginOperationTransaction(BeginOperationTransactionArgs e) {
        super.beginOperationTransaction(e);

        DynamicObject[] positionEntities = e.getDataEntities();
        if (positionEntities.length == 0) {
            return;
        }

        // 获取岗位和上级岗位的业务ID
        List<Long> positionBoIds = Lists.newArrayListWithExpectedSize(positionEntities.length);
        // 获取 行政组织业务ID
        List<Long> adminorgBoIds = Lists.newArrayListWithExpectedSize(positionEntities.length);
        // 岗位ID标识
        String positionIdKey = String.join("_", PositionBillConstant.NCKD_POSITION_KEY, PositionBillConstant.ID_KEY);
        for (DynamicObject positionEntity : positionEntities) {
            positionBoIds.add(positionEntity.getLong(positionIdKey));
            adminorgBoIds.add(positionEntity.getLong(PositionBillConstant.NCKD_ADMINORGBOID_KEY));
            // 获取上级岗位
            DynamicObject parentPositionVersionDy = positionEntity.getDynamicObject(PositionBillConstant.NCKD_PARENT);
            if (parentPositionVersionDy != null) {
                long parentOrgBoId = parentPositionVersionDy.getLong(PositionBillConstant.BOID_KEY);
                positionBoIds.add(parentOrgBoId);
            }
        }

        // 根据岗位ID从数据库中获取岗位信息
        HRBaseServiceHelper positionServiceHelper = HRBaseServiceHelper.create(PositionBillConstant.HBPM_POSITIONHR);
        DynamicObject[] positionDyos = positionServiceHelper.loadDynamicObjectArray(new QFilter[]{new QFilter(PositionBillConstant.ID_KEY, QCP.in, positionBoIds)});
        Map<Long, DynamicObject> dbPositionMap = Maps.newHashMapWithExpectedSize(positionDyos.length);
        for (DynamicObject positionDyo : positionDyos) {
            dbPositionMap.put(positionDyo.getLong(PositionBillConstant.ID_KEY), positionDyo);
        }
        // 根据组织BOID从数据库中获取组织信息
        DynamicObject[] adminOrgDyos = HRBaseServiceHelper.create(PositionBillConstant.ADMINORG_ENTITYID).loadDynamicObjectArray(new QFilter[]{new QFilter(PositionBillConstant.ID_KEY, QCP.in, adminorgBoIds)});
        Map<Long, DynamicObject> dbAdminOrgMap = Maps.newHashMapWithExpectedSize(adminOrgDyos.length);
        for (DynamicObject adminOrgDyo : adminOrgDyos) {
            dbAdminOrgMap.put(adminOrgDyo.getLong(PositionBillConstant.BOID_KEY), adminOrgDyo);
        }
        // 构建岗位对象
        OperateOption operateOption = OperateOption.create();
        List<DynamicObject> positionList = Lists.newArrayListWithExpectedSize(positionEntities.length);
        // 获取岗位要转换的键值
        Map<String, String> positionTransKeyMap = PositionBillServiceHelper.getPositionTransKeyMap();

        for (DynamicObject positionEntity : positionEntities) {
            long positionId = positionEntity.getLong(positionIdKey);
            // 如果数据库存在则用数据库的岗位对象
            DynamicObject positionDyo = dbPositionMap.get(positionId);
            // 不存在则创建一个
            if (positionDyo == null) {
                positionDyo = positionServiceHelper.generateEmptyDynamicObject();
            }
            // 将表单中的信息赋值到岗位信息中
            PositionBillServiceHelper.getPositionHrDy(positionEntity, positionDyo, positionTransKeyMap);// 调用保存会自动设置status、enable、datastatus
            // 设置ID为岗位ID
            positionDyo.set(PositionBillConstant.ID_KEY, positionId);
            // 设置 是否标准岗位
            positionDyo.set(PositionBillConstant.ISSTANDARDPOS_KEY, "9");// 暂存的数据固定为9，由于标品岗位一定会生成历史版本数据，所以为了能够正常的多次保存且不显示在岗位中需要这样做
            // 设置 行政组织
            positionDyo.set(PositionBillConstant.ADMINORG, dbAdminOrgMap.get(positionEntity.getLong(PositionBillConstant.NCKD_ADMINORGBOID_KEY)));
            // 设置 上级岗位
            DynamicObject parentPositionVersionDy = positionEntity.getDynamicObject(PositionBillConstant.NCKD_PARENT);
            if (parentPositionVersionDy != null) {
                positionDyo.set(PositionBillConstant.PARENT_KEY, dbPositionMap.get(parentPositionVersionDy.getLong(PositionBillConstant.BOID_KEY)));
            } else {
                positionDyo.set(PositionBillConstant.PARENT_KEY, null);
            }
            positionList.add(positionDyo);
            String number = positionDyo.getString(PositionBillConstant.NUMBER_KEY);
            // 设置 编码为已变更
            if (HRStringUtils.isNotEmpty(number)) {
                operateOption.setVariableValue(positionId + "coderule_billno_from_initAbstractCodeRule", "coderule_billno_from_init_value_of_operation");
            }
        }
        // 设置岗位临时新增标识
        //operateOption.setVariableValue("OP_ADD_POSITION_TEMP_TAG", Boolean.TRUE.toString());
        // 跳过功能权限校验
        operateOption.setVariableValue(OperateOptionConst.ISHASRIGHT, Boolean.TRUE.toString());
        // 跳过数据权限校验
        operateOption.setVariableValue(OperateOptionConst.SKIPCHECKPERMISSION, Boolean.TRUE.toString());
        List<String> errorMsgList = Lists.newArrayList();
        List successPkIds = Lists.newArrayList();
        for (int index = 0; index < positionList.size(); ++index) {
            DynamicObject positionDyo = positionList.get(index);
            String orgId = "";
            // 设置编码
            if (HRStringUtils.isBlank(positionDyo.getString(PositionBillConstant.NUMBER_KEY))) {
                orgId = String.valueOf(positionDyo.getLong(String.join("_", PositionBillConstant.ORG_KEY, PositionBillConstant.ID_KEY)));
                String positionNumber = CodeRuleServiceHelper.getNumber(PositionBillConstant.HBPM_POSITIONHR, positionDyo, orgId);
                positionDyo.set(PositionBillConstant.NUMBER_KEY, positionNumber);
            }
            // 保存
            OperationServiceImpl opImpl = new OperationServiceImpl();
            OperationResult saveResult = opImpl.localInvokeOperation(PositionBillConstant.SAVE_OP, new DynamicObject[]{positionDyo}, operateOption);
            if (!saveResult.isSuccess()) {
                // 回收编码
                if (HRStringUtils.isNotBlank(orgId)) {
                    CodeRuleServiceHelper.recycleNumber(PositionBillConstant.HBPM_POSITIONHR, positionDyo, orgId, positionDyo.getString(PositionBillConstant.NUMBER_KEY));
                }

                for(IOperateInfo operateInfo : saveResult.getAllErrorOrValidateInfo()) {
                    errorMsgList.add(operateInfo.getMessage());
                }
            } else {
                successPkIds.addAll(saveResult.getSuccessPkIds());
                DynamicObject[] dbPositionEntityDys = positionServiceHelper.loadDynamicObjectArray(new QFilter[]{new QFilter(PositionBillConstant.ID_KEY, QCP.in, saveResult.getSuccessPkIds())});
                DynamicObject dbPositionEntityDy = dbPositionEntityDys[0];
                DynamicObject positionEntity = positionEntities[index];
                positionEntity.set(positionIdKey, dbPositionEntityDy.get(PositionBillConstant.ID_KEY));
                positionEntity.set(PositionBillConstant.NUMBER_KEY, dbPositionEntityDy.getString(PositionBillConstant.NUMBER_KEY));
            }
        }

        // 不论成功与否，都调用岗位删除，BOS岗位不需要暂存数据
        List<Long> positionIds = positionList.stream().map(positionDy -> positionDy.getLong(PositionBillConstant.ID_KEY)).collect(Collectors.toList());
        PositionBillServiceHelper.delAddMasterForBos(positionIds);

        if (!errorMsgList.isEmpty()) {
            throw new KDBizException(String.join(System.lineSeparator(), errorMsgList));
        } else {
            // 由于标品会强制设置值，所以需要后置更新
            //updatePositionStatus(successPkIds);
        }
    }

    /**
     * 更新岗位信息的状态
     * @param successPkIds
     */
    private void updatePositionStatus(List successPkIds) {
        HRBaseServiceHelper positionServiceHelper = HRBaseServiceHelper.create(PositionBillConstant.HBPM_POSITIONHR);
        DynamicObject[] positionDys = positionServiceHelper.loadDynamicObjectArray(new QFilter[]{new QFilter(PositionBillConstant.BOID_KEY, QCP.in, successPkIds)});
        for (DynamicObject positionDy : positionDys) {
            positionDy.set(PositionBillConstant.STATUS, StatusEnum.A);
            positionDy.set(PositionBillConstant.DATA_STATUS, HisModelDataStatusEnum.TEMP.getStatus());
        }
        SaveServiceHelper.save(positionDys);
    }

}
