package cn.cslg.pas.common.utils;

import cn.cslg.pas.common.core.base.Constants;
import cn.cslg.pas.domain.PatentAffair;
import cn.cslg.pas.domain.PatentApplicant;
import cn.cslg.pas.domain.ProjectFieldTree;
import cn.cslg.pas.common.model.dto.ClassNumberDTO;
import cn.hutool.core.util.StrUtil;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class PatentUtils {

    /**
     * 直辖市
     */
    public static final List<String> CHARTERED_CITIES = Arrays.asList("北京市", "天津市", "重庆市", "上海市");

    public static String getMapKeyByValue(Map<String, String> map, String value) {
        for (String key : map.keySet()) {
            if (map.get(key).equals(value)) {
                return key;
            }
        }
        return null;
    }

    public static Integer getIntKeyByValue(Map<String, String> map, String value) {
        String key = getMapKeyByValue(map, value);
        if (key != null) {
            return Integer.parseInt(key);
        }
        return 0;
    }

    public static Integer getIntKeyByOrganType(String name) {
        if (name.length() < 4) {
            return 1;
        }
        if (Arrays.asList("大学", "学院", "学校").contains(name.substring(name.length() - 2))) {
            return 3;
        }
        if (Arrays.asList("研究所", "研究所").contains(name.substring(name.length() - 3)) || "研究总院".equals(name.substring(name.length() - 4))) {
            return 4;
        }
        return 2;
    }

    public static List<String> formatValue(String string) {
        return StringUtils.changeStringToString(string.replaceAll(" ", ""), "\\|");
    }

    public static List<String> formatValue2(String string) {
        return StringUtils.changeStringToString(string.replaceAll(">", ""), "\\\n");
    }

    public static String getPatentCountry(String patentNo) {
        return StrUtil.sub(patentNo, 0, 2);
    }

    public static String formatAddress(String address, Integer level) {
        for (String name : CHARTERED_CITIES) {
            if (address.contains(name)) {
                if (level == 1 || level == 2) {
                    return name;
                } else {
                    return StrUtil.sub(address, address.indexOf("市") + 1, address.indexOf("区") + 1);
                }
            }
        }
        String a = removeStringNotChinese(address);
        switch (level) {
            case 1:
                return StrUtil.sub(a, 0, a.indexOf("省") + 1);
            case 2:
                return StrUtil.sub(a, a.indexOf("省") + 1, a.indexOf("市") + 1);
            case 3:
                return StrUtil.sub(a, a.indexOf("市") + 1, a.indexOf("区") + 1);
        }
        return "暂无";
    }

    private static String removeStringNotChinese(String address) {
        String tmpString = address.replaceAll("(?i)[^a-zA-Z0-9\u4E00-\u9FA5]", "");
        char[] carr = tmpString.toCharArray();
        for (int i = 0; i < tmpString.length(); i++) {
            if (carr[i] < 0xFF) {
                carr[i] = ' ';
            }
        }
        return String.copyValueOf(carr).trim();
    }

    public static ClassNumberDTO getClassNumberDTO(String classNumber, Integer type) {
        ClassNumberDTO dto = new ClassNumberDTO();
        dto.setClassNumber(classNumber);
        switch (type) {
            case 1:
            case 2:
                dto.setA(StrUtil.sub(classNumber, 0, 1));
                dto.setB(StrUtil.sub(classNumber, 0, 3));
                dto.setC(StrUtil.sub(classNumber, 0, 4));
                dto.setD(StrUtil.sub(classNumber, 0, classNumber.indexOf("/")));
                dto.setE(classNumber);
                break;
            case 3:
                String[] a = StrUtil.split(classNumber, "/");
                dto.setB(a[0]);
                dto.setC(a[1]);
                break;
            case 4:
                String[] b = StrUtil.split(classNumber, "-");
                dto.setB(b[0]);
                dto.setC(b[1]);
                break;
        }
        return dto;
    }

    public static String getPeopleCountry(List<PatentApplicant> people) {
        if (people.size() != 0) {
            return people.get(0).getCountry();
        }
        return "";
    }

    public static String getPeopleAddress(List<PatentApplicant> people) {
        if (people.size() != 0) {
            return people.get(0).getAddressStr();
        }
        return "";
    }

    public static String getPeopleProvinceAndCityAndArea(List<PatentApplicant> people) {
        if (people.size() != 0) {
            return "";
        }
        return "";
    }

    public static String getPatentAffair(List<PatentAffair> affairList, Integer type) {
        if (affairList.size() == 0) {
            return "";
        }
        PatentAffair affair = affairList.get(0);
        switch (type) {
            case 0:
                return DateUtils.formatDate(affair.getDateTime(), DateUtils.YYYY_MM_DD);
            case 1:
                return affair.getCreateStatus();
            case 2:
                return affair.getCreateSimpleStatus();
            case 3:
                return StringUtils.join(affairList.stream().map(PatentAffair::getContent).collect(Collectors.toList()), Constants.SEPARATOR_VERTICAL_BAR);
            default:
                return "";
        }
    }

    public static String getTreeNodeFullName(List<ProjectFieldTree> treeList, String path) {
        List<String> paths = StringUtils.changeStringToString(path, "/");
        List<String> fullName = new ArrayList<>();
        paths.forEach(id -> fullName.add(treeList.stream().filter(item -> item.getId().equals(Integer.parseInt(id))).findFirst().orElse(new ProjectFieldTree()).getName()));
        return StringUtils.join(fullName, "\\");
    }

    public static List<String> getPatentLicensor(String text) {
        return Arrays.stream(text.replaceAll("\n", "").split("[0-99]\\.")).filter(StringUtils::isNotEmpty).collect(Collectors.toList());
    }

    public static String formatTextQuerySql(String content, String keyword) {
        String space = " ";
        String like = " LIKE ";
        String notLike = " NOT LIKE ";
        String left = "'%";
        String right = "%'";
        String placeholder = "#";
        Pattern patten = Pattern.compile(" OR | AND ");
        Matcher matcher = patten.matcher(content);
        String copy = matcher.replaceAll(placeholder);
        String[] querys = StringUtils.split(copy, placeholder);
        List<String> queryList = new ArrayList<>();

        if (content.split(",").length > 1) {
            String[] a = content.split(",");
            StringBuffer sb = new StringBuffer();

            for (int j = 0; j < a.length; j++) {
                content = sb.append(keyword).append(like).append(left).append(a[j]).append(right).append(" or ").toString();

                if (j == a.length - 1) {
                    content = sb.delete(sb.length() - 4, sb.length()).toString();

                }
            }
        } else {
            for (int i = 0; i < querys.length; i++) {
                String query = querys[i].replaceAll("\\(|\\)", "");
                queryList.add(query);
                content = content.replaceFirst(query, i + placeholder);
            }
            for (int i = 0; i < queryList.size(); i++) {
                StringBuffer sb = new StringBuffer();
                content = content.replaceAll(i + placeholder, sb.append(keyword).append(like).append(left).append(queryList.get(i)).append(right).toString());
            }
        }
        return content;
    }

    public static void main(String[] args) {
//        System.out.println(formatTextQuerySql("(一种 OR 测试) AND 测试2 AND (测试 OR A method)", "a.name"));
        System.out.println(formatTextQuerySql("(A method for manufacturing OR A test) AND 测试", "a.name"));
        System.out.println(formatTextQuerySql("CN", "a.name"));
        System.out.println(formatTextQuerySql("CN OR CM AND SD", "a.name"));
        System.out.println(formatTextQuerySql("CN OR CM AND CM", "a.name"));
    }
}
