package com.yihu.hos.crawler.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.core.datatype.CollectionUtil;
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.adapter.AdapterDataSet;
import com.yihu.hos.crawler.model.config.SysConfig;
import com.yihu.hos.crawler.model.patient.Patient;
import com.yihu.hos.standard.model.adapter.AdapterDatasetModel;
import com.yihu.hos.standard.model.adapter.AdapterDictEntryModel;
import com.yihu.hos.standard.model.adapter.AdapterSchemeVersionModel;
import com.yihu.hos.standard.service.adapter.AdapterDatasetService;
import com.yihu.hos.standard.service.adapter.AdapterSchemeVersionService;
import com.yihu.hos.standard.service.bo.AdapterVersion;
import com.yihu.hos.web.framework.model.DictItem;
import com.yihu.hos.web.framework.util.springutil.SpringBeanUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CrawlerManager {

    private static Logger logger = LoggerFactory.getLogger(CrawlerManager.class);

    private static DataCollectDispatcher dispatch = DataCollectDispatcher.getInstance();
    private static SysConfig sysConfig=SysConfig.getInstance();
    private static Map<String, Map<String, AdapterDataSet>> adapterDataSetVersionMap = new HashMap<>();
    private Map<String, AdapterDataSet> adapterDataSetMap;
    private Boolean adapterFlg = false;
    private String schemeVersion;
    private List<DictItem> datasetList;
    public CrawlerManager(List datasetList, String schemeVersion) {
        this.datasetList = datasetList;
        this.schemeVersion = schemeVersion;
    }
    public CrawlerManager() {
    }

    public void finalize() throws Throwable {

    }

    public String dataCrawler(Map<String, Object> condition) {
        Integer count = 0;
        Integer totalCount = 0;
        String message;
        /**
         * 适配基本数据准备
         */
        if (!getDataForPrepare()) {
            message = "适配数据尚未准备";
            logger.error(message);
            return message;
        }

        List<Patient> patientList = dispatch.getPatientList(condition, adapterDataSetMap);
        if (!CollectionUtil.isEmpty(patientList)) {
            totalCount = patientList.size();
            for (Patient patient : patientList) {
                Boolean result = collectProcess(patient);
                if (result) {
                    count++;
                }
            }
        }
        message = "本次采集病人共" + totalCount + "条,成功采集信息"+ count + "条";
        return message;
    }

    //单个病人采集上传
    public Boolean collectProcess(Patient patient) {
        if (!getDataForPrepare()) {
            logger.error("适配数据尚未准备");
            return false;
        }
        patient.setReUploadFlg(StringUtil.toString(false));
        logger.trace("采集->注册->打包上传,patient_id:" + patient.getPatientId() + ", event_no:" + patient.getEventNo());
        try {
            //getToken
            if (!dispatch.getToken()) {
                logger.error("token获取失败");
                return false;
            }

            //getRemoteVersion
//            if (!dispatch.getRemoteVersion(patient.getOrgCode())) {
//                logger.error("远程版本获取失败");
//                return false;
//            }

            if(StringUtil.isEmpty(sysConfig.getVersionMap().get(patient.getOrgCode()))){
                logger.error("版本获取失败");
                return false;
            }

            Map<String, AdapterDataSet> dataSetMap = new HashMap<>();
            Map<String, JsonNode> dataMap = new HashMap<>();
            for (String key : adapterDataSetMap.keySet()) {
                /**
                 * 获取数据
                 */
                AdapterDataSet adapterDataSet = adapterDataSetMap.get(key);
                JsonNode jsonObject = dispatch.fecthData(patient, adapterDataSet);
                if (StringUtil.isEmpty(jsonObject)) {
                    continue;
                }
                dataSetMap.put(adapterDataSet.getAdapterDataSetT().getStdDatasetCode(), adapterDataSet);
                dataMap.put(key, jsonObject);
                /**
                 * 注册病人
                 */
                if (SysConfig.getInstance().getRegisterDataSet().equals(adapterDataSet.getAdapterDataSetT().getStdDatasetCode())) {
                    if (!StringUtil.isEmpty(jsonObject.get("data")) && !StringUtil.isEmpty(jsonObject.get("data").get(0))) {
                        if (!StringUtil.isEmpty(jsonObject.get("data").get(0).get(SysConfig.getInstance().getRegisterIdCardNo()))) {
                            logger.info("注册病人");
                            dispatch.register(patient, jsonObject.toString());
                        }
                    }
                }
            }
            logger.info("采集病人成功,patient_id:" + patient.getPatientId() + ", event_no:" + patient.getEventNo());
            //上传档案
            logger.info("上传病人档案");
            try {
                if (!CollectionUtil.isEmpty(dataMap.keySet())) {
                    if (!dispatch.upload(dataMap, patient, dataSetMap)) {
                        logger.error("上传档案失败");
                        return false;
                    }
                }
            } catch (Exception e) {
                logger.error("档案上传失败,patient_id:" + patient.getPatientId() + ", event_no:" + patient.getEventNo());
                return false;
            }
        } catch (Exception e) {
            logger.error("采集病人失败,patient_id:" + patient.getPatientId() + ", event_no:" + patient.getEventNo(), e);
            return false;
        }
        return true;
    }

    public Boolean getDataForPrepare() {
        if (adapterFlg) {
            return true;
        }
        logger.info("适配基本相关数据准备");
        try {
            adapterDataSetMap = new HashMap<>();
            AdapterVersion adapterVersion;
            AdapterDatasetService adapterDatasetService = SpringBeanUtil.getService(AdapterDatasetService.BEAN_ID);
            List<AdapterDatasetModel> adapterDataSetModelList = new ArrayList<>();
            if (!CollectionUtil.isEmpty(datasetList)) {
                /**
                 * 拉模式接口调用，由任务配置决定适配版本
                 */
                adapterVersion = new AdapterVersion(schemeVersion);
                List<Integer> datasetIdList = new ArrayList<>();
                for (DictItem dictItem : datasetList) {
                    datasetIdList.add(Integer.parseInt(dictItem.getCode()));
                }
                adapterDataSetModelList = adapterDatasetService.getAdapterDatasetByAdapterIdList(adapterVersion, datasetIdList);
            } else {
                /**
                 * 推模式接口调用，默认只使用最新版本的适配
                 */
                AdapterSchemeVersionService adapterSchemeVersionService = SpringBeanUtil.getService(AdapterSchemeVersionService.BEAN_ID);
                AdapterSchemeVersionModel adapterSchemeVersionModel = adapterSchemeVersionService.getEhrAdapterVersionLasted();
                if (adapterSchemeVersionModel == null) {
                    logger.error("获取最新ehr适配版本错误");
                    return false;
                } else {
                    this.schemeVersion = adapterSchemeVersionModel.getVersion();
                    adapterVersion = new AdapterVersion(schemeVersion);
                }
                if (adapterDataSetVersionMap.get(schemeVersion) != null) {
                    adapterDataSetMap = adapterDataSetVersionMap.get(schemeVersion);
                    adapterFlg = true;
                    return true;
                }
                Map<String, String> condition = new HashMap<>();
                condition.put("column", "adapter_dataset_code");
                ObjectMapper mapper = new ObjectMapper();
                String conditionStr = mapper.writeValueAsString(condition);
                adapterDataSetModelList = adapterDatasetService.getAdapterDatasetNotNullList(adapterVersion, conditionStr);
            }

            /**
             * 字典项初始化
             */
            List<AdapterDictEntryModel> adapterDictEntryModelList = adapterDatasetService.getList(AdapterDictEntryModel.class, adapterVersion.getDictEntryTableName(), null, null, null, null);
            Map<Integer, List<AdapterDictEntryModel>> adapterDictEntryModelMap = new HashMap<>();
            for (AdapterDictEntryModel adapterDictEntryModel : adapterDictEntryModelList) {
                List<AdapterDictEntryModel> entryModelList = adapterDictEntryModelMap.get(adapterDictEntryModel.getStdDictId());
                if (CollectionUtil.isEmpty(entryModelList)) {
                    entryModelList = new ArrayList<>();
                }
                entryModelList.add(adapterDictEntryModel);
                adapterDictEntryModelMap.put(adapterDictEntryModel.getStdDictId(), entryModelList);
            }
            /**
             * 数据集初始化
             */
            for (AdapterDatasetModel adapterDatasetModel : adapterDataSetModelList) {
                adapterDataSetMap.put(adapterDatasetModel.getStdDatasetCode(), new AdapterDataSet(adapterDatasetModel, adapterVersion, adapterDictEntryModelMap));
            }
            adapterDataSetVersionMap.put(schemeVersion, adapterDataSetMap);
            adapterFlg = true;
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 解析病人索引信息
     *
     * @param patientInfo 病人索引信息
     * @return
     */
    public Patient parsePatient(String patientInfo) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            Patient patient = mapper.readValue(patientInfo, Patient.class);
            return patient;
        } catch (Exception e) {
            logger.error("patient参数错误：" + patientInfo, e);
            return null;
        }
    }

    public void setSchemeVersion(String schemeVersion) {
        this.schemeVersion = schemeVersion;
    }

    public void setDatasetList(List<DictItem> datasetList) {
        this.datasetList = datasetList;
    }
}
