package com.yihu.hos.crawler.model.config;

import com.yihu.hos.core.datatype.StringUtil;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import com.yihu.hos.crawler.model.patient.PatientIdentity;
import com.yihu.hos.crawler.model.patient.PatientIndex;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SysConfig {

    private static Logger logger = LoggerFactory.getLogger(SysConfig.class);
    public static final String HOS_RESOURCES_CONFIG = "/config/sys.config.xml";
    private static volatile SysConfig instance = null;
    private HashMap<String, PatientIdentity> patientIdentityHashMap;
    private Map<String, PatientIndex> patientIndexMap;//病人摘要信息内容
    private Map<String, String> publicKeyMap;
    private Map<String, String> versionMap;
    public static String tempFile;
    public static String orgcode;
    public static String registerDataSet;
    public static String registerIdCardNo;

    private SysConfig() {
        patientIdentityHashMap = new HashMap<>();
        patientIndexMap = new HashMap<>();
        publicKeyMap = new HashMap<>();
        versionMap = new HashMap<>();
        init();
    }

    public static SysConfig getInstance() {
        if (instance == null) {
            synchronized (SysConfig.class) {
                if (instance == null) {
                    try {
                        instance = new SysConfig();
                    } catch (Exception e) {
                        e.printStackTrace();

                    }
                }
            }
        }

        return instance;
    }

    public void finalize() throws Throwable {

    }

    public String getTempFile() {
        return this.tempFile;
    }

    public void setTempFile(String tempFile) {
        this.tempFile = tempFile;
    }

    public PatientIdentity getPatientIdentity(String dataSetCode) {
        return patientIdentityHashMap.get(dataSetCode);
    }

    public HashMap<String, PatientIdentity> getPatientIdentityHashMap() {
        return patientIdentityHashMap;
    }

    public String getRegisterDataSet() {
        return registerDataSet;
    }

    public String getRegisterIdCardNo() {
        return registerIdCardNo;
    }

    public Map<String, PatientIndex> getPatientIndexMap() {
        return patientIndexMap;
    }

    public Map<String, String> getPublicKeyMap() {
        return publicKeyMap;
    }

    public Map<String, String> getVersionMap() {
        return versionMap;
    }

    public void setVersionMap(Map<String, String> versionMap) {
        this.versionMap = versionMap;
    }

    private Document getDocument() throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            InputStream inputStream = SysConfig.class.getResourceAsStream(HOS_RESOURCES_CONFIG);
            document = reader.read(inputStream);
            return document;
        } catch (DocumentException de) {
            logger.info("读取classpath下的xml文档路径发生异常");
            return null;
        }
    }

    private void init() {
        try {
            Document document = this.getDocument();
            Element rootElement = null;
            if (document != null) {
                rootElement = document.getRootElement();
            }

            if (rootElement == null) {
                return;
            }

            this.initCrawler(rootElement);
            this.initEventNo(rootElement);
            this.initVersion(rootElement);
//            this.initPatientIndex(rootElement);
        } catch (Exception e) {
            logger.error(e.getCause().toString());
        }
    }

    private void initVersion(Element rootElement){
        String tempFile = rootElement.elementTextTrim("temp_file");
        if (!StringUtil.isEmpty(tempFile)) {
            this.tempFile = tempFile;
        } else {
            String home = System.getProperty("catalina.home").replace('\\','/');
            String homeUrl = home.substring(0,home.lastIndexOf('/')+1);
            this.tempFile = homeUrl + "temp";
        }
        List queueDataSets = rootElement.element("ehr_version").elements("org_code");
        for (Object obj : queueDataSets) {
            if (obj instanceof Element) {
                Element element = (Element) obj;
                String dataSetCode = element.attributeValue("code");
                String version = element.elementTextTrim("version");

                String ehrVersion=new String(version);
                versionMap.put(dataSetCode,ehrVersion);
            }
        }

        Element registerDataSet = rootElement.element("register").element("dataset");
        this.registerDataSet = registerDataSet.attributeValue("code");
        this.registerIdCardNo = registerDataSet.elementTextTrim("id_card");
    }

    private void initCrawler(Element rootElement) {
        String tempFile = rootElement.elementTextTrim("temp_file");
        if (!StringUtil.isEmpty(tempFile)) {
            this.tempFile = tempFile;
        } else {
            String home = System.getProperty("catalina.home").replace('\\','/');
            String homeUrl = home.substring(0,home.lastIndexOf('/')+1);
            this.tempFile = homeUrl + "temp";
        }
        List queueDataSets = rootElement.element("patient_queue").elements("dataset");
        for (Object obj : queueDataSets) {
            if (obj instanceof Element) {
                Element element = (Element) obj;
                String dataSetCode = element.attributeValue("code");
                String eventNo = element.elementTextTrim("event_no");
                String refTime = element.elementTextTrim("ref_time");

                PatientIdentity patientIdentity = new PatientIdentity(eventNo, refTime);
                patientIdentityHashMap.put(dataSetCode, patientIdentity);
            }
        }

        Element registerDataSet = rootElement.element("register").element("dataset");
        this.registerDataSet = registerDataSet.attributeValue("code");
        this.registerIdCardNo = registerDataSet.elementTextTrim("id_card");
    }

    private void initEventNo(Element rootElement) {
        List eventItems = rootElement.element("event_no").elements("item");
        for (Object obj : eventItems) {
            if (obj instanceof Element) {
                Element element = (Element) obj;
                String eventNoCode = element.getTextTrim();
                PatientIdentity.addEventNoCode(eventNoCode);
            }
        }
    }
}//end SysConfig