package com.kingdee.eas.custom.perfweb.utils;

import com.kingdee.bos.Context;
import com.kingdee.shr.perfweb.app.base.evalplan.PerfPeriodInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * 飞书消息批量推送辅助类
 * <p>
 * 统一处理：按 wfLevel 分组查询下一节点处理人 → 合并结果 → 推送飞书消息
 */
public class FeishuPushHelper {

    private static final Logger logger = LoggerFactory.getLogger(FeishuPushHelper.class);

    /**
     * 按 wfLevel 分组查询下一节点处理人，合并后推送飞书消息（下一节点处理人去重）
     */
    public static void sendOnceByWfLevel(Context ctx, Map<Integer, FeishuBatchContext> feishuBatchByWfLevel) {
        if (feishuBatchByWfLevel == null || feishuBatchByWfLevel.isEmpty()) {
            return;
        }

        Set<String> allEvaObjSet = new LinkedHashSet<>();
        Map<String, Integer> evaObjSubmitWfLevelMap = new HashMap<>();
        Map<String, Set<String>> mergedNextHandlerMap = new HashMap<>();
        Map<String, String> mergedWorkFlowNameMap = new HashMap<>();
        PerfPeriodInfo period = null;

        List<Integer> wfLevels = new ArrayList<>(feishuBatchByWfLevel.keySet());
        Collections.sort(wfLevels);

        for (Integer submitWfLevel : wfLevels) {
            FeishuBatchContext batch = feishuBatchByWfLevel.get(submitWfLevel);
            if (batch == null || batch.getEvaObjSet().isEmpty()) {
                continue;
            }
            allEvaObjSet.addAll(batch.getEvaObjSet());
            for (String evaObjId : batch.getEvaObjSet()) {
                evaObjSubmitWfLevelMap.put(evaObjId, submitWfLevel);
            }
            if (period == null && batch.getPeriod() != null) {
                period = batch.getPeriod();
            }

            Map<String, String> currentHandlerMap = new HashMap<>();
            Map<String, Set<String>> evaObjHandlerMap = new HashMap<>();
            Map<String, Set<String>> workNodeNameMap = new HashMap<>();
            Map<String, String> workFlowNameMap = new HashMap<>();

            PerfEvaObjectUtil.getBatchCurrentNodeHandersForEvaObj(ctx, batch.getEvaObjSet(), currentHandlerMap,
                    evaObjHandlerMap, workNodeNameMap, workFlowNameMap, String.valueOf(submitWfLevel + 1));

            mergeHandlerMap(mergedNextHandlerMap, evaObjHandlerMap);
            mergedWorkFlowNameMap.putAll(workFlowNameMap);
        }

        if (allEvaObjSet.isEmpty() || period == null) {
            logger.info("无考核对象或考核周期为空，跳过飞书推送");
            return;
        }

        try {
            String messageUrl = UrlParamUtil.buildPerfPortalFeishuMessageUrl();
            String workFlowName = mergedWorkFlowNameMap.isEmpty() ? "" : mergedWorkFlowNameMap.values().iterator().next();
            FeishuMessageUtil.sendAfterScoreSubmit(ctx, evaObjSubmitWfLevelMap, mergedNextHandlerMap,
                    allEvaObjSet, period, messageUrl, workFlowName, messageUrl);
            logger.info("飞书消息推送完成，考核对象数={}", allEvaObjSet.size());
        } catch (Exception e) {
            logger.error("飞书推送异常", e);
            throw new RuntimeException(e);
        }
    }

    private static void mergeHandlerMap(Map<String, Set<String>> target, Map<String, Set<String>> source) {
        if (source == null || source.isEmpty()) {
            return;
        }
        for (Map.Entry<String, Set<String>> entry : source.entrySet()) {
            target.computeIfAbsent(entry.getKey(), k -> new HashSet<>()).addAll(entry.getValue());
        }
    }

    /**
     * 按 wfLevel 分组的飞书推送数据容器
     */
    public static class FeishuBatchContext {
        private final Set<String> evaObjSet = new LinkedHashSet<>();
        private PerfPeriodInfo period;

        public Set<String> getEvaObjSet() {
            return evaObjSet;
        }

        public PerfPeriodInfo getPeriod() {
            return period;
        }

        public void setPeriod(PerfPeriodInfo period) {
            this.period = period;
        }
    }
}
