package com.lantone.qc.kernel;


import com.lantone.qc.pub.jdbc.MysqlJdbc;
import com.lantone.qc.pub.util.PropertiesUtil;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;

/**
 * @ClassName : ImportTaizTestData
 * @Description :
 * @Author : 楼辉荣
 * @Date: 2020-03-28 09:51
 */
public class ImportTaizDataTest {
    private static Map<String, String> modelInfoMap = new HashMap<>();

    public static void main(String[] args) {
        ImportTaizDataTest importTaizDataTest = new ImportTaizDataTest();
//        String filePath = "E:\\docs\\产品目录\\病历质控\\病历数据\\台州\\质控医院数据采集标准格式20200326.xls";

        String filePath = "E:\\docs\\产品目录\\病历质控\\病历数据\\长兴\\入院记录";
        try {
            List<Map<String, Object>> patientInserts = new ArrayList<>();
            List<Map<String, Object>> modelMappingInserts = new ArrayList<>();

            Set<String> patients = new LinkedHashSet<>();
            Map<String, Map<String, List<String>>> records = importTaizDataTest.readFromTxt(filePath);
            for (Map.Entry<String, Map<String, List<String>>> entry : records.entrySet()) {
                for (Map.Entry<String, List<String>> modelEntry : entry.getValue().entrySet()) {
                    for (String s : modelEntry.getValue()) {
                        String text = "";
                        Map<String, Object> rowMap = new HashMap<>();
                        rowMap.put("mode_id", modelInfoMap.get(modelEntry.getKey()));
                        rowMap.put("origin_text", s);
                        /*if (StringUtils.isNotEmpty(s)) {
                            Map<String, String> textMap = CxXmlUtil.beHospitalizedXmlToMap(s);
                            for (Map.Entry<String, String> e : textMap.entrySet()) {
                                text = text + "【" + e.getKey() + "】：" + e.getValue() + "\n";
                            }
                        }*/
                        rowMap.put("case_number", entry.getKey());
                        rowMap.put("text", text);
                        modelMappingInserts.add(rowMap);
                    }
                }
                patients.add(entry.getKey());
            }

            for (String patientSerial : patients) {
                Map<String, Object> patientSerialMap = new HashMap<>();
                patientSerialMap.put("case_number", patientSerial);
                patientSerialMap.put("hospital_id", "1");
                patientInserts.add(patientSerialMap);
            }

            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"));
            mysqlJdbc.insert(patientInserts, "qc_cases_number", new String[]{"hospital_id", "case_number"});
            mysqlJdbc.insert(modelMappingInserts, "qc_model_mapping", new String[]{"case_number", "origin_text", "mode_id", "text"});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Map<String, Map<String, List<String>>> readFromTxt(String filePath) throws Exception {
        initData();
        Map<String, Map<String, List<String>>> result = new HashMap<>();
        File file = new File(filePath);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8"), 512);
                List<String> list = new ArrayList<>();

                String theWord = "";
                String content = "";
                do {
                    theWord = br.readLine();
                    if (theWord != null && !"".equals(theWord.trim())) {
                        content = content + theWord;
                    }
                } while (theWord != null);

                list.add(content);

                Map<String, List<String>> map = new HashMap<>();
                map.put("入院记录", list);

                result.put(f.getName().substring(0, f.getName().indexOf(".")), map);
            }
        }
        return result;
    }

    private Map<String, Map<String, List<String>>> readFromExcel(String filePath) throws Exception {
        Map<String, Map<String, List<String>>> excelDataMap = new HashMap<>();
        //创建输入流
        InputStream stream = new FileInputStream(filePath);
        //获取Excel文件对象
        Workbook rwb = Workbook.getWorkbook(stream);
        //获取文件的指定工作表 默认的第一个
        Sheet sheet = rwb.getSheet(0);
        //行数(表头的目录不需要，从1开始)
        String patientSerial = "";
        Map<String, List<String>> modelMap = initData();
        for (int i = 1; i < sheet.getRows(); i++) {
            Cell patientCell = sheet.getCell(0, i);
            Cell modelCell = sheet.getCell(1, i);
            Cell contentCell = sheet.getCell(2, i);
            modelMap.get(modelCell.getContents()).add(contentCell.getContents());
            if (StringUtils.isNotEmpty(patientSerial) && !patientSerial.equals(patientCell.getContents())) {
                excelDataMap.put(patientSerial, modelMap);
                modelMap = initData();
            }
            patientSerial = patientCell.getContents();
        }
        excelDataMap.put(patientSerial, modelMap);
        return excelDataMap;
    }

    private Map<String, List<String>> initData() {
        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 conn = mysqlJdbc.connect();
        Statement st = null;
        ResultSet rs = null;
        String r1, r2;
        List<String> modeNamesList = new ArrayList<>();
        try {
            st = conn.createStatement();
            String sql = "select id, name from qc_mode";
            rs = st.executeQuery(sql);
            while (rs.next()) {
                r1 = rs.getString(1);
                r2 = rs.getString(2);
                modelInfoMap.put(r2, r1);
                modeNamesList.add(r2);
            }
        } catch (SQLException sqle) {
            sqle.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            mysqlJdbc.close(rs, st, conn);
        }
        Map<String, List<String>> map = new HashMap<>();
        modeNamesList.stream().forEach(x ->
                map.put(x, new ArrayList<String>()));
        return map;
    }
}