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

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import kd.bos.common.enums.EnableEnum;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.IDataEntityProperty;
import kd.bos.dataentity.metadata.clr.DataEntityPropertyCollection;
import kd.bos.entity.EntityMetadataCache;
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.AddValidatorsEventArgs;
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.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.hr.hbp.common.util.HRDynamicObjectUtils;
import kd.hr.hbp.common.util.HRStringUtils;
import nckd.jxccl.hrmp.hbpm.common.hr.PositionBillConstant;
import nckd.jxccl.hrmp.hbpm.plugin.operate.hr.validator.PositionBillEntryValidator;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 岗位申请-新增岗位保存OP
 * @author: jtd
 * @date: 2025-11-08 15:30
 */
public class PosBillEntryAddSaveOpPlugin extends AbstractOperationServicePlugIn {

    private static final String FIELD_PREFIX = "nckd_";

    @Override
    public void onAddValidators(AddValidatorsEventArgs e) {
        super.onAddValidators(e);

        e.addValidator(new PositionBillEntryValidator());
    }

    @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);
        for (DynamicObject orgEntity : positionEntities) {
            positionBoIds.add(orgEntity.getLong(String.format("%s_id", PositionBillConstant.NCKD_POSITION)));

            // 获取上级岗位
            DynamicObject parentPositionVersionDy = orgEntity.getDynamicObject(PositionBillConstant.NCKD_PARENT);
            if (parentPositionVersionDy != null) {
                long parentOrgBoId = parentPositionVersionDy.getLong(PositionBillConstant.BOID_KEY);
                positionBoIds.add(parentOrgBoId);
                //orgEntity.set("adminorgboid", Long.valueOf(parentOrgBoId));
            }
        }

        // 根据岗位业务ID从数据库中获取岗位信息
        DynamicObjectCollection positionQueryDyColl = QueryServiceHelper.query(PositionBillConstant.HBPM_POSITIONHR, PositionBillConstant.ID_KEY, new QFilter[]{new QFilter(PositionBillConstant.ID_KEY, QCP.in, positionBoIds)});
        List<Object> listIds = new ArrayList<Object>();
        positionQueryDyColl.forEach(row -> listIds.add(row.getLong(PositionBillConstant.ID_KEY)));
        DynamicObject[] dbPositionDys = BusinessDataServiceHelper.load(listIds.toArray(), EntityMetadataCache.getDataEntityType(PositionBillConstant.HBPM_POSITIONHR));
        Map<Long, DynamicObject> dbPositionMap = Maps.newHashMapWithExpectedSize(dbPositionDys.length);
        for (DynamicObject dbPositionDy : dbPositionDys) {
            dbPositionMap.put(dbPositionDy.getLong(PositionBillConstant.ID_KEY), dbPositionDy);
        }

        // 准备岗位保存数据
        OperateOption operateOption = OperateOption.create();
        List<DynamicObject> positionList = Lists.newArrayListWithExpectedSize(positionEntities.length);
        for (DynamicObject positionEntity : positionEntities) {
            long positionId = positionEntity.getLong(String.format("%s_id", PositionBillConstant.NCKD_POSITION));

            // 如果数据库存在则用数据库的岗位对象
            DynamicObject positionDy = dbPositionMap.get(positionId);
            // 不存在则创建一个
            if (positionDy == null) {
                positionDy = BusinessDataServiceHelper.newDynamicObject(PositionBillConstant.HBPM_POSITIONHR);
            }

            // 键值转换
            Map<String, String> transKeyMap = new HashMap<String, String>();
            DataEntityPropertyCollection properties = positionDy.getDataEntityType().getProperties();
            for (IDataEntityProperty property : properties) {
                String name = property.getName();
                if (name.startsWith(FIELD_PREFIX)) {
                    transKeyMap.put(name.substring(name.indexOf(FIELD_PREFIX)), name);
                }
            }
            // 设立日期单独处理
            transKeyMap.put(PositionBillConstant.ESTABLISHMENTDATE_KEY, PositionBillConstant.NCKD_ESTDATE);

            // 将表单中的信息赋值到岗位信息中
            HRDynamicObjectUtils.copy(positionEntity, positionDy);
            positionDy.set(PositionBillConstant.ID_KEY, positionId);
            DynamicObject parentPositionVersionDy = positionEntity.getDynamicObject(PositionBillConstant.NCKD_PARENT);
            if (parentPositionVersionDy != null) {
                positionDy.set(PositionBillConstant.PARENT_KEY, dbPositionMap.get(parentPositionVersionDy.getLong(PositionBillConstant.BOID_KEY)));
            } else {
                positionDy.set(PositionBillConstant.PARENT_KEY, null);
            }
            positionDy.set(PositionBillConstant.STATUS, StatusEnum.A);
            positionDy.set(PositionBillConstant.ENABLE, EnableEnum.YES.getCode());
            positionList.add(positionDy);
            String number = positionDy.getString("number");
            if (HRStringUtils.isNotEmpty(number)) {
                operateOption.setVariableValue(positionId + "coderule_billno_from_initAbstractCodeRule", "coderule_billno_from_init_value_of_operation");
            }
        }
        // 跳过功能权限校验
        operateOption.setVariableValue(OperateOptionConst.ISHASRIGHT, Boolean.TRUE.toString());
        // 跳过数据权限校验
        operateOption.setVariableValue(OperateOptionConst.SKIPCHECKPERMISSION, Boolean.TRUE.toString());
        StringBuilder errorMsg = new StringBuilder();
        for (int index = 0; index < positionList.size(); index++) {
            DynamicObject positionDy = positionList.get(index);
            OperationServiceImpl opImpl = new OperationServiceImpl();
            OperationResult saveResult = opImpl.localInvokeOperation(PositionBillConstant.SAVE_OP, new DynamicObject[] { positionDy }, operateOption);
            if (!saveResult.isSuccess()) {
                List<IOperateInfo> errorOrValidateInfo = saveResult.getAllErrorOrValidateInfo();
                for (IOperateInfo operateInfo : errorOrValidateInfo) {
                    errorMsg.append(operateInfo.getMessage());
                }
            } else {
                //DynamicObject[] dbPositionEntityDys = OrgRepository.getInstance().queryOrgDys(String.join(",", PositionBillConstant.ID_KEY, PositionBillConstant.NUMBER_KEY), new QFilter(PositionBillConstant.ID_KEY, QCP.in, saveResult.getSuccessPkIds()));
                DynamicObject[] dbPositionEntityDys = null;
                DynamicObject dbPositionEntityDy = dbPositionEntityDys[0];
                DynamicObject positionEntity = positionEntities[index];
                positionEntity.set(String.format("%s_id", PositionBillConstant.NCKD_POSITION), dbPositionEntityDy.get(PositionBillConstant.ID_KEY));
                positionEntity.set(PositionBillConstant.NUMBER_KEY, dbPositionEntityDy.getString(PositionBillConstant.NUMBER_KEY));
            }
        }
        if (errorMsg.length() > 0) {
            throw new KDBizException(errorMsg.toString());
        }
    }

}
