package com.lantone.qc.kernel.util;

import com.lantone.qc.pub.jdbc.MysqlJdbc;
import com.lantone.qc.pub.util.PropertiesUtil;
import com.lantone.qc.security.util.CryptUtil;
import com.lantone.qc.security.util.EncrypDES;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * Created by louhr on 2019/8/16.
 */
public class CacheFileManager {
    Logger logger = LoggerFactory.getLogger(CacheFileManager.class);

    private String user;
    private String password;
    private String url;

    private static String hospitalId = "2";

    private String path = "";

    public static void main(String[] args) {
        CacheFileManager cacheFileManager = new CacheFileManager();
        String p = cacheFileManager.getClass().getResource("/").getPath();
        p = p.substring(0, p.indexOf("/target/")) + "/src/main/resources/cache/"+ hospitalId + "/";
        File file = new File(p);
        if (!file.exists()) {
            file.mkdir();
        }
        cacheFileManager.createCacheFile(p);
    }

    public CacheFileManager() {
        try {
            PropertiesUtil propertiesUtil = new PropertiesUtil("kernel.properties");
//            EncrypDES encrypDES = new EncrypDES();
//            user = encrypDES.decryptor(propertiesUtil.getProperty("mysql.redis.user"));
//            password = encrypDES.decryptor(propertiesUtil.getProperty("mysql.redis.password"));
//            url = encrypDES.decryptor(propertiesUtil.getProperty("mysql.redis.url"));
            user = propertiesUtil.getProperty("mysql.redis.user");
            password = propertiesUtil.getProperty("mysql.redis.password");
            url = propertiesUtil.getProperty("mysql.redis.url");
        } catch (Exception e) {
            logger.info("数据库连接信息出错...." + e.getMessage());
        }
    }

    public void createCacheFile(String path) {
        MysqlJdbc nlpJdbc = new MysqlJdbc(user, password, url);
        Connection conn = nlpJdbc.connect();
        Statement st = null;
        ResultSet rs = null;
        String r1, r2, r3, r4, r5;
        try {
            EncrypDES encrypDES = new EncrypDES();
            st = conn.createStatement();
            //疾病相關特征
            String sql = "select drf.diagnose, group_concat(feature) feature_name from kl_relevant_feature drf group by diagnose";
            Map<String, String> map = new HashMap<>();
            rs = st.executeQuery(sql);
            while (rs.next()) {
                r1 = rs.getString(1);
                r2 = rs.getString(2);
                r2 = r2 == null ? "" : r2;
                map.put(r1, r2);
            }

            //所有词典库 不能用concat_group 大小写不区分
            sql = "select dis.name, dis.is_chronic, dis.is_infections, dis.name group_name from kl_disease dis where hospital_id = " + hospitalId + " order by name";

            FileWriter fw = new FileWriter(path + "concept_diag_properties.dict");
            rs = st.executeQuery(sql);
            while (rs.next()) {
                r1 = rs.getString(1);
                r2 = rs.getString(2);
                r3 = rs.getString(3);
                r4 = rs.getString(4);

//                r1 = CryptUtil.decrypt_char(r1==null?"":r1);
                r1 = r1==null?"":r1;
                r2 = r2==null?"0":r2;
                r3 = r3==null?"0":r3;
//                r4 = CryptUtil.decrypt_char(r4==null?"":r4);
                r4 = r4==null?"":r4;
                r5 = map.get(r1) == null ? "" : map.get(r1);

                fw.write(encrypDES.encrytor(r1 + "|" + r2 + "|" + r3 + "|" + r4 + "|" + r5));
                fw.write("\n");
            }
            fw.close();

            //需要部位的症状信息
            sql = "select name from kl_clinic  where has_bodypart = '1'";

            fw = new FileWriter(path + "concept_clinic_bodypart_properties.dict");
            rs = st.executeQuery(sql);
            while (rs.next()) {
                r1 = rs.getString(1);
//                r1 = CryptUtil.decrypt_char(r1==null?"":r1);
                r1 = r1==null?"":r1;

                fw.write(encrypDES.encrytor(r1));
                fw.write("\n");
            }
            fw.close();

            //医院疾病信息
            sql = "select name from kl_disease where hospital_id = " + hospitalId;

            fw = new FileWriter(path + "hospital_diag_info.dict");
            rs = st.executeQuery(sql);
            while (rs.next()) {
                r1 = rs.getString(1);
//                r1 = CryptUtil.decrypt_char(r1==null?"":r1);
                r1 = r1==null?"":r1;

                fw.write(encrypDES.encrytor(r1));
                fw.write("\n");
            }
            fw.close();

            //医院医生信息
            sql = "select doctor_id, name, dept_id, professor, occup from bas_doctor_info where hospital_id = " + hospitalId + " order by occup asc";

            fw = new FileWriter(path + "hospital_doctor_info.dict");
            rs = st.executeQuery(sql);
            while (rs.next()) {
                r1 = rs.getString(2);
                r2 = rs.getString(3);
                r3 = rs.getString(4);
                r4 = rs.getString(5);
//                r1 = CryptUtil.decrypt_char(r1==null?"":r1);
                if (StringUtils.isEmpty(r1)) {
                    continue;
                }
                r1 = r1==null?"":r1;
                r2 = r2==null?"":r2;
                r3 = r3==null?"":r3;
                r4 = r4==null?"":r4;

                fw.write(encrypDES.encrytor(r1+ "|" + r2 + "|" + r3 + "|" + r4));
                fw.write("\n");
            }
            fw.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (SQLException sqle) {
            sqle.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            nlpJdbc.close(rs, st, conn);
        }
    }

    public void insertFeature(List<String> record, String tableName, String col) {
        MysqlJdbc nlpJdbc = new MysqlJdbc(user, password, url);

        List<String> hasLabelsList = new ArrayList<>();
        List<Map<String, String>> queryResult = nlpJdbc.query(tableName, new String[]{"name"});
        for (Map<String, String> map : queryResult) {
            hasLabelsList.add(map.get(col));
        }
        List<Map<String, Object>> data = new ArrayList<>();
        for (String s : record) {
            Map<String, Object> obj = new HashMap<>();
            if (!hasLabelsList.contains(s)) {
                obj.put(col, s);
                data.add(obj);
            }
        }
        nlpJdbc.insert(data, tableName, new String[]{col});
    }
}
