package com.lantone.qc.kernel.util;

import com.google.common.collect.Lists;
import com.lantone.qc.kernel.catalogue.QCCatalogue;
import com.lantone.qc.pub.Content;
import com.lantone.qc.pub.model.doc.DoctorAdviceDoc;
import com.lantone.qc.pub.model.doc.ThreeLevelWardDoc;
import com.lantone.qc.pub.model.entity.Diag;
import com.lantone.qc.pub.util.ListUtil;
import com.lantone.qc.pub.util.StringUtil;
import lombok.Getter;
import lombok.Setter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName : CatalogueUtil
 * @Description :
 * @Author : 楼辉荣
 * @Date: 2020-03-09 10:59
 */
@Getter
@Setter
public class CatalogueUtil {
    public static Map<String, QCCatalogue> qcCatalogueMap = new HashMap<>();


    public static boolean isEmpty(String content) {
        return StringUtil.isBlank(removeSpecialChar(content));
    }

    public static String removeSpecialChar(String content) {
        if (StringUtil.isEmpty(content)) {
            return "";
        }
        return content.replaceAll("[\r\n|/r/n|\n|/n|/t|\t]", "").trim();
    }

    public static String[] extractDigit(String value) {
        String[] res = new String[2];
        try {
            String regTime = "([\\d]+)([\\u4e00-\\u9fa5]+)";
            Pattern pattern = Pattern.compile(regTime);
            Matcher matcher = pattern.matcher(value);
            if (matcher.find(0)) {
                res[0] = matcher.group(1);
                res[1] = matcher.group(2);
            } else {
                res[0] = value;
                res[1] = "";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return res;
    }

    /**
     * words中的所有词，哪些不包含在text文本里的引号下面
     * 如：
     * word：{"高血压","糖尿病","白血病","感冒"}
     * text: 否认患有"高血压，糖尿病等"，"白血病",感冒
     * 结果：感冒
     *
     * @param words
     * @param text
     * @return
     */
    public static List<String> noInQuotes(List<String> words, String text) {
        List<String> retWords = Lists.newArrayList();
        if (ListUtil.isNotEmpty(words) && StringUtil.isNotBlank(text)) {
            List<String> sections = Lists.newArrayList();
            int index = 0;
            for (String txt : text.split("\"")) {
                if (index % 2 == 1 && text.indexOf("\"", text.indexOf(txt)) > -1) {
                    sections.add(txt);
                }
                index++;
            }
            for (String word : words) {
                if (StringUtil.isNotBlank(word) && sections.stream().filter(section -> section.indexOf(word) != -1).count() == 0) {
                    retWords.add(word);
                }
            }
        }
        return retWords;
    }

    /**
     * 从现有诊断中筛选符合某一属性值的诊断
     *
     * @param diags
     * @param nature
     * @param natureValue
     * @return
     */
    public static List<Diag> filterDiagsByNature(List<Diag> diags, String nature, String natureValue) {
        if (ListUtil.isEmpty(diags) || StringUtil.isBlank(nature) || StringUtil.isBlank(natureValue)) {
            return null;
        }
        RedisUtil redisUtil = SpringContextUtil.getBean("redisUtil");
        Map<String, Map<String, String>> conceptDiagPropertyMap = redisUtil.getJsonStringValue(KernelConstants.CONCEPT_DIAG_PROPERTY_MAP);
        if (conceptDiagPropertyMap == null) {
            return null;
        }
        List<Diag> retDiags = Lists.newArrayList();
        diags.forEach(i -> {
            if (i != null && StringUtil.isNotBlank(i.getName())) {
                Map<String, String> diagDetailMap = conceptDiagPropertyMap.get(i.getName());
                if (diagDetailMap != null) {
                    String natureValue_ = diagDetailMap.get(nature);
                    if (StringUtil.isNotBlank(natureValue_) && natureValue_.equals(natureValue)) {
                        retDiags.add(i);
                    }
                }
            }
        });
        return retDiags;
    }

    /**
     * 对比两个String类型的Date是否一致
     *
     * @param firstDateStr
     * @param secondDateStr
     * @param datePattren
     * @return
     */
    public static boolean equalsDate(String firstDateStr, String secondDateStr, String datePattren) {
        if (!isEmpty(firstDateStr) && !isEmpty(secondDateStr)) {
            Date firstDate = StringUtil.parseDateTime(firstDateStr);
            Date secondDate = StringUtil.parseDateTime(secondDateStr);
            SimpleDateFormat fmt = new SimpleDateFormat(datePattren);
            if (firstDate != null && secondDate != null && fmt.format(firstDate).equals(fmt.format(secondDate))) {
                return true;
            }
        }
        return false;
    }

    public static boolean equalsDate(Date firstDate, Date secondDate, String datePattren) {
        if (firstDate != null && secondDate != null) {
            SimpleDateFormat fmt = new SimpleDateFormat(datePattren);
            return fmt.format(firstDate).equals(fmt.format(secondDate));
        }
        return false;
    }

    /**
     * 对比两个String类型的Date先后
     *
     * @param firstDateStr
     * @param secondDateStr
     * @param symbol        =1 -> firstDateStr比secondDateStr时间早
     * @param symbol        =-1 -> firstDateStr比secondDateStr时间晚
     * @return
     */
    public static boolean compareDate(String firstDateStr, String secondDateStr, int symbol) {
        if (!isEmpty(firstDateStr) && !isEmpty(secondDateStr)) {
            Date firstDate = StringUtil.parseDateTime(firstDateStr);
            Date secondDate = StringUtil.parseDateTime(secondDateStr);
            if (symbol == 1) {
                return firstDate != null && secondDate != null && firstDate.before(secondDate);
            } else if (symbol == -1) {
                return firstDate != null && secondDate != null && firstDate.after(secondDate);
            }
        }
        return false;
    }

    /**
     * 对比两个去除了特殊字符的字符串是否一致
     *
     * @param firstStr
     * @param secondStr
     * @return
     */
    public static boolean compareToken(String firstStr, String secondStr) {
        if (!isEmpty(firstStr) && !isEmpty(secondStr)) {
            if (removeSpecialChar(firstStr).equals(removeSpecialChar(secondStr))) {
                return true;
            }
        }
        return false;
    }

    /**
     * 比较时间,以分钟为单位
     * endDate比startDate多diff分钟则返回true
     *
     * @param startDate
     * @param endDate
     * @param diff
     * @return
     */
    public static boolean compareTime(Date startDate, Date endDate, Long diff) {
        boolean overtime = false;
        if (startDate == null || endDate == null) {
            return false;
        }
        Calendar calendar_s = Calendar.getInstance();
        Calendar calendar_e = Calendar.getInstance();
        Long time_s, time_e, time_diff;
        try {
            calendar_s.setTime(startDate);
            calendar_e.setTime(endDate);

            time_s = calendar_s.getTimeInMillis();
            time_e = calendar_e.getTimeInMillis();

            time_diff = (time_e - time_s) / (1000 * 60);
            if (time_diff >= diff) {
                overtime = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return overtime;
    }

    /**
     * 获取查房记录标题中医师职称
     *
     * @return
     */
    public static String subTitle(String srcText) {
        if (StringUtil.isNotBlank(srcText) && srcText.contains("代")) {
            srcText = srcText.substring(srcText.lastIndexOf("代") + 1);
        }
        return srcText;
    }

    /**
     * 获取指定字符串出现的次数
     *
     * @param srcText  源字符串
     * @param findText 要查找的字符串
     * @return
     */
    public static int appearNumber(String[] srcText, String findText) {
        int count = 0;
        Pattern p = null;
        Matcher m = null;
        for (String title : srcText) {
            title = subTitle(title);
            p = Pattern.compile(findText);
            m = p.matcher(title);
            while (m.find()) {
                count++;
            }
        }
        return count;
    }

    /**
     * 只保留Date数组中精确到分的格式
     *
     * @param dateFormats
     * @return
     */
    public static String[] processDateFormat(String[] dateFormats) {
        List<String> dateFormatsList = Arrays.asList(dateFormats);
        List<String> dateFormatsNew = new ArrayList<>(dateFormatsList);
        dateFormatsNew.removeIf(dateFormat -> !dateFormat.contains("m"));
        String[] dateFormatsArr = new String[dateFormatsNew.size()];
        return dateFormatsNew.toArray(dateFormatsArr);
    }

    /**
     * 判断字符串是否包含中文字
     *
     * @param str
     * @return
     */
    public static boolean isContainChinese(String str) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }

    /**
     * 判断是否为手术患者
     *
     * @param doctorAdviceDocs
     * @return
     */
    public static boolean isOperativePatients(List<DoctorAdviceDoc> doctorAdviceDocs) {
        String orderPrescriptionType, orderItemName;
        for (DoctorAdviceDoc doctorAdviceDoc : doctorAdviceDocs) {
            Map<String, String> doctorAdviceStructureMap = doctorAdviceDoc.getStructureMap();
            orderPrescriptionType = doctorAdviceStructureMap.get("医嘱处方类型");
            orderItemName = doctorAdviceStructureMap.get("医嘱项目名称");
            if (StringUtil.isNotBlank(orderPrescriptionType) && "手术".equals(orderPrescriptionType)) {
                return true;
            }
            if (StringUtil.isNotBlank(orderItemName) && Pattern.matches(".*拟.*术.*", orderItemName)
                    && !orderItemName.contains("冠脉造影")) {
                return true;
            }
        }
        return false;
    }
}