package com.lantone.qc.kernel.structure.ai.process;

import com.alibaba.fastjson.JSONObject;
import com.lantone.qc.kernel.structure.ai.model.EntityEnum;
import com.lantone.qc.kernel.structure.ai.model.Lemma;
import com.lantone.qc.pub.model.entity.BetterFinding;
import com.lantone.qc.pub.model.entity.Clinical;
import com.lantone.qc.pub.model.entity.Diag;
import com.lantone.qc.pub.model.entity.OutcomeCure;
import com.lantone.qc.pub.model.entity.OutcomeToBetter;
import com.lantone.qc.pub.model.entity.PositiveFinding;
import com.lantone.qc.pub.model.entity.Sign;
import com.lantone.qc.pub.model.entity.TreatmentPlan;
import com.lantone.qc.pub.model.label.ThreeLevelWardLabel;

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

/**
 * @ClassName : EntityProcessThreeLevelWard
 * @Description : 查房记录
 * @Author : 胡敬
 * @Date: 2020-03-20 11:20
 */
public class EntityProcessThreeLevelWard extends EntityProcess {
    private List<String> titleList = Arrays.asList(
            EntityEnum.TITLE_FOR_SIGN.toString(),
            EntityEnum.TITLE_FOR_DIAG.toString(),
            EntityEnum.TITLE_FOR_DIAG_BASIS.toString(),
            EntityEnum.TITLE_FOR_DIFF.toString(),
            EntityEnum.TITLE_FOR_TREAT.toString());

    public ThreeLevelWardLabel extractEntity(JSONObject aiOut) {
        ThreeLevelWardLabel threeLevelWardLabel = new ThreeLevelWardLabel();
        String content = aiOut.getString("content");

        Map<String, List<String>> titleText = subWithTitle(aiOut);
        //全部临床表现实体
        List<Lemma> clinicalLemmas = createEntityTree(aiOut, EntityEnum.CLINICAL_FEATURE.toString());
        //全部诊断
        List<Lemma> diagLemmas = createEntityTree(aiOut, EntityEnum.DIEASE.toString());
        //诊断依据
        if (titleText.get(EntityEnum.TITLE_FOR_DIAG_BASIS.toString()) != null) {
            List<String> diagBasisList = titleText.get(EntityEnum.TITLE_FOR_DIAG_BASIS.toString());
            String text = textJoin(content, diagBasisList);
            String[] diagBasisSplit = String.join(",", diagBasisList).split(",");
            //诊断依据文本
            threeLevelWardLabel.setDiagBasisText(text);
            //病史(在 诊断依据 以外的片段中出现 任一 临床表现)
            addClinical(threeLevelWardLabel, diagBasisSplit, clinicalLemmas);
            //补充诊断/初步诊断/修正诊断
            addDiag(threeLevelWardLabel, diagBasisSplit, diagLemmas);
        }

        //鉴别诊断
        if (titleText.get(EntityEnum.TITLE_FOR_DIFF.toString()) != null) {
            List<String> diffDiagList = titleText.get(EntityEnum.TITLE_FOR_DIFF.toString());
            String diagBasis = String.join(",", diffDiagList);
            String[] diffDiagSplit = diagBasis.split(",");
            //病史(在 鉴别诊断 以外的片段中出现 任一 临床表现)
            addClinical(threeLevelWardLabel, diffDiagSplit, clinicalLemmas);
            //补充诊断/初步诊断/修正诊断
            addDiag(threeLevelWardLabel, diffDiagSplit, diagLemmas);
            //添加鉴别诊断
            List<Diag> diags = new ArrayList<>();
            for (Lemma dieaseLemma : diagLemmas) {
                if (Integer.parseInt(dieaseLemma.getPosition()) < Integer.parseInt(diffDiagSplit[0])
                        || Integer.parseInt(dieaseLemma.getPosition()) > Integer.parseInt(diffDiagSplit[diffDiagSplit.length - 1])) {
                    continue;
                }
                Diag diag = new Diag();
                diag.setHospitalDiagName(dieaseLemma.getText());
                diags.add(diag);
            }
            threeLevelWardLabel.setDiffDiag(diags);
            List<Lemma> diagDiffLemmas = createEntityTree(aiOut, EntityEnum.TITLE_FOR_DIFF.toString());
            for (Lemma lemma : diagDiffLemmas) {
                if (lemma.getText().contains("诊断明确") || lemma.getText().contains("无需鉴别")) {
                    threeLevelWardLabel.setDiffDiagText(lemma.getText());
                    break;
                }
            }
        }

        //没有诊断依据和鉴别诊断情况下，添加诊断
        if (titleText.get(EntityEnum.TITLE_FOR_DIAG_BASIS.toString()) == null
                && titleText.get(EntityEnum.TITLE_FOR_DIFF.toString()) == null) {
            //补充诊断/初步诊断/修正诊断
            addDiag(threeLevelWardLabel, diagLemmas);
        }

        //查体
        List<Lemma> signLemmas = createEntityTree(aiOut, EntityEnum.PHYSICAL_EXAMINATION.toString());
        List<Sign> signs = new ArrayList<>();
        for (Lemma lemma : signLemmas) {
            Sign sign = new Sign();
            sign.setName(lemma.getText());
            signs.add(sign);
        }
        threeLevelWardLabel.setSigns(signs);

        //诊疗计划
        List<Lemma> treatmentPlanLemmas = createEntityTree(aiOut, EntityEnum.TREATMENT_PLAN.toString());
        List<TreatmentPlan> treatmentPlans = new ArrayList<>();
        for (Lemma lemma : treatmentPlanLemmas) {
            TreatmentPlan treatmentPlan = new TreatmentPlan();
            treatmentPlan.setName(lemma.getText());
            treatmentPlans.add(treatmentPlan);
        }
        threeLevelWardLabel.setTreatmentPlans(treatmentPlans);

        //好转表现
        List<Lemma> betterFindingLemmas = createEntityTree(aiOut, EntityEnum.BETTER_FINDING.toString());
        List<BetterFinding> betterFindings = new ArrayList<>();
        for (Lemma lemma : betterFindingLemmas) {
            BetterFinding betterFinding = new BetterFinding();
            betterFinding.setName(lemma.getText());
            betterFindings.add(betterFinding);
        }
        threeLevelWardLabel.setBetterFindings(betterFindings);

        //转归情况-好转
        List<Lemma> outcomeToBetterLemmas = createEntityTree(aiOut, EntityEnum.OUTCOME_TO_BETTER.toString());
        List<OutcomeToBetter> outcomeToBetters = new ArrayList<>();
        for (Lemma lemma : outcomeToBetterLemmas) {
            OutcomeToBetter outcomeToBetter = new OutcomeToBetter();
            outcomeToBetter.setName(lemma.getText());
            outcomeToBetters.add(outcomeToBetter);
        }
        threeLevelWardLabel.setOutcomeToBetters(outcomeToBetters);

        //转归情况-治愈
        List<Lemma> outcomeCureLemmas = createEntityTree(aiOut, EntityEnum.OUTCOME_CURE.toString());
        List<OutcomeCure> outcomeCures = new ArrayList<>();
        for (Lemma lemma : outcomeCureLemmas) {
            OutcomeCure outcomeCure = new OutcomeCure();
            outcomeCure.setName(lemma.getText());
            outcomeCures.add(outcomeCure);
        }
        threeLevelWardLabel.setOutcomeCures(outcomeCures);

        //阳性表现
        List<Lemma> positiveFindingLemmas = createEntityTree(aiOut, EntityEnum.POSITIVE_FINDING.toString());
        List<PositiveFinding> positiveFindings = new ArrayList<>();
        for (Lemma lemma : positiveFindingLemmas) {
            PositiveFinding positiveFinding = new PositiveFinding();
            positiveFinding.setName(lemma.getText());
            positiveFindings.add(positiveFinding);
        }
        threeLevelWardLabel.setPositiveFindings(positiveFindings);
        return threeLevelWardLabel;
    }

    private String textJoin(String content, List<String> operativeFindingsList) {
        StringBuffer text = new StringBuffer();
        for (String titleTextIndex : operativeFindingsList) {
            String[] titleTextIndexSplit = titleTextIndex.split(",");
            text.append(content.substring(Integer.parseInt(titleTextIndexSplit[0]),
                    Integer.parseInt(titleTextIndexSplit[1])));
        }
        return text.toString();
    }

    /**
     * 根据各标题截取文本index
     *
     * @param aiOut
     * @return
     */
    private Map<String, List<String>> subWithTitle(JSONObject aiOut) {
        Map<String, List<String>> titleText = new LinkedHashMap<>();
        String content = aiOut.getString("content");
        List<Lemma> lemmaList = loadAllLemmaList(aiOut.getJSONObject("annotation").getJSONArray("T"));
        Lemma lemma;
        int start = 0;
        String subContentIndex = "", title = "";
        for (int i = 0; i < lemmaList.size(); i++) {
            lemma = lemmaList.get(i);
            if (!titleList.contains(lemma.getProperty()) && i != lemmaList.size() - 1) {
                continue;
            }
            if (i != lemmaList.size() - 1) {
                if (start == 0) {
                    start = Integer.parseInt(lemma.getPosition());
                    title = lemma.getProperty();//截取的这一段文本的标题
                } else {
                    subContentIndex = start + lemma.getText().length() + 1 + "," + Integer.parseInt(lemma.getPosition());
                    putSubContent(titleText, title, subContentIndex);
                    start = Integer.parseInt(lemma.getPosition());
                    title = lemma.getProperty();//截取的这一段文本的标题
                }
            } else {
                //将倒数第二个标题存入结构
                subContentIndex = start + "," + Integer.parseInt(lemma.getPosition());
                putSubContent(titleText, title, subContentIndex);
                //如果是最后一个Lemma，文本就从当前lemma的position开始取，取到结束
                title = lemma.getProperty();//截取的这一段文本的标题
                if (titleList.contains(title)) {
                    start = Integer.parseInt(lemma.getPosition());
                    int lastIndex = content.length() - 1;
                    subContentIndex = start + "," + lastIndex;
                    putSubContent(titleText, title, subContentIndex);
                }
            }
        }
        return titleText;
    }

    private void putSubContent(Map<String, List<String>> titleText, String text, String subContent) {
        List<String> textList;
        if (titleText.containsKey(text)) {
            titleText.get(text).add(subContent);
        } else {
            textList = new ArrayList<>();
            textList.add(subContent);
            titleText.put(text, textList);
        }
    }

    /**
     * 添加病史(临床表现)
     *
     * @param threeLevelWardLabel
     * @param indexArray          标题对应文本全部起始位置、结束位置信息
     * @param clinicalLemmas
     */
    private void addClinical(ThreeLevelWardLabel threeLevelWardLabel, String[] indexArray, List<Lemma> clinicalLemmas) {
        List<Clinical> clinicals = new ArrayList<>();
        for (Lemma lemma : clinicalLemmas) {
            if (Integer.parseInt(lemma.getPosition()) > Integer.parseInt(indexArray[0])
                    && Integer.parseInt(lemma.getPosition()) < Integer.parseInt(indexArray[indexArray.length - 1])) {
                continue;
            }
            Clinical clinical = new Clinical();
            clinical.setName(lemma.getText());
            clinicals.add(clinical);
        }
        if (threeLevelWardLabel.getClinicals().size() == 0) {
            threeLevelWardLabel.setClinicals(clinicals);
        } else {
            threeLevelWardLabel.getClinicals().addAll(clinicals);
        }
    }

    /**
     * 添加补充诊断/初步诊断/修正诊断
     *
     * @param threeLevelWardLabel
     * @param indexArray          标题对应文本全部起始位置、结束位置信息
     * @param diagLemmas
     */
    private void addDiag(ThreeLevelWardLabel threeLevelWardLabel, String[] indexArray, List<Lemma> diagLemmas) {
        List<Diag> diags = new ArrayList<>();
        for (Lemma lemma : diagLemmas) {
            if (Integer.parseInt(lemma.getPosition()) > Integer.parseInt(indexArray[0])
                    && Integer.parseInt(lemma.getPosition()) < Integer.parseInt(indexArray[indexArray.length - 1])) {
                continue;
            }
            Diag diag = new Diag();
            diag.setHospitalDiagName(lemma.getText());
            diags.add(diag);
        }
        if (threeLevelWardLabel.getDiags().size() == 0) {
            threeLevelWardLabel.setDiags(diags);
        } else {
            threeLevelWardLabel.getDiags().addAll(diags);
        }
    }

    /**
     * 没有诊断依据和鉴别诊断情况下，添加诊断
     *
     * @param threeLevelWardLabel
     * @param diagLemmas
     */
    private void addDiag(ThreeLevelWardLabel threeLevelWardLabel, List<Lemma> diagLemmas) {
        List<Diag> diags = new ArrayList<>();
        for (Lemma lemma : diagLemmas) {
            Diag diag = new Diag();
            diag.setHospitalDiagName(lemma.getText());
            diags.add(diag);
        }
        if (threeLevelWardLabel.getDiags().size() == 0) {
            threeLevelWardLabel.setDiags(diags);
        } else {
            threeLevelWardLabel.getDiags().addAll(diags);
        }
    }

}