package nckd.jxccl.hrmp.haos.plugin.operate.adminorg;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.args.BeginOperationTransactionArgs;
import kd.bos.entity.plugin.args.EndOperationTransactionArgs;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.hr.hbp.common.util.HRDateTimeUtils;
import nckd.jxccl.base.orm.helper.QFilterCommonHelper;
import nckd.jxccl.hrmp.haos.common.adminorg.AdminOrgConstant;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 组织快速维护确认变更操作插件
 * @entity: nckd_haos_adminorgdet_ext
 * @operate: confirmchange
 * @author: jtd
 * @date: 2025-10-16 9:47
 */
public class AdminOrgDetailConfirmChangeOpPlugin extends AbstractOperationServicePlugIn  {

    /** 上级变更 */
    private static final String CHANGETYPE_PARENT = "1020_S";

    /** 变更信息 */
    private static final String CHANGETYPE_INFO = "1030_S";

    /** 变更前组织信息 */
    private DynamicObjectCollection adminOrgOldDyColl;

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

        DynamicObject[] dataEntities = e.getDataEntities();
        DynamicObject data = dataEntities[0];
        // 未来生效不处理
        if (HRDateTimeUtils.dayAfter(data.getDate(AdminOrgConstant.BSED), HRDateTimeUtils.getNowDate())) {
            return;
        }

        String changeType = data.getDynamicObject(AdminOrgConstant.CHANGETYPE).getString(AdminOrgConstant.NUMBER_KEY);
        if (CHANGETYPE_PARENT.equals(changeType)) {
            beginOpParentHandler(dataEntities);
        }
    }

    /**
     * 处理调整上级数据
     * @param dataEntities
     */
    private void beginOpParentHandler(DynamicObject[] dataEntities) {
        // 获取组织及下级组织（旧数据）
        QFilter qFilter = QFilter.of("1!=1");
        Arrays.stream(dataEntities).map(dataEntity -> dataEntity.getString(AdminOrgConstant.STRUCTLONGNUMBER)+"%").forEach(structlongnumber -> {
            qFilter.or(QFilter.like(AdminOrgConstant.STRUCTLONGNUMBER, structlongnumber));
        });
        adminOrgOldDyColl = QueryServiceHelper.query(AdminOrgConstant.ADMINORG_ENTITYID, AdminOrgConstant.BOID_KEY, new QFilter[]{QFilter.isNotNull(AdminOrgConstant.STRUCTLONGNUMBER).and(qFilter).and(QFilterCommonHelper.getCurrentVersionFilter())});
    }

    @Override
    public void endOperationTransaction(EndOperationTransactionArgs e) {
        super.endOperationTransaction(e);

        DynamicObject[] dataEntities = e.getDataEntities();
        DynamicObject data = dataEntities[0];
        // 未来生效不处理
        if (HRDateTimeUtils.dayAfter(data.getDate(AdminOrgConstant.BSED), HRDateTimeUtils.getNowDate())) {
            return;
        }

        String changeType = data.getDynamicObject(AdminOrgConstant.CHANGETYPE).getString(AdminOrgConstant.NUMBER_KEY);
        switch (changeType) {
            case CHANGETYPE_PARENT:
                endOpParentHandler();
                break;
            case CHANGETYPE_INFO:
                //endOpInfoHandler(dataEntities);
        }
    }

    /**
     * 处理调整上级数据
     */
    private void endOpParentHandler() {
        // 获取组织及下级组织（新数据）含历史版本
        List<Long> adminOrgBoIds = adminOrgOldDyColl.stream().map(adminOrg -> adminOrg.getLong(AdminOrgConstant.BOID_KEY)).collect(Collectors.toList());
        String selectProperties = String.join(",", AdminOrgConstant.BOID_KEY, AdminOrgConstant.STRUCTLONGNUMBER, AdminOrgConstant.LEVEL, String.join(",", AdminOrgConstant.ADMINORG_STRUCT_FIELDS));
        QFilter qFilter = QFilter.isNotNull(AdminOrgConstant.STRUCTLONGNUMBER).and(new QFilter(AdminOrgConstant.STRUCTLONGNUMBER, QCP.not_equals, "")).and(new QFilter(AdminOrgConstant.BOID_KEY, QCP.in, adminOrgBoIds));
        DynamicObject[] adminOrgDys = BusinessDataServiceHelper.load(AdminOrgConstant.ADMINORG_ENTITYID, selectProperties, new QFilter[]{qFilter}, AdminOrgConstant.BOID_KEY);
        // 遍历获取结构编码
        Map<String, String> structMap = Arrays.stream(adminOrgDys)
                .map(adminOrgDy -> adminOrgDy.getString(AdminOrgConstant.STRUCTLONGNUMBER))
                .flatMap(structNumber -> Arrays.stream(structNumber.split("!")))
                .collect(Collectors.toMap(
                        Function.identity(), // 等价于 structNumber -> structNumber
                        structNumber -> "", // value为空
                        (existing, replacement) -> existing // 重复key处理 保留旧值或新值都可以 这里随便挑一个
                ));

        // 根据结构编码获取组织
        DynamicObjectCollection adminOrgDyColl = QueryServiceHelper.query(AdminOrgConstant.ADMINORG_ENTITYID, String.join(",", AdminOrgConstant.BOID_KEY, AdminOrgConstant.STRUCTNUMBER), new QFilter[]{new QFilter(AdminOrgConstant.STRUCTNUMBER, QCP.in, new ArrayList<String>(structMap.keySet())).and(QFilterCommonHelper.getCurrentVersionFilter())}, String.join(",", AdminOrgConstant.LEVEL, AdminOrgConstant.NUMBER_KEY));
        adminOrgDyColl.forEach(adminOrgDy -> structMap.put(adminOrgDy.getString(AdminOrgConstant.STRUCTNUMBER), adminOrgDy.getString(AdminOrgConstant.BOID_KEY)));

        // 更新一二三四五六级组织
        for (DynamicObject adminOrgDy : adminOrgDys) {
            String[] structLongNumbers = adminOrgDy.getString(AdminOrgConstant.STRUCTLONGNUMBER).split("!");
            for (int i = 0; i < AdminOrgConstant.ADMINORG_STRUCT_FIELDS.length; i++) {
                adminOrgDy.set(AdminOrgConstant.ADMINORG_STRUCT_FIELDS[i], i < structLongNumbers.length ? structMap.get(structLongNumbers[i]) : null);
            }
        }

        // 保存数据
        SaveServiceHelper.save(adminOrgDys);
    }

    /**
     * 处理变更信息数据
     * @param dataEntities
     */
    private void endOpInfoHandler(DynamicObject[] dataEntities) {
        // 存放变更数据的BOID
        List<Long> boIds = new ArrayList<Long>();
        // 获取组织结构编码
        Map<String, Long> structNumberMap = new HashMap<String, Long>();
        // 拼接过滤条件
        QFilter qFilter = QFilter.of("1!=1");
        for (DynamicObject data : dataEntities) {
            boIds.add(data.getLong(AdminOrgConstant.BOID_KEY));
            structNumberMap.put(data.getString(AdminOrgConstant.STRUCTNUMBER), data.getLong(AdminOrgConstant.ID_KEY));
            qFilter.or(QFilter.like(AdminOrgConstant.STRUCTLONGNUMBER, data.getString(AdminOrgConstant.STRUCTLONGNUMBER)+"%"));
        }
        qFilter.and(QFilterCommonHelper.getCurrentVersionFilter());

        // 查询字段
        String adminOrgStructField = String.join(",", AdminOrgConstant.ADMINORG_STRUCT_FIELDS);
        String selectProperties = String.join(",", AdminOrgConstant.BOID_KEY, AdminOrgConstant.SOURCEVID_KEY, AdminOrgConstant.STRUCTLONGNUMBER, adminOrgStructField);

        // 存放关联历史版本ID和要更新的字段以及值
        Map<Long, String> sourceIdMap = new HashMap<Long, String>();
        // 查询需要更新的组织(当前版本含本身)
        DynamicObject[] adminOrgDys = BusinessDataServiceHelper.load(AdminOrgConstant.ADMINORG_ENTITYID, selectProperties, new QFilter[]{qFilter}, String.join(",", AdminOrgConstant.LEVEL, AdminOrgConstant.NUMBER_KEY));
        for (DynamicObject adminOrgDy : adminOrgDys) {
            for (String structNumber : structNumberMap.keySet()) {
                if (adminOrgDy.getString(AdminOrgConstant.STRUCTLONGNUMBER).contains(structNumber)) {
                    int index = Arrays.asList(adminOrgDy.getString(AdminOrgConstant.STRUCTLONGNUMBER).split("!")).indexOf(structNumber);
                    String fieldKey = AdminOrgConstant.ADMINORG_STRUCT_FIELDS[index];
                    Long value = structNumberMap.get(structNumber);
                    adminOrgDy.set(fieldKey, value);
                    sourceIdMap.put(adminOrgDy.getLong(AdminOrgConstant.SOURCEVID_KEY), String.join("@", fieldKey, value.toString()));
                    break;
                }
            }
        }

        // 查询出历史版本记录
        Set<Long> sourceIds = new HashSet<>(sourceIdMap.keySet());
        DynamicObject[] adminOrgHisDys = BusinessDataServiceHelper.load(AdminOrgConstant.ADMINORG_ENTITYID, String.join(",", AdminOrgConstant.STRUCTLONGNUMBER, adminOrgStructField), new QFilter[]{new QFilter(AdminOrgConstant.ID_KEY, QCP.in, sourceIds)}, String.join(",", AdminOrgConstant.LEVEL, AdminOrgConstant.NUMBER_KEY));
        for (DynamicObject adminOrgHisDy : adminOrgHisDys) {
            String[] sourceId = sourceIdMap.get(adminOrgHisDy.getLong(AdminOrgConstant.ID_KEY)).split("@");
            // 判断是否此次变更的组织
            if (boIds.indexOf(adminOrgHisDy.getLong(AdminOrgConstant.BOID_KEY)) > 0) {
                adminOrgHisDy.set(sourceId[0], adminOrgHisDy.getLong(AdminOrgConstant.ID_KEY));
            } else {
                adminOrgHisDy.set(sourceId[0], Long.valueOf(sourceId[1]));
            }
        }

        // 合并数据
        DynamicObject[] result = new DynamicObject[adminOrgDys.length + adminOrgHisDys.length];
        System.arraycopy(adminOrgDys, 0, result, 0, adminOrgDys.length);
        System.arraycopy(adminOrgHisDys, 0, result, adminOrgDys.length, adminOrgHisDys.length);
        // 保存数据
        SaveServiceHelper.save(result);
    }

}
