package com.zzsn.search.util;



import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SplitKeyword {

    //关键词处理
    public static List<String> transForm(String keyWords) {
        if (keyWords == null) {
            return null;
        }
        //（*备注：或：用“，”号表示，与：用“+”号表示，非：用“-”号表示）
        keyWords = keyWords.replaceAll("[,，;；]", "|");
        keyWords = keyWords.replace("（", "(");
        keyWords = keyWords.replace("）", ")");

        List<String> keyWordsList = new ArrayList<>();

        if (!keyWords.contains("+")) { //不含有+  形式：A|B|C
            keyWords = keyWords.replace("(", "");
            keyWords = keyWords.replace(")", "");
            keyWordsList = Arrays.asList(keyWords.split("\\|"));

        } else if (keyWords.contains(")+(")) { //含有+ 形式：(A|B)+(C|D)+(E|F)
            String[] cronArray = keyWords.split("\\+");
            List<List<String>> list = new ArrayList<>();
            for (int i = 0; i < cronArray.length; i++) {
                cronArray[i] = cronArray[i].replace("(", "");
                cronArray[i] = cronArray[i].replace(")", "");
                cronArray[i] = cronArray[i].replace("|", ",");
                list.add(Arrays.asList(cronArray[i].split(",")));
            }
            List<String> stringList = getPermutations(list);
            for (String str : stringList) {
                keyWordsList.add(str.substring(0, str.length() - 1));
            }
        }
        return keyWordsList;
    }


    /**
     * 多个数组排列组合
     * @param list 原始list
     * @param <T> 数据类型
     * @return
     */
    private static <T> List<List<T>> getDescartes(List<List<T>> list) {
        List<List<T>> returnList = new ArrayList<>();
        descartesRecursive(list, 0, returnList, new ArrayList<T>());
        return returnList;
    }

    /**
     * 递归实现
     * 原理：从原始list的0开始依次遍历到最后
     *
     * @param originalList 原始list
     * @param position     当前递归在原始list的position
     * @param returnList   返回结果
     * @param cacheList    临时保存的list
     */
    private static <T> void descartesRecursive(List<List<T>> originalList, int position, List<List<T>> returnList, List<T> cacheList) {
        List<T> originalItemList = originalList.get(position);
        for (int i = 0; i < originalItemList.size(); i++) {
            //最后一个复用cacheList，节省内存
            List<T> childCacheList = (i == originalItemList.size() - 1) ? cacheList : new ArrayList<>(cacheList);
            childCacheList.add(originalItemList.get(i));
            if (position == originalList.size() - 1) {//遍历到最后退出递归
                returnList.add(childCacheList);
                continue;
            }
            descartesRecursive(originalList, position + 1, returnList, childCacheList);
        }
    }

    /**
     * 多个数组排列组合
     * @param list 原始list
     * @return
     */
    private static List<String> getPermutations(List<List<String>> list) {
        List<String> resultList = new ArrayList<>();
        List<List<String>> list1 = getDescartes(list);
        if(!CollectionUtils.isEmpty(list1)){
            list1.forEach(temp->{
                String str = listToStr(temp);
                if (!org.springframework.util.StringUtils.isEmpty(str)) {
                    resultList.add(listToStr(temp));
                }
            });
        }
        return resultList;
    }

    private static String listToStr(List<String> list){
        StringBuffer str = new StringBuffer();
        if(!CollectionUtils.isEmpty(list)){
            list.forEach(temp->{
                str.append(temp).append("+");
            });
        }
        return str.toString();
    }

    public static void main(String[] args) {
        String kwords="Russia+(sanction|Cancel|revoke|restrict|stop|Punishment|punishment)+(Center for a New America Security|CNAS|WestExec Advisor|Carnegie Endowment for International Peace|CEIP|Brookings Institution|National Endowment for Democracy|NED|Council on Foreign Relations|CFR|Foreign Policy for American|fp4America|Center for American Progress|CAP|Meridian International|Asia Society|The Asia Group LLG|Penn Biden Center for Diplomacy and Global Engagement|Rand|Foreign Affairs|Center for Strategic and International Studies|Hoover Institution on War|revolution and Peace|American Enterprise Institute for Public Policy Research|Hudson Institute|Urban Institute|International Institute for Applied Systems Analysis|Heritage Foundation|CATO Institute|Carter Center|The Boston Consulting Group|Aspen Human Institute|East-West Center|Center for Defense Information|Battelle|The Population Council|Institute for the Future|U.S. Asian Cultural Academy|Atlantic Council|Centre for European Policy Studies|Royal Institute of Intemational Affairs|The Fabian Society|The Foreign Policy Centre|Institut français des relations internationales|Irish Examiner|timesofmalta|texasnewstoday|californianewstimes|foxbusiness|IAI|DGAP)";
        List<String> strings = transForm(kwords);
        for (String key :strings) {
            System.out.println(key);
        }
    }
}
