package nckd.jxccl.sit.hcsi.formplugin.web.tp.helper;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.entity.tree.TreeNode;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.basedata.BaseDataServiceHelper;
import kd.bos.util.CollectionUtils;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;

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

public class SitItemSelectAddItemServiceHelper {

    private static final String INSURANCEITEM_ENTITY = "sitbs_insuranceitem";
    private static final String QUERY_FIELDS = "id,number,name,group.name,group.number,group.id";
    private static final String DEFAULT_ORDER = "number asc";

    private static final String INSURANCEITEM_KEY = "insuranceitemkey";
    private static final String BASEITEM_KEY = "baseitemkey";
    private static final String ITEM_TYPE_II = "II";
    private static final String BASE_TYPE_II = "BI";
    private static final String PREFIX_SEPARATOR = "_@_";

    /**
     * 获取所有需要展示的项目，目前就险种
     * @param orgId
     * @return
     */
    public Map<String, Map<String, Map<String, Object>>> getAllItemData(long orgId) {
        Map<String, Map<String, Map<String, Object>>> dataMap = new HashMap(4);
        Map<String, Map<String, Object>> insuranceItemMap = this.getInsuranceItemList(false, (QFilter)null, (QFilter)null, orgId);
        dataMap.put("insuranceitemkey", insuranceItemMap);
        //dataMap.put("baseitemkey", getBaseItemMap());
        return dataMap;
    }


    public Map<String, Map<String, Object>> getBaseItemMap() {
        Map<String, Map<String, Object>> baseItemMap = new HashMap<>(3);
        Map<String, Object> itemMap1 = new HashMap<>(3);
        itemMap1.put("id", "999990");
        itemMap1.put("number", "999990");
        itemMap1.put("name", "滞纳金");
        baseItemMap.put("滞纳金", itemMap1);
        Map<String, Object> itemMap2 = new HashMap<>(3);
        itemMap2.put("id", "999991");
        itemMap2.put("number", "999991");
        itemMap2.put("name", "利息");
        baseItemMap.put("利息", itemMap2);
        return baseItemMap;
    }

    private Map<String, Map<String, Object>> getInsuranceItemList(boolean isProrationFormula, QFilter countryQFilter, QFilter calBlockQFilter, long orgId) {
        if (isProrationFormula) {
            return Collections.emptyMap();
        }
        List<QFilter> qFilters = buildFilters(countryQFilter, calBlockQFilter, orgId);
        DynamicObjectCollection result = queryInsuranceItems(qFilters);
        return result.stream()
                .collect(Collectors.toMap(
                        item -> item.getString("name"),
                        this::convertToItemMap,
                        (existing, replacement) -> existing,
                        LinkedHashMap::new
                ));
    }

    private List<QFilter> buildFilters(QFilter countryQFilter, QFilter calBlockQFilter, long orgId) {
        List<QFilter> filters = new ArrayList<>();
        Optional.ofNullable(countryQFilter).ifPresent(filters::add);
        Optional.ofNullable(calBlockQFilter).ifPresent(filters::add);
        QFilter baseFilter = new QFilter("enable", "=", "1")
                .and(new QFilter("status", "=", "C"))
                .and(new QFilter("insurancetypeattr.number", QCP.not_in, new String[]{"1007_S","1008_S","1013_S","1014_S"}));
        filters.add(baseFilter);
        filters.add(BaseDataServiceHelper.getBaseDataFilter(INSURANCEITEM_ENTITY, orgId));
        return filters;
    }

    private DynamicObjectCollection queryInsuranceItems(List<QFilter> filters) {
        HRBaseServiceHelper helper = new HRBaseServiceHelper(INSURANCEITEM_ENTITY);
        return helper.queryOriginalCollection(
                QUERY_FIELDS,
                filters.toArray(new QFilter[0]),
                DEFAULT_ORDER
        );
    }

    private Map<String, Object> convertToItemMap(DynamicObject item) {
        Map<String, Object> itemMap = new HashMap<>(3);
        itemMap.put("id", item.getLong("id"));
        itemMap.put("number", item.getString("number"));
        itemMap.put("name", item.getString("name"));
        itemMap.put("group_name", item.getString("group.name"));
        itemMap.put("group_number", item.getString("group.number"));
        itemMap.put("group_id", item.getString("group.id"));
        return itemMap;
    }

    /**
     * 构建险种项目树结构
     * 顶层ID ： II
     * 险种分类节点ID：险种编码 + _@_
     * 险种项目子节点ID：险种项目ID
     * @param name
     * @param isExpend
     * @param dataMap
     * @return
     */
    public static List<TreeNode> loadInsuranceItemChildNode(String name, boolean isExpend,
                                                     Map<String, Map<String, Map<String, Object>>> dataMap) {
        // 所有险种项目
        List<Map<String, Object>> insuranceItemList = getInsuranceItemList(name, dataMap);
        List<TreeNode> tree = createRootNode(isExpend);
        if (CollectionUtils.isEmpty(insuranceItemList)) {
            return tree;
        }

        // 最后返回树：
        List<TreeNode> totalNodeList = new ArrayList<>(insuranceItemList.size() + 1);

        // 构建根节点：
        TreeNode itemRoot = new TreeNode("", ITEM_TYPE_II,
                ResManager.loadKDString("险种项目-II", "FormulaItemOrFuncTreeHelper_1",
                        "swc-hsas-business", new Object[0]));
        itemRoot.setExpend(isExpend);
        itemRoot.setIsOpened(isExpend);
        totalNodeList.add(itemRoot);

        // 构建子节点：
        if (!CollectionUtils.isEmpty(insuranceItemList)) {
            Map<String, TreeNode> itemTypeNodeMap = new LinkedHashMap(insuranceItemList.size());
            Map<String, List<TreeNode>> insuranceItemNodeMap = new HashMap(16);
            List<TreeNode> treeNodeList = null;
            String itemTypeNum = null;
            for (Map<String, Object> map : insuranceItemList) {
                itemTypeNum = (String)map.get("group_number");
                String itemTypeName = (String)map.get("group_name");
                treeNodeList = (List)insuranceItemNodeMap.get(itemTypeNum);
                if (treeNodeList == null) {
                    treeNodeList = new ArrayList(10);
                    insuranceItemNodeMap.put(itemTypeNum, treeNodeList);
                }
                ((List)treeNodeList).add(new TreeNode(itemTypeNum + PREFIX_SEPARATOR, String.valueOf(map.get("id")), (String)map.get("name")));
                if (!itemTypeNodeMap.containsKey(itemTypeNum)) {
                    TreeNode itemTreeNode = new TreeNode(ITEM_TYPE_II, itemTypeNum + PREFIX_SEPARATOR, itemTypeName);
                    itemTreeNode.setExpend(isExpend);
                    itemTreeNode.setIsOpened(isExpend);
                    itemTypeNodeMap.put(itemTypeNum, itemTreeNode);
                }
            }
            treeNodeList = new ArrayList(itemTypeNodeMap.size());
            Iterator it = itemTypeNodeMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, TreeNode> entry = (Map.Entry)it.next();
                TreeNode typeNode = (TreeNode)entry.getValue();
                typeNode.setChildren((List)insuranceItemNodeMap.get(entry.getKey()));
                treeNodeList.add(typeNode);
            }
            itemRoot.setChildren(treeNodeList);
            return totalNodeList;
        }
        else {
            return totalNodeList;
        }
    }

    public static List<TreeNode> loadBaseItemChildNode(boolean isExpend) {
        // 最后返回树：
        List<TreeNode> totalNodeList = new ArrayList<>(2);

        // 构建根节点：
        TreeNode itemRoot = new TreeNode("", BASE_TYPE_II,
                ResManager.loadKDString("基本项目-II", "FormulaItemOrFuncTreeHelper_1",
                        "swc-hsas-business", new Object[0]));
        itemRoot.setExpend(isExpend);
        itemRoot.setIsOpened(isExpend);
        totalNodeList.add(itemRoot);

        //构建子节点，这里固定滞纳金和利息
        List<TreeNode> children = new ArrayList<>(2);
        children.add(new TreeNode(BASE_TYPE_II, "999990", "滞纳金"));
        children.add(new TreeNode(BASE_TYPE_II, "999991", "利息"));
        itemRoot.setChildren(children);
        return totalNodeList;
    }



    private static List<Map<String, Object>> getInsuranceItemList(String name,
                                                               Map<String, Map<String, Map<String, Object>>> dataMap) {
        return StringUtils.isEmpty(name)
                ? mapToList(dataMap.get(INSURANCEITEM_KEY))
                : findItemByName(name, INSURANCEITEM_KEY, dataMap);
    }

    public static List<Map<String, Object>> mapToList(Map<String, Map<String, Object>> dataMap) {
        if (dataMap != null && dataMap.size() != 0) {
            List<Map<String, Object>> result = new ArrayList(dataMap.size());
            Iterator var2 = dataMap.entrySet().iterator();

            while(var2.hasNext()) {
                Map.Entry<String, Map<String, Object>> entry = (Map.Entry)var2.next();
                result.add(entry.getValue());
            }

            return result;
        } else {
            return new ArrayList();
        }
    }

    public static List<Map<String, Object>> findItemByName(String name, String itemName, Map<String, Map<String, Map<String, Object>>> dataMap) {
        List<Map<String, Object>> filterItemsList = new ArrayList();
        Map<String, Map<String, Object>> result = (Map)dataMap.get(itemName);
        Iterator var5 = result.entrySet().iterator();

        while(var5.hasNext()) {
            Map.Entry<String, Map<String, Object>> entry = (Map.Entry)var5.next();
            if (((String)entry.getKey()).contains(name)) {
                filterItemsList.add(entry.getValue());
            }
        }

        return filterItemsList;
    }

    private static List<TreeNode> createRootNode(boolean isExpend) {
        return createRootNode(isExpend, Collections.emptyList());
    }

    private static List<TreeNode> createRootNode(boolean isExpend, List<TreeNode> children) {
        TreeNode itemRoot = new TreeNode("", ITEM_TYPE_II,
                ResManager.loadKDString("险种项目-II", "FormulaItemOrFuncTreeHelper_1",
                        "swc-hsas-business", new Object[0]));
        itemRoot.setExpend(isExpend);
        itemRoot.setIsOpened(isExpend);
        itemRoot.setChildren(children);
        return Collections.singletonList(itemRoot);
    }

}
