package nckd.jxccl.swc.hsas.formplugin.web.outdata.basedata;

import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.entity.tree.TreeNode;
import kd.bos.form.control.Search;
import kd.bos.form.control.TreeView;
import kd.bos.form.control.events.SearchEnterEvent;
import kd.bos.form.control.events.SearchEnterListener;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.hr.hbp.common.cache.HRPageCache;
import nckd.jxccl.base.swc.helper.SWCHelper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Tyx 2025-12-22
 * 外单位项目选择界面右表格搜索插件 【hsas_calitemselect】
 */
public class OutItemSelectTreePlugin extends AbstractFormPlugin implements SearchEnterListener {

    // 常量定义
    private static final String TREE_SEARCH_CONTROL = "nckd_treesearchap";
    private static final String TREE_VIEW_CONTROL = "nckd_treeviewap";
    private static final String ITEM_SELECT_ENTRY = "nckd_itemselectentry";
    private static final String SALARY_ITEM_KEY = "salaryitemkey";
    private static final String NO_SEARCH_RESULT_MSG = "搜索已完成，未找到搜索项。";

    public OutItemSelectTreePlugin() {
    }

    public void registerListener(EventObject e) {
        super.registerListener(e);
        Search search = (Search)this.getView().getControl(TREE_SEARCH_CONTROL);
        search.addEnterListener(this);
    }

    @Override
    public void search(SearchEnterEvent arg) {
        String searchText = arg.getText();
        HRPageCache pageCache = new HRPageCache(this.getView());
        Map<String, Map<String, Map<String, Object>>> dataMap =
                (Map<String, Map<String, Map<String, Object>>>) pageCache.get("allItemData", Map.class);
        boolean isExpend = StringUtils.isNotEmpty(searchText);

        List<TreeNode> nodeItemList = new ArrayList<>();
        nodeItemList.addAll(loadSLItemChildNode(searchText, isExpend, dataMap));
        nodeItemList.addAll(loadBSItemChildNode(searchText, isExpend, dataMap));

        if (nodeItemList.isEmpty()) {
            showNoResultNotification();
        } else {
            updateTreeView(nodeItemList);
        }
    }

    private void showNoResultNotification() {
        this.getView().showTipNotification(
                ResManager.loadKDString(NO_SEARCH_RESULT_MSG, "CalResultTplItemTreePlugin_0",
                        "swc-hsas-formplugin", new Object[0]));
    }

    private void updateTreeView(List<TreeNode> nodeItemList) {
        TreeView treeView = (TreeView) this.getView().getControl(TREE_VIEW_CONTROL);
        treeView.deleteAllNodes();
        treeView.addNodes(nodeItemList);
        checkSelectedTreeNode(treeView, nodeItemList);
    }

    private void checkSelectedTreeNode(TreeView treeView, List<TreeNode> nodeList) {
        DynamicObjectCollection selectDatas = this.getView().getModel().getEntryEntity(ITEM_SELECT_ENTRY);
        Set<String> uniqueCodeSet = (Set)selectDatas.stream().map((selectData) -> {
            return selectData.getString("nckd_itemunicodeid");
        }).collect(Collectors.toSet());
        List<TreeNode> checkNodeList = SWCHelper.getCheckTreeNodeList(nodeList, uniqueCodeSet);
        if (CollectionUtils.isNotEmpty(checkNodeList)) {
            treeView.checkNodes(checkNodeList);
        }
    }

    private List<TreeNode> loadSLItemChildNode(String name, boolean isExpend, Map<String, Map<String, Map<String, Object>>> dataMap) {
        List<TreeNode> childNodes = new ArrayList<>(10);
        List<Map<String, Object>> salaryItemList;
        if (StringUtils.isEmpty(name)) {
            salaryItemList = SWCHelper.mapToList(dataMap.get("salaryitemkey"));
        } else {
            salaryItemList = this.findItemByName(name, "salaryitemkey", dataMap);
        }

        if (salaryItemList == null || salaryItemList.isEmpty()) {
            return childNodes;
        }
        // 构建项目类型节点映射和项目节点列表映射
        Map<String, TreeNode> itemTypeNodeMap = new LinkedHashMap<>(salaryItemList.size());
        Map<String, List<TreeNode>> salaryItemNodeMap = new HashMap<>(16);
        // 遍历薪酬项目列表，构建树节点
        for (Map<String, Object> itemMap : salaryItemList) {
            String itemTypeNum = (String) itemMap.get("group_number");
            String itemTypeName = (String) itemMap.get("group_name");

            // 获取或创建该项目类型的节点列表
            List<TreeNode> itemNodes = salaryItemNodeMap.computeIfAbsent(itemTypeNum, k -> new ArrayList<>(10));

            // 添加项目节点
            String groupId = "SI" + itemTypeNum + "_@_";
            String nodeId = String.valueOf(itemMap.get("id"));
            String uniqueCode = String.valueOf(itemMap.get("uniquecode"));
            String itemName = (String) itemMap.get("name");
            itemNodes.add(new TreeNode(groupId, nodeId, itemName));

            // 如果还没有该项目类型的父节点，则创建
            if (!itemTypeNodeMap.containsKey(itemTypeNum)) {
                TreeNode itemTypeNode = new TreeNode("SI", groupId, itemTypeName);
                itemTypeNode.setExpend(isExpend);
                itemTypeNode.setIsOpened(isExpend);
                itemTypeNodeMap.put(itemTypeNum, itemTypeNode);
            }
        }

        // 关联子节点到父节点
        List<TreeNode> finalTreeNodes = new ArrayList<>(itemTypeNodeMap.size());
        for (Map.Entry<String, TreeNode> entry : itemTypeNodeMap.entrySet()) {
            TreeNode parentNode = entry.getValue();
            List<TreeNode> children = salaryItemNodeMap.get(entry.getKey());
            parentNode.setChildren(children);
            finalTreeNodes.add(parentNode);
        }

        // 添加根节点
        if (!finalTreeNodes.isEmpty()) {
            TreeNode root = new TreeNode("", "SI",
                    ResManager.loadKDString("薪酬项目-SI", "FormulaItemOrFuncTreeHelper_1",
                            "swc-hsas-business", new Object[0]));
            root.setChildren(finalTreeNodes);
            root.setExpend(isExpend);
            root.setIsOpened(isExpend);
            childNodes.add(root);
        }

        return childNodes;
    }

    private List<TreeNode> loadBSItemChildNode(String name, boolean isExpend, Map<String, Map<String, Map<String, Object>>> dataMap) {
        List<TreeNode> childNodes = new ArrayList<>(10);
        return childNodes;
    }


    private List<Map<String, Object>> findItemByName(String name, String itemName, Map<String, Map<String, Map<String, Object>>> dataMap) {
        Map<String, Map<String, Object>> result = dataMap.get(itemName);
        if (result == null) {
            return new ArrayList<>(0);
        }

        return result.entrySet().stream()
                .filter(entry -> {
                    Map<String, Object> itemMap = entry.getValue();
                    if (itemMap == null || itemMap.isEmpty()) {
                        return entry.getKey().contains(name);
                    }

                    String number = (String) itemMap.get("number");
                    return (StringUtils.isNotEmpty(number) && number.contains(name)) ||
                            entry.getKey().contains(name);
                })
                .map(Map.Entry::getValue)
                .collect(Collectors.toList());
    }

}
