package com.lantone.qc.kernel.util;

import com.lantone.qc.kernel.structure.ai.ThreeLevelWardAI;
import com.lantone.qc.pub.Content;
import com.lantone.qc.pub.jdbc.MysqlJdbc;
import com.lantone.qc.pub.model.InputInfo;
import com.lantone.qc.pub.model.doc.BeHospitalizedDoc;
import com.lantone.qc.pub.model.doc.FirstCourseRecordDoc;
import com.lantone.qc.pub.model.doc.LeaveHospitalDoc;
import com.lantone.qc.pub.model.doc.ThreeLevelWardDoc;
import com.lantone.qc.pub.model.doc.operation.OperationDiscussionDoc;
import com.lantone.qc.pub.model.doc.operation.OperationDoc;
import com.lantone.qc.pub.model.doc.ward.AttendingDoctorWardDoc;
import com.lantone.qc.pub.model.doc.ward.DirectorDoctorWardDoc;
import com.lantone.qc.pub.model.vo.QueryVo;
import com.lantone.qc.pub.util.ListUtil;
import com.lantone.qc.pub.util.PropertiesUtil;
import com.lantone.qc.pub.util.StringUtil;
import com.lantone.qc.trans.TransDispatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 长兴医院进模型数据
 * @Author: HUJING
 * @Date: 2020/4/1 17:23
 */
public class ModelDataUtil {
    private Logger logger = LoggerFactory.getLogger(ModelDataUtil.class);

    public void executor(String caseNumber, QueryVo queryVo) {
        InputInfo inputInfo = TransDispatch.trans(queryVo);
        if (inputInfo == null) {
            return;
        }
        Map<String, Map<String, String>> changxDocs = new LinkedHashMap<>();
        beHospitalized(inputInfo, changxDocs, "入院记录");
        firstCourseRecord(inputInfo, changxDocs, "首次病程录");
        operationDiscussion(inputInfo, changxDocs, "术后首次病程及谈话记录文档");
        threeLevelWard(inputInfo, changxDocs, "三级查房记录");
        leaveHospital(inputInfo, changxDocs, "出院小结");
        insertDB(caseNumber, changxDocs);
    }

    public void insertDB(String caseNumber, Map<String, Map<String, String>> changxDocs) {
        PropertiesUtil propertiesUtil = new PropertiesUtil("kernel.properties");
        MysqlJdbc mysqlJdbc = new MysqlJdbc(propertiesUtil.getProperty("mysql.test.user"),
                propertiesUtil.getProperty("mysql.test.password"),
                propertiesUtil.getProperty("mysql.test.url"));
        Connection connect = null;
        PreparedStatement pst = null;
        String sql = "INSERT INTO qc_model_input_info(case_number,title,sub_title,text) VALUES(?,?,?,?)";
        try {
            connect = mysqlJdbc.connect();
            connect.setAutoCommit(false);
            pst = connect.prepareStatement(sql);
            for (Map.Entry<String, Map<String, String>> changxDoc : changxDocs.entrySet()) {
                int i = 0;
                String model = changxDoc.getKey();
                for (Map.Entry<String, String> doc : changxDoc.getValue().entrySet()) {
                    pst.setString(1, caseNumber);
                    pst.setString(2, model);
                    pst.setString(3, doc.getKey());
                    pst.setString(4, doc.getValue());
                    pst.addBatch();
                    i++;
                    if ((i != 0 && i % 1000 == 0) || i == changxDoc.getValue().size()) {
                        pst.executeBatch();
                        connect.commit();
                        pst.clearBatch();
                    }
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                pst.close();
                connect.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public void truncateDB(String dbName) {
        PropertiesUtil propertiesUtil = new PropertiesUtil("kernel.properties");
        MysqlJdbc mysqlJdbc = new MysqlJdbc(propertiesUtil.getProperty("mysql.test.user"),
                propertiesUtil.getProperty("mysql.test.password"),
                propertiesUtil.getProperty("mysql.test.url"));
        Connection connect = null;
        PreparedStatement pst = null;
        String sql = "TRUNCATE " + dbName;
        try {
            connect = mysqlJdbc.connect();
            pst = connect.prepareStatement(sql);
            pst.execute();
            logger.info(dbName + "表已清空");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                pst.close();
                connect.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 入院记录
     *
     * @param inputInfo
     * @param changxDocs
     * @param model
     */
    public void beHospitalized(InputInfo inputInfo, Map<String, Map<String, String>> changxDocs, String model) {
        if (inputInfo == null) {
            return;
        }
        BeHospitalizedDoc beHospitalizedDoc = inputInfo.getBeHospitalizedDoc();
        if (beHospitalizedDoc != null) {
            Map<String, String> changxDoc = new LinkedHashMap<>();
            String chiefText = beHospitalizedDoc.getChiefLabel().getText();
            String presentText = beHospitalizedDoc.getPresentLabel().getText();
            String pastText = beHospitalizedDoc.getPastLabel().getText();
            String personalText = beHospitalizedDoc.getPersonalLabel().getText();
            String familyText = beHospitalizedDoc.getFamilyLabel().getText();
            String pacsText = beHospitalizedDoc.getPacsLabel().getText();
            String initialDiagText = beHospitalizedDoc.getInitialDiagLabel().getText();   //初步诊断
            String revisedDiagText = beHospitalizedDoc.getRevisedDiagLabel().getText();   //修正诊断
            String suppleDiagText = beHospitalizedDoc.getSuppleDiagLabel().getText();    //补充诊断
            String menstrualText = beHospitalizedDoc.getMenstrualLabel().getText();    //月经史
            String maritalText = beHospitalizedDoc.getMaritalLabel().getText();    //婚育史
            String vitalText = beHospitalizedDoc.getVitalLabel().getText();        //一般体格检查
            String vitalSpecialText = beHospitalizedDoc.getVitalLabelSpecial().getText();  //专科体格检查
            putDoc(changxDoc, Content.chief, chiefText);
            putDoc(changxDoc, Content.present, presentText);
            putDoc(changxDoc, Content.past, pastText);
            putDoc(changxDoc, Content.personal, personalText);
            putDoc(changxDoc, Content.family, familyText);
            putDoc(changxDoc, Content.pacs, pacsText);
            putDoc(changxDoc, Content.initial_diag, initialDiagText);
            putDoc(changxDoc, Content.revised_diag, revisedDiagText);
            putDoc(changxDoc, Content.supple_diag, suppleDiagText);
            putDoc(changxDoc, Content.menses, menstrualText);
            putDoc(changxDoc, Content.marriage, maritalText);
            putDoc(changxDoc, Content.phys_exam, vitalText);
            putDoc(changxDoc, Content.special_exam, vitalSpecialText);
            changxDocs.put(model, changxDoc);
        }
    }

    /**
     * 首次病程录
     *
     * @param inputInfo
     * @param changxDocs
     * @param model
     */
    public void firstCourseRecord(InputInfo inputInfo, Map<String, Map<String, String>> changxDocs, String model) {
        if (inputInfo == null) {
            return;
        }
        FirstCourseRecordDoc firstCourseRecordDoc = inputInfo.getFirstCourseRecordDoc();
        if (firstCourseRecordDoc != null) {
            Map<String, String> changxDoc = new LinkedHashMap<>();
            //病历特点
            putDoc(changxDoc, Content.case_feature, firstCourseRecordDoc.getCaseCharacteristicLabel().getText());
            //初步诊断
            putDoc(changxDoc, Content.initial_diag, firstCourseRecordDoc.getInitialDiagLabel().getText());
            //诊断依据
            putDoc(changxDoc, Content.diag_basis, firstCourseRecordDoc.getDiagnosisLabel().getText());
            //鉴别诊断
            putDoc(changxDoc, Content.differential_diag_basis, firstCourseRecordDoc.getDifferentialDiagLabel().getText());
            //诊疗计划
            putDoc(changxDoc, Content.treat_plan, firstCourseRecordDoc.getTreatPlanLabel().getText());
            changxDocs.put(model, changxDoc);
        }
    }

    /**
     * 术后首次病程及谈话记录文档
     *
     * @param inputInfo
     * @param changxDocs
     * @param model
     */
    public void operationDiscussion(InputInfo inputInfo, Map<String, Map<String, String>> changxDocs, String model) {
        if (inputInfo == null) {
            return;
        }
        List<OperationDoc> operationDocs = inputInfo.getOperationDocs();
        if (ListUtil.isEmpty(operationDocs)) {
            return;
        }
        Map<String, String> changxDoc = new LinkedHashMap<>();
        for (int i = 0; i < operationDocs.size(); i++) {
            if (operationDocs.get(i).getOperationDiscussionDoc() == null) {
                continue;
            }
            OperationDiscussionDoc operationDiscussionDoc = operationDocs.get(i).getOperationDiscussionDoc();
            putDoc(changxDoc, Content.operation_Discussion + i, operationDiscussionDoc.getText());
        }
        changxDocs.put(model, changxDoc);
    }

    /**
     * 查房记录
     *
     * @param inputInfo
     * @param changxDocs
     * @param model
     */
    public void threeLevelWard(InputInfo inputInfo, Map<String, Map<String, String>> changxDocs, String model) {
        if (inputInfo == null) {
            return;
        }
        List<ThreeLevelWardDoc> threeLevelWardDocs = inputInfo.getThreeLevelWardDocs();
        if (threeLevelWardDocs.size() == 0) {
            return;
        }
        ThreeLevelWardAI threeLevelWardAI = new ThreeLevelWardAI();
        Map<String, String> changxDoc = new LinkedHashMap<>();
        ThreeLevelWardDoc threeLevelWardDoc = threeLevelWardDocs.get(0);
        List<AttendingDoctorWardDoc> attendingDocs = threeLevelWardDoc.getAttendingDoctorWardDocs();//主治医师查房记录
        if (attendingDocs.size() > 0) {
            //主治医师首次查房记录
            Map<String, String> fitstAttStructureMap = attendingDocs.get(0).getStructureMap();
            putDoc(changxDoc, Content.attend + "首次查房记录", fitstAttStructureMap.get("病情记录"));
        }

        List<DirectorDoctorWardDoc> directorDocs = threeLevelWardDoc.getDirectorDoctorWardDocs();//主任医师查房记录
        if (directorDocs.size() > 0) {
            //主任医师首次查房记录
            Map<String, String> fitstDirStructureMap = directorDocs.get(0).getStructureMap();
            putDoc(changxDoc, Content.director + "首次查房记录", fitstDirStructureMap.get("病情记录"));

            //主任医师最后一次查房记录
            Map<String, String> lastDirStructureMap = directorDocs.get(directorDocs.size() - 1).getStructureMap();
            putDoc(changxDoc, Content.director + "末次查房记录", lastDirStructureMap.get("病情记录"));
        }

        List<Map<String, String>> directorDifficultRecord = new ArrayList<>();
        //疑难患者副高及以上查房记录
        if (inputInfo.getDifficultCaseDiscussDocs().size() > 0) {
            directorDifficultRecord = threeLevelWardAI.putDirectorDifficultRecord(inputInfo, threeLevelWardDocs);
            for (int i = 0; i < directorDifficultRecord.size(); i++) {
                putDoc(changxDoc, Content.difficultPatients + i, directorDifficultRecord.get(i).get("病情记录"));
            }
        }
        List<Map<String, String>> directorRescueRecord = new ArrayList<>();
        //抢救患者副高及以上查房记录
        if (inputInfo.getRescueDocs().size() > 0) {
            directorRescueRecord = threeLevelWardAI.putDirectorRescueRecord(inputInfo, threeLevelWardDocs);
            for (int i = 0; i < directorRescueRecord.size(); i++) {
                putDoc(changxDoc, Content.rescuingPatients + i, directorRescueRecord.get(i).get("病情记录"));
            }
        }
        changxDocs.put(model, changxDoc);
    }

    /**
     * 出院小结
     *
     * @param inputInfo
     * @param changxDocs
     * @param model
     */
    public void leaveHospital(InputInfo inputInfo, Map<String, Map<String, String>> changxDocs, String model) {
        if (inputInfo == null) {
            return;
        }
        LeaveHospitalDoc leaveHospitalDoc = inputInfo.getLeaveHospitalDoc();
        if (leaveHospitalDoc != null) {
            Map<String, String> changxDoc = new LinkedHashMap<>();
            //            putDoc(changxDoc, Content.discharge, leaveHospitalDoc.getText());
            Map<String, String> leaveHospitalStructureMap = leaveHospitalDoc.getStructureMap();
            if (leaveHospitalStructureMap != null) {
                if (leaveHospitalStructureMap.get(Content.inStatus) != null) {
                    putDoc(changxDoc, Content.inStatus, leaveHospitalStructureMap.get(Content.inStatus));
                }
                if (leaveHospitalStructureMap.get(Content.dischargeDiag) != null) {
                    putDoc(changxDoc, Content.dischargeDiag, leaveHospitalStructureMap.get(Content.dischargeDiag));
                }
            }
            changxDocs.put(model, changxDoc);
        }
    }

    private void putDoc(Map<String, String> changxDoc, String title, String content) {
        if (StringUtil.isEmpty(content)) {
            return;
        }
        if (title.contains("、")) {
            title = title.split("、")[1];
        }
        if (changxDoc.containsKey(title)) {
            logger.info(title + "已存在");
            return;
        }
        changxDoc.put(title, content);
    }
}
