package com.yihu.hos.crawler.format;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.standard.model.adapter.AdapterDatasetModel;
import com.yihu.hos.standard.model.adapter.AdapterMetadataModel;
import com.yihu.hos.standard.model.adapter.AdapterSchemeVersionModel;
import com.yihu.hos.standard.service.adapter.AdapterDatasetService;
import com.yihu.hos.standard.service.bo.AdapterVersion;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 适配方案
 * 一个适配方案可能有一到多个机构要采集数据
 *
 * @created Created by Air on 2015/6/3.
 */
public class AdapterScheme  extends AdapterBase{

    @Resource(name = AdapterDatasetService.BEAN_ID)
    private AdapterDatasetService adapterDatasetService;

    private HashMap<String, List<AdapterMetadataModel>> adapterMetaDataMap;


    public AdapterScheme() {

    }

    public synchronized HashMap<String, List<AdapterMetadataModel>> getAdapterMetaDataMap() {
        if (adapterMetaDataMap ==null){
            AdapterSchemeVersionModel adapterSchemeVersionModel = getAdapterSchemeVersionService().getEhrAdapterVersionLasted();
            if (adapterSchemeVersionModel == null) {
                adapterSchemeVersionModel=new AdapterSchemeVersionModel();
            }
            String version = adapterSchemeVersionModel.getVersion();
            AdapterVersion adapterVersion = new AdapterVersion(version);
            adapterMetaDataMap =new HashMap<>();
            Map<String, String> condition = new HashMap<>();
            condition.put("column", "adapter_dataset_code");
            String conditionStr ="";
            ObjectMapper mapper = new ObjectMapper();
            try {
                conditionStr = mapper.writeValueAsString(condition);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            List<AdapterDatasetModel> adapterDataSets = adapterDatasetService.getAdapterDatasetNotNullList(adapterVersion, conditionStr);
            for (AdapterDatasetModel adapterDataSet:adapterDataSets){
                List<AdapterMetadataModel> adapterMetaDataTList = getAdapterMetadataService().getAdapterMetadataByDataset(version, adapterDataSet.getId());
                if (adapterMetaDataTList!=null && adapterMetaDataTList.size()>0){
                    adapterMetaDataMap.put(adapterDataSet.getStdDatasetCode(), adapterMetaDataTList);
                }
            }
        }
        return adapterMetaDataMap;
    }

    public List<AdapterMetadataModel> getAdapterMetaDatas(String dataSetCode){
        if (dataSetCode==null){
            return new ArrayList<>();
        }
        return getAdapterMetaDataMap().get(dataSetCode);

    }

}
