package com.lantone.qc.kernel.catalogue.threelevelward;

import com.google.common.collect.ImmutableMap;
import com.lantone.qc.kernel.catalogue.QCCatalogue;
import com.lantone.qc.pub.model.InputInfo;
import com.lantone.qc.pub.model.OutputInfo;
import com.lantone.qc.pub.model.doc.DoctorAdviceDoc;
import com.lantone.qc.pub.model.doc.LisDoc;
import com.lantone.qc.pub.util.StringUtil;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @ClassName : THR03044
 * @Description : 抗生素使用指征不明确
 * @Author : kwz
 * @Date: 2020-07-23 14:16
 */
@Component
public class THR03044 extends QCCatalogue {
    public static Map<String, String> lisData = ImmutableMap.<String, String>builder()
            .put("超敏C反应蛋白", ">10")
            .put("降钙素CT(免疫)", ">0.25")
            .put("尿=白细胞", ">13.2")
            //.put("白细胞计数[电阻抗法]", "<0.4")
            //.put("中性粒细胞绝对值", ">12")
            //.put("中性粒细胞百分率", ">70%")
            .put("血培养报阳时间", "")
            //            .put("尿培养加菌落计数", "细菌生长")
            .put("一般细菌涂片检查", "细菌生长")
            //            .put("内毒素鲎定性试验", "阳性")
            //            .put("常规药敏定性试验", "阳性")
            //            .put("细菌抗体测定", "阳性")
            .put("碱性磷酸酶[速率法]", ">80")
            .put("血沉", ">25")
            //            .put("肥达氏反应", "大于等于1:160")
            //            .put("外斐氏反应", "大于等于:160")
            .put("粪=白细胞", ">2")
            //            .put("前列腺液白细胞", "大于1个/高位视野")
            .put("胸水常规=白细胞", ">500")
            .put("G+球菌:痰夜", "少,中等,多,偶见")
            .put("G-球菌:痰夜", "少,中等,多,偶见")
            .put("G+杆菌:痰夜", "少,中等,多,偶见")
            .put("G-杆菌:痰夜", "少,中等,多,偶见")
            .build();

    public static Map<String, String> lisGroupData = ImmutableMap.<String, String>builder()
            .put("白细胞计数[电阻抗法]", "<0.4")
            .put("中性粒细胞绝对数", ">12")
            .put("中性粒百分数", ">70")
            .build();

    public void start(InputInfo inputInfo, OutputInfo outputInfo) {
        status.set("0");
        List<DoctorAdviceDoc> doctorAdviceDocs = inputInfo.getDoctorAdviceDocs();
        List<LisDoc> lisDocs = inputInfo.getLisDocs();

        if (doctorAdviceDocs.size() == 0 || lisDocs.size() == 0) {
            return;
        }

        Set<String> antibiotics = doctorAdviceDocs
                .stream()
                .map(x -> x.getStructureMap().get("药品类型"))
                .filter(x -> StringUtil.isNotBlank(x) && x.contains("抗生素"))
                .collect(Collectors.toSet());

        if (antibiotics.size() == 0) {
            return;
        }

        Map<String, String> lises = new HashMap<>();
        Map<String, String> lisReportMap = new HashMap<>();

        for (LisDoc lisDoc : lisDocs) {
            Map<String, String> lisDocStructureMap = lisDoc.getStructureMap();
            String lisName = lisDocStructureMap.get("报告名称").trim();
            String result = lisDocStructureMap.get("检验结果");
            lisReportMap.put(lisName, result);
            if (lisName.contains("=")) {
                lises.put(lisName.split("=")[1], result);
            } else {
                lises.put(lisName, result);
            }
        }


        /**
         * 白细胞组合项单独处理
         */
        if (lises.containsKey("白细胞计数[电阻抗法]")) {
            String wbcValue = lisGroupData.get("白细胞计数[电阻抗法]");
            String wbc = lises.get("白细胞计数[电阻抗法]");
            if (!compare(wbc, wbcValue)) {
                status.set("-1");
                return;
            }
            if (lises.containsKey("中性粒细胞绝对数")) {
                String neutrophilValue = lisGroupData.get("中性粒细胞绝对数");
                String neutrophil = lises.get("中性粒细胞绝对数");
                if (!compare(neutrophil, neutrophilValue)) {
                    status.set("-1");
                    return;
                }
            } else if (lises.containsKey("中性粒百分数")) {
                String neutrophilValue = lisGroupData.get("中性粒百分数");
                String neutrophil = lises.get("中性粒百分数");
                if (!compare(neutrophil, neutrophilValue)) {
                    status.set("-1");
                    return;
                }
            }
        }

        //如果这个病例的化验项目不在lisData，不报
        Set<String> dataLises = lisData.keySet();
        Set<String> collect = new HashSet<>();
        for (String dataLis : dataLises) {
            if (dataLis.contains("=")) {
                collect.add(dataLis.split("=")[1]);
            } else {
                collect.add(dataLis);
            }
        }
        collect.retainAll(lises.keySet());
        if (collect.size() == 0) {
            return;
        }

        String[] lisNameMapSub = null;
        String[] lisNameSub = null;
        String lisMapKey = null, lisMapValue = null, lisKey = null, lisValue = null;
        for (Map.Entry<String, String> lisDataMap : lisData.entrySet()) {
            String lisName = lisDataMap.getKey();
            String lisResult = lisDataMap.getValue();
            if (lisName.contains("=")) {
                lisNameMapSub = lisName.split("=");
            }
            if (lisNameMapSub != null) {
                lisMapKey = lisNameMapSub[0]; //静态map(lisData)的key根据=分隔，得到的key，如尿=白细胞，lisMapKey=尿
                lisMapValue = lisNameMapSub[1];//静态map(lisData)的key根据=分隔，得到的value，如尿=白细胞，lisMapValue=白细胞
            } else {
                lisMapValue = lisName;//若静态map(lisData)的key没有=，直接用key作为分隔后的value，如超敏C反应蛋白，lisMapValue=超敏C反应蛋白
            }
            for (Map.Entry<String, String> lis : lisReportMap.entrySet()) {
                String lisname = lis.getKey();
                String result = lis.getValue();
                lisNameSub = lisname.split("=");
                lisKey = lisNameSub[0];//库中化验表map的key根据=分隔，得到的key，如尿=白细胞，lisMapKey=尿
                lisValue = lisNameSub[1];
                if (StringUtil.isBlank(lisMapKey) && lisMapValue.equals(lisValue)) {
                    if (!compare(result, lisResult)) {
                        status.set("-1");
                        return;
                    }
                }
                if (StringUtil.isNotBlank(lisMapKey) && lisMapKey.contains(lisKey) && lisMapValue.equals(lisValue)) {
                    if (!compare(result, lisResult)) {
                        status.set("-1");
                        return;
                    }
                }
            }
        }

    }

    /**
     * 比对化验表数据与lisData中数据大小，若符合则返回true
     *
     * @param result
     * @param value
     * @return
     */
    private boolean compare(String result, String value) {
        boolean flag = false;
        String s = num_method(value);
        String resultValue = num_method(result);
        if (num_contain(resultValue) && num_contain(s)) {
            if (Float.parseFloat(resultValue) > Float.parseFloat(s) && value.contains(">")) {
                flag = true;
            }
            if (Float.parseFloat(resultValue) < Float.parseFloat(s) && value.contains("<")) {
                flag = true;
            }
        } else {
            if (s.contains(result)) {
                flag = true;
            }
        }
        return flag;
    }

    public String num_method(String content) {
        //        String compile = "(\\d+\\.\\d+)|(\\d+)";
        String group = "";
        String compile = "([1-9]\\d*\\.?\\d*)|(0\\.\\d*[1-9])";
        Pattern p = Pattern.compile(compile);
        Matcher matcher = p.matcher(content);
        if (matcher.find()) {
            group = matcher.group(0);
        }
        return group;
    }

    public Boolean num_contain(String content) {
        //        String compile = "(\\d+\\.\\d+)|(\\d+)";
        String compile = "(\\d+)";
        Pattern p = Pattern.compile(compile);
        Matcher matcher = p.matcher(content);
        boolean b = matcher.find();
        return b;
    }
}