package com.yihu.hos.standard.service.adapter;


import com.fasterxml.jackson.databind.JsonNode;
import com.yihu.hos.core.datatype.CollectionUtil;
import com.yihu.hos.core.datatype.StringUtil;
import com.yihu.hos.standard.dao.IStdDataSetModelDao;
import com.yihu.hos.standard.dao.IStdMetaDataModelDao;
import com.yihu.hos.standard.match.matchModel.MetadataMatchVO;
import com.yihu.hos.standard.match.metadata.MetadataStrategyExecute;
import com.yihu.hos.standard.match.metadata.MetatdataStandardNameStrategy;
import com.yihu.hos.standard.model.adapter.AdapterDatasetModel;
import com.yihu.hos.standard.model.adapter.AdapterDictModel;
import com.yihu.hos.standard.model.adapter.AdapterMetadataModel;
import com.yihu.hos.standard.model.adapter.AdapterSchemeVersionModel;
import com.yihu.hos.standard.model.standard.StdDataSetModel;
import com.yihu.hos.standard.model.standard.StdMetaDataModel;
import com.yihu.hos.standard.service.bo.AdapterVersion;
import com.yihu.hos.standard.service.bo.StandardVersion;
import com.yihu.hos.standard.service.standard.StdMetadataService;
import com.yihu.hos.standard.util.GetChineseFirst;
import com.yihu.hos.web.framework.constant.ErrorCode;
import com.yihu.hos.web.framework.constant.SqlConstants;
import com.yihu.hos.web.framework.dao.SQLGeneralDAO;
import com.yihu.hos.web.framework.exception.ApiException;
import com.yihu.hos.web.framework.model.DetailModelResult;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.web.framework.model.TreeView;
import com.yihu.hos.web.framework.util.springutil.SpringBeanUtil;
import com.yihu.hos.web.framework.util.sql.BeanTransformer;
import com.yihu.hos.web.framework.util.sql.SqlCreator;
import org.apache.commons.collections.CollectionUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Transactional
@Service("AdapterDatasetService")
public class AdapterDatasetService extends SQLGeneralDAO {

    public static final String BEAN_ID = "AdapterDatasetService";

    @Autowired
    private AdapterMetadataService adapterMetadataService;

    @Autowired
    private AdapterSchemeVersionService adapterSchemeVersionService;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    private IStdMetaDataModelDao stdMetaDataModelDao;

    @Autowired
    private IStdDataSetModelDao stdDataSetModelDao;

    @Autowired
    private StdMetadataService stdMetadataService;

    private AdapterDatasetService adapterDatasetService;

    public AdapterDatasetService() {
    }

    public void finalize() throws Throwable {
        super.finalize();
    }

    public Result add(String adapterVersion, String dataset) {
        try {
            AdapterVersion version = new AdapterVersion(adapterVersion);
            AdapterDatasetModel adapterDatasetModel = objectMapper.readValue(dataset, AdapterDatasetModel.class);
            adapterDatasetModel.setId(getMaxId(version.getDataSetTableName()));
            JsonNode jsonNode = objectMapper.readTree(objectMapper.writeValueAsString(adapterDatasetModel));
            SqlCreator sqlCreator = new SqlCreator(AdapterDatasetModel.class);
            String sql = sqlCreator.insertData(version.getDataSetTableName(), jsonNode);
            Query query = getExeuteQuery(sqlCreator, sql);
            query.executeUpdate();
            adapterDatasetModel.setSuccessFlg(true);
            adapterDatasetModel.setMessage("保存适配数据集成功");
            return adapterDatasetModel;
        } catch (Exception e) {
            return Result.error("保存适配数据集失败");
        }
    }

    public Result delete(String adapterVersion, Integer datasetId) {
        try {
            if (adapterVersion == null || adapterVersion.length() == 0) {
                return Result.success("无效适配版本");
            }
            AdapterVersion version = new AdapterVersion(adapterVersion);
            Session session = getCurrentSession();
            String sql = "delete from " + version.getDataSetTableName() + " where id = :id";
            Query query = session.createSQLQuery(sql);
            query.setInteger("id", datasetId);
            query.executeUpdate();
            return Result.success("删除适配数据集成功");
        } catch (Exception e) {
            return Result.error("删除适配数据集失败");
        }
    }

    public Result modify(String adapterVersion, String dataset) {
        try {
            AdapterVersion version = new AdapterVersion(adapterVersion);
            AdapterDatasetModel adapterDatasetModel = objectMapper.readValue(dataset, AdapterDatasetModel.class);
            JsonNode jsonNode = objectMapper.readTree(objectMapper.writeValueAsString(adapterDatasetModel));
            SqlCreator sqlCreator = new SqlCreator(AdapterDatasetModel.class);
            String sql = sqlCreator.updateDataByTableKey(version.getDataSetTableName(), jsonNode);
            Query query = getExeuteQuery(sqlCreator, sql);
            query.executeUpdate();
            adapterDatasetModel.setSuccessFlg(true);
            adapterDatasetModel.setMessage("修改适配数据集成功");
            return adapterDatasetModel;
        } catch (Exception e) {
            return Result.error("修改适配数据集失败");
        }
    }

    public Result get(String version, Integer datasetId) {
        try {
            AdapterVersion adapterVersion = new AdapterVersion(version);
            AdapterDatasetModel adapterDatasetModel = (AdapterDatasetModel) get(AdapterDatasetModel.class, adapterVersion.getDataSetTableName(), datasetId);
            adapterDatasetModel.setSuccessFlg(true);
            adapterDatasetModel.setMessage("获取适配数据集成功");
            return adapterDatasetModel;
        } catch (Exception e) {
            return Result.error("获取适配数据集失败");
        }
    }

    public DetailModelResult getDetailModelResult(String version, String condition, String order, Integer rows, Integer page) {
        try {
            AdapterVersion adapterVersion = new AdapterVersion(version);
            List<AdapterDatasetModel> dataSetModelList = getDatasetList(AdapterDatasetModel.class, version, condition, order, rows, page);
            Integer count = getDatasetInt(AdapterDatasetModel.class, adapterVersion, condition);
            DetailModelResult detailModelResult = DetailModelResult.success("获取适配数据集成功");
            detailModelResult.setDetailModelList(dataSetModelList);
            detailModelResult.setTotalCount(count);
            return detailModelResult;
        } catch (Exception e) {
            return DetailModelResult.error("获取适配数据集失败");
        }
    }

    public List getDatasetList(Class tClass, String version, String condition, String order, Integer limit, Integer offset) throws Exception {
        AdapterVersion adapterVersion = new AdapterVersion(version);
        String tableName = adapterVersion.getDataSetTableName();
        SqlCreator sqlCreator = new SqlCreator(tClass);
        if (!StringUtil.isEmpty(condition)) {
            JsonNode jsonNode = objectMapper.readTree(condition);
            String name = jsonNode.get("name").asText();
            sqlCreator.likeOrCondition("stdDatasetName", "stdDatasetCode", name);
        }
        if (!StringUtil.isEmpty(order)) {
            JsonNode jsonNode = objectMapper.readTree(order);
            Iterator<String> fieldNames = jsonNode.fieldNames();
            while (fieldNames.hasNext()) {
                String fieldName = fieldNames.next();
                String value = jsonNode.get(fieldName).asText().toUpperCase();
                sqlCreator.order(fieldName, value);
            }
        }
        String sql = sqlCreator.selectData(tableName);
        Query query = getQuery(sqlCreator, sql);
        if (limit != null) {
            query.setMaxResults(limit);
            if (offset != null) {
                query.setFirstResult((offset - 1) * limit);
            }
        }
        return query.list();
    }

    public Integer getDatasetInt(Class tClass, AdapterVersion adapterVersion, String condition) {
        try {
            String tableName = adapterVersion.getDataSetTableName();
            SqlCreator sqlCreator = new SqlCreator(tClass);
            if (!StringUtil.isEmpty(condition)) {
                JsonNode jsonNode = objectMapper.readTree(condition);
                String name = jsonNode.get("name").asText();
                sqlCreator.likeOrCondition("stdDatasetName", "stdDatasetCode", name);
            }
            String sql = sqlCreator.countData(tableName);
            Query query = getCurrentSession().createSQLQuery(sql);
            for (String key : sqlCreator.getKeyValueMap().keySet()) {
                query.setParameter(key, sqlCreator.getKeyValueMap().get(key));
            }
            Integer count = Integer.parseInt(StringUtil.toString(query.list().get(0)));
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ApiException(ErrorCode.GetDataSetListFailed);
        }
    }

    public void getAdapterCustomize(String adapterVersion, List<TreeView> treeViewList, List<Integer> hasCheckDatasetIdList, List<Integer> hasCheckMetadataIdList) {
        boolean adapter = false;  //定制是否添加根节点
        //获取所有定制数据集
        AdapterVersion aVersion = new AdapterVersion(adapterVersion);
        List<AdapterDatasetModel> adapterDataSetList = getList(AdapterDatasetModel.class, aVersion.getDataSetTableName(), "", "", null, null);
        List<AdapterMetadataModel> adapterMetaDataList = getList(AdapterMetadataModel.class, aVersion.getMetaDataTableName(), "", "", null, null);
        List<TreeView> adapterCustomizeList = new ArrayList<>();
        //数据集
        for (AdapterDatasetModel adapterDataset : adapterDataSetList) {
            TreeView parent = new TreeView();
            parent.setId("AD" + adapterDataset.getStdDatasetId());
            parent.setPid("A0");
            parent.setText(adapterDataset.getStdDatasetName());
            parent.setIschecked(true);
            adapterCustomizeList.add(parent);
            adapter = true;
            hasCheckDatasetIdList.add(adapterDataset.getStdDatasetId());
        }
        //数据元
        for (AdapterMetadataModel adapterMetadat : adapterMetaDataList) {
            TreeView child = new TreeView();
            child.setId("AM" + adapterMetadat.getStdMetadataId());
            child.setPid("AD" + adapterMetadat.getStdDatasetId());
            child.setText(adapterMetadat.getStdMetadataName());
            child.setIschecked(true);
            adapterCustomizeList.add(child);
            adapter = true;
            hasCheckMetadataIdList.add(adapterMetadat.getStdMetadataId());
        }
        //根节点
        if (adapter) {
            TreeView adapterRoot = new TreeView();
            adapterRoot.setId("A0");
            adapterRoot.setPid("-1");
            adapterRoot.setText("数据集");
            adapterRoot.setIschecked(true);
            adapterCustomizeList.add(adapterRoot);
        }
        treeViewList.addAll(adapterCustomizeList);
    }

    public void getStdCustomize(String stdVersion, List<TreeView> treeViewList, List<Integer> hasCheckDatasetIdList, List<Integer> hasCheckMetadataIdList) {
        String id;
        boolean check;     //是否勾选
        boolean std = false;      //标准是否添加根节点
        long childCheckCount;
        long datasetCount = 0;

        //获取所有标准数据集
        StandardVersion sVersion = new StandardVersion(stdVersion);
        List<StdDataSetModel> dataSetList = getList(StdDataSetModel.class, sVersion.getDataSetTableName(), "", "", null, null);
        String idListStr = SqlConstants.EMPTY;
        for (StdDataSetModel dataSet : dataSetList) {
            idListStr += dataSet.getId() + SqlConstants.COMMA;
        }
        Map<Integer, List<StdMetaDataModel>> stdDataSetModelMap = new HashMap<>();
        if (!StringUtil.isEmpty(idListStr)) {
            String tableName = sVersion.getMetaDataTableName();
            SqlCreator sqlCreator = new SqlCreator(StdMetaDataModel.class);
            String sql = sqlCreator.selectData(tableName);
            Query query = getQuery(sqlCreator, sql);
            List<StdMetaDataModel> stdMetaDataModelList = query.list();
            for (StdMetaDataModel stdMetaDataModel : stdMetaDataModelList) {
                List<StdMetaDataModel> stdMetaDataModels = stdDataSetModelMap.get(stdMetaDataModel.getDatasetId());
                if (stdMetaDataModels == null) {
                    stdMetaDataModels = new ArrayList<>();
                }
                stdMetaDataModels.add(stdMetaDataModel);
                stdDataSetModelMap.put(stdMetaDataModel.getDatasetId(), stdMetaDataModels);
            }
        }

        List<TreeView> stdCustomizeList = new ArrayList<>();

        for (StdDataSetModel dataSet : dataSetList) {
            TreeView parent = new TreeView();
            parent.setId("SD" + dataSet.getId());
            parent.setPid("S0");
            parent.setText(dataSet.getName());
            parent.setIschecked(false);
            std = true;
            childCheckCount = 0;
            List<StdMetaDataModel> metaDataList = stdDataSetModelMap.get(dataSet.getId());
            if (!CollectionUtil.isEmpty(metaDataList)) {
                for (StdMetaDataModel metaData : metaDataList) {
                    id = String.valueOf(metaData.getId());
                    if (hasCheckMetadataIdList.contains(metaData.getId())) {
                        check = true;
                        childCheckCount++;
                    } else {
                        check = false;
                    }
                    TreeView child = new TreeView();
                    child.setId("SM" + id);
                    child.setPid("SD" + dataSet.getId());
                    child.setText(metaData.getName());
                    child.setIschecked(check);
                    stdCustomizeList.add(child);
                }
                std = true;
            }
            if (!CollectionUtil.isEmpty(metaDataList) && metaDataList.size() == childCheckCount && childCheckCount > 0) {
                parent.setIschecked(true);//子节点全选
                datasetCount++;
            } else if (CollectionUtil.isEmpty(metaDataList) && hasCheckDatasetIdList.contains(dataSet.getId())) {
                parent.setIschecked(true);
                datasetCount++;
            }
            stdCustomizeList.add(parent);
        }
        //根节点
        if (std) {
            TreeView stdRoot = new TreeView();
            stdRoot.setId("S0");
            stdRoot.setPid("-1");
            stdRoot.setText("数据集");
            if (datasetCount == dataSetList.size()) {
                stdRoot.setIschecked(true);
            } else {
                stdRoot.setIschecked(false);
            }

            stdCustomizeList.add(stdRoot);
        }
        treeViewList.addAll(stdCustomizeList);
    }

    public DetailModelResult getDatasetCustomize(String adapterVersion, String stdVersion) {

        try {
            List<TreeView> treeViewList = new ArrayList<>();
            List<Integer> hasCheckDatasetIdList = new ArrayList<>();
            List<Integer> hasCheckMetadataIdList = new ArrayList<>();
            getAdapterCustomize(adapterVersion, treeViewList, hasCheckDatasetIdList, hasCheckMetadataIdList);
            getStdCustomize(stdVersion, treeViewList, hasCheckDatasetIdList, hasCheckMetadataIdList);
            DetailModelResult detailModelResult = DetailModelResult.success("获取定制数据集列表成功");
            detailModelResult.setDetailModelList(treeViewList);
            return detailModelResult;
        } catch (Exception e) {
            return DetailModelResult.error("获取定制数据集列表失败");
        }
    }

    public Result updateCustomize(Integer schemeId, String adapterVersion, String stdVersion, String datasetIdStr, String metaDataIdStr) {
        AdapterVersion aVersion = new AdapterVersion(adapterVersion);
        StandardVersion sVersion = new StandardVersion(stdVersion);
        try {
            String[] datasetIdList = datasetIdStr.split(",");
            String[] metadataIdList = metaDataIdStr.split(",");
            List<Integer> newDatasetIdList = new ArrayList<>();
            List<Integer> newMetadataIdList = new ArrayList<>();

            for (String datasetId : datasetIdList) {
                if (!StringUtil.isStrEmpty(datasetId)) {
                    Integer newDatasetId = Integer.parseInt(datasetId);
                    newDatasetIdList.add(newDatasetId);
                }
            }

            for (String metadataId : metadataIdList) {
                if (!StringUtil.isStrEmpty(metadataId)) {
                    Integer newMetadataId = Integer.parseInt(metadataId);
                    newMetadataIdList.add(newMetadataId);
                }
            }

            if (newDatasetIdList.size() == 0) {
                return Result.error("定制内容为空");
            }

            updateDatasetCustomizeData(schemeId, aVersion, sVersion, newDatasetIdList, newMetadataIdList);
            return Result.success("定制数据集成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("定制数据集失败");
        }
    }

    public void updateDatasetCustomizeData(Integer schemeId, AdapterVersion aVersion, StandardVersion sVersion, List<Integer> newDatasetIdList, List<Integer> newMetadataIdList) throws Exception {
        List<StdMetaDataModel> metadataList = new ArrayList<StdMetaDataModel>();
        if (newMetadataIdList.size() > 0) {
            SqlCreator sqlCreator = new SqlCreator(StdMetaDataModel.class);
            sqlCreator.inCondition("id", newMetadataIdList);
            String sql = sqlCreator.selectData(sVersion.getMetaDataTableName());
            Query query = getQuery(sqlCreator, sql);
            metadataList = query.list();
        }

        List<Integer> newDictdList = new ArrayList<>();
        for (StdMetaDataModel stdMetaDataModel : metadataList) {
            if (stdMetaDataModel.getDictId() != null && !newDictdList.contains(stdMetaDataModel.getDictId())) {
                newDictdList.add(stdMetaDataModel.getDictId());
            }
        }

        List<String> insertSqlList = new ArrayList<>();
        // 找出新增 删除  modify by cyj
        List<AdapterDatasetModel> datasetModels = selectData(aVersion.getDataSetTableName(), AdapterDatasetModel.class);
        List<AdapterMetadataModel> metadataModels = selectData(aVersion.getMetaDataTableName(), AdapterMetadataModel.class);
        List<AdapterDictModel> dictModels = selectData(aVersion.getDictTableName(), AdapterDictModel.class);
//        List<AdapterDictEntryModel> dictEntryModels = selectData(aVersion.getDictEntryTableName(), AdapterDictEntryModel.class);
        List<Integer> oldDatasetIdList = new ArrayList<>();
        for (AdapterDatasetModel datasetModel : datasetModels) {
            oldDatasetIdList.add(datasetModel.getId());
        }
        List<Integer> oldMetadataIdList = new ArrayList<>();
        for (AdapterMetadataModel metadataModel : metadataModels) {
            oldMetadataIdList.add(metadataModel.getId());
        }
        List<Integer> oldDictIdList = new ArrayList<>();
        for (AdapterDictModel dictModel : dictModels) {
            oldDictIdList.add(dictModel.getId());
        }
//        List<Integer> oldDictEntryIdList = new ArrayList<>();
//        for (AdapterDictEntryModel entryModel : dictEntryModels) {
//            oldDictEntryIdList.add(entryModel.getStdDictId());
//        }
        Map<String, List<Integer>> datasetMap = getDiffId(newDatasetIdList, oldDatasetIdList);
        Map<String, List<Integer>> metaMap = getDiffId(newMetadataIdList, oldMetadataIdList);
        Map<String, List<Integer>> dicMap = getDiffId(newDictdList, oldDictIdList);
//        Map<String,List<Integer>> dicEntryMap = getDiffId(newDictdList,oldDictEntryIdList);
//        add del
        List<Integer> delDatasetList = datasetMap.get("del");
        if (delDatasetList.size() > 0) {
            insertSqlList.add(delData(aVersion.getDataSetTableName(), "id", delDatasetList));
        }
        List<Integer> delMetaList = metaMap.get("del");
        if (delMetaList.size() > 0) {
            insertSqlList.add(delData(aVersion.getMetaDataTableName(), "id", delMetaList));
        }
        List<Integer> delDicList = dicMap.get("del");
        if (delDicList.size() > 0) {
            insertSqlList.add(delData(aVersion.getDictTableName(), "id", delDicList));
            insertSqlList.add(delData(aVersion.getDictEntryTableName(), "std_dict_id", delDicList));
        }
/*        insertSqlList.add(SqlConstants.DELETE + SqlConstants.FROM + aVersion.getDataSetTableName());
        insertSqlList.add(SqlConstants.DELETE + SqlConstants.FROM + aVersion.getMetaDataTableName());
        insertSqlList.add(SqlConstants.DELETE + SqlConstants.FROM + aVersion.getDictTableName());
        insertSqlList.add(SqlConstants.DELETE + SqlConstants.FROM + aVersion.getDictEntryTableName());*/

        List<Integer> addDataSetList = datasetMap.get("add");
        if (addDataSetList.size() > 0) {
            insertSqlList.add(insertData(aVersion.getDataSetTableName(), sVersion.getDataSetTableName(),
                    new String[]{"id,std_dataset_id,std_dataset_code,std_dataset_name"},
                    new String[]{"id,id,code,name"},
                    schemeId,
                    "id",
                    addDataSetList));
        }
        List<Integer> addMetaList = metaMap.get("add");
        if (addMetaList.size() > 0) {
            insertSqlList.add(insertData(aVersion.getMetaDataTableName(), sVersion.getMetaDataTableName(),
                    new String[]{"id,std_metadata_id,std_metadata_code,std_metadata_name,std_dataset_id,std_dict_id"},
                    new String[]{"id,id,code,name,dataset_id,dict_id"},
                    schemeId,
                    "id",
                    addMetaList));
        }
        List<Integer> addDicList = dicMap.get("add");
        if (addDicList.size() > 0) {
            insertSqlList.add(insertData(aVersion.getDictTableName(), sVersion.getDictTableName(),
                    new String[]{"id,std_dict_id,std_dict_code,std_dict_name"},
                    new String[]{"id,id,code,name"},
                    schemeId,
                    "id",
                    addDicList));
            insertSqlList.add(insertData(aVersion.getDictEntryTableName(), sVersion.getDictEntryTableName(),
                    new String[]{"id,std_entry_id,std_entry_code,std_entry_value,std_dict_id"},
                    new String[]{"id,id,code,value,dict_id"},
                    schemeId,
                    "dict_id",
                    addDicList));
        }

        if (insertSqlList.size() > 0) {
            insertBatch(insertSqlList);
        }

    }

    private String delData(String adapterTableName, String item, List<Integer> idList) {
        StringBuffer sql = new StringBuffer();
        String idStr = SqlConstants.EMPTY;
        for (Integer id : idList) {
            idStr += id + SqlConstants.COMMA;
        }
        if (!StringUtil.isEmpty(idStr)) {
            idStr = SqlConstants.LEFT_BRACKET + idStr.substring(0, idStr.length() - 1) + SqlConstants.RIGHT_BRACKET;
        }
        sql.append(SqlConstants.DELETE + SqlConstants.FROM).append(adapterTableName).append(SqlConstants.WHERE).append(item).append(SqlConstants.IN).append(idStr);
        return sql.toString();
    }

    /**
     * 将第一个数组放入map(id,1) 然后循环第二个数组，如果map中找到对应键值就+1  不存在设置 1
     *
     * @param firtList   new
     * @param secondList old
     */
    private Map<String, List<Integer>> getDiffId(List<Integer> firtList, List<Integer> secondList) {
        Map<Integer, Integer> map = new HashMap<>();
        for (Integer id : firtList) {
            map.put(id, 1);
        }

        for (Integer id1 : secondList) {
            Integer flag = map.get(id1);
            if (flag != null) {
                map.put(id1, ++flag);
            } else {
                map.put(id1, 1);
            }
        }


        List<Integer> diffLs = new ArrayList<>();
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() == 1) {
                diffLs.add(entry.getKey());
            }
        }

        List<Integer> delIDLs = new ArrayList<>();
        List<Integer> addIDLs = new ArrayList<>();
        for (Integer diffL : diffLs) {
            if (firtList.contains(diffL)) {
                addIDLs.add(diffL);
            } else if (secondList.contains(diffL)) {
                delIDLs.add(diffL);
            }
        }
        Map<String, List<Integer>> listMap = new HashMap<>();
        listMap.put("del", delIDLs);
        listMap.put("add", addIDLs);
        return listMap;
    }

    private String insertData(String adapterTableName, String stdTableName, String[] item1, String[] item2, Integer schemeId, String item, List<Integer> idList) {
        StringBuffer sql = new StringBuffer();
        String idStr = SqlConstants.EMPTY;
        for (Integer id : idList) {
            idStr += id + SqlConstants.COMMA;
        }
        if (!StringUtil.isEmpty(idStr)) {
            idStr = SqlConstants.LEFT_BRACKET + idStr.substring(0, idStr.length() - 1) + SqlConstants.RIGHT_BRACKET;
        }

        sql.append(SqlConstants.INSERT_INTO + adapterTableName + SqlConstants.LEFT_BRACKET);
        for (String it : item1) {
            sql.append(it + SqlConstants.COMMA);
        }
        sql.append("scheme_id" + SqlConstants.RIGHT_BRACKET + SqlConstants.LEFT_BRACKET + SqlConstants.SELECT);
        for (String it : item2) {
            sql.append(it + SqlConstants.COMMA);
        }
        sql.append(schemeId + SqlConstants.FROM + stdTableName + SqlConstants.WHERE + item + SqlConstants.IN + idStr + SqlConstants.RIGHT_BRACKET);
        return sql.toString();
    }

    public List selectData(String adapterTableName, Class clazz) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT * FROM ").append(adapterTableName);
        return queryListBySql(sql.toString(), clazz);
    }

    public List getAdapterDatasetNotNullList(AdapterVersion adapterVersion, String condition) {
        try {
            StringBuffer sql = new StringBuffer();
            sql.append("SELECT * FROM ").append(adapterVersion.getDataSetTableName());
            if (!StringUtil.isEmpty(condition)) {
                JsonNode jsonNode = objectMapper.readTree(condition);
                String column = jsonNode.get("column").asText();
                sql.append(" WHERE ").append(column).append(" IS NOT NULL");
            }
            Query query = getCurrentSession().createSQLQuery(sql.toString());
            query.setResultTransformer(new BeanTransformer(AdapterDatasetModel.class));
            return query.list();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public List getListByAdapterDatasetIdList(AdapterVersion adapterVersion, List<Integer> datasetIdList) {
        try {
            if (CollectionUtil.isEmpty(datasetIdList)) {
                return null;
            }
            SqlCreator sqlCreator = new SqlCreator(AdapterDatasetModel.class);
            sqlCreator.inCondition("stdDatasetId", datasetIdList);
            String sql = sqlCreator.selectData(adapterVersion.getDataSetTableName());
            Query query = getQuery(sqlCreator, sql);
            return query.list();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public AdapterDatasetModel getAdapterDatasetByCode(String version, String datasetCode) {
        try {
            if (StringUtil.isEmpty(datasetCode)) {
                return null;
            }
            SqlCreator sqlCreator = new SqlCreator(AdapterDatasetModel.class);
            sqlCreator.equalCondition("stdDatasetCode", datasetCode);
            String sql = sqlCreator.selectData("adapter_dataset_" + version);
            Query query = getQuery(sqlCreator, sql);
            return (AdapterDatasetModel) query.uniqueResult();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public AdapterDatasetModel getAdapterDatasetByCode(String schemaName,String version, String datasetCode) {
        try {
            if (StringUtil.isEmpty(datasetCode)) {
                return null;
            }
            SqlCreator sqlCreator = new SqlCreator(AdapterDatasetModel.class);
            sqlCreator.equalCondition("stdDatasetCode", datasetCode);
            String sql = sqlCreator.selectData("adapter_dataset_" + version);

            String myCatAnnotation = "/*#mycat\\:schema=" + schemaName + "*/ ";
            String completeSql = myCatAnnotation + sql;

            Query query = getQuery(sqlCreator, completeSql);
            return (AdapterDatasetModel) query.uniqueResult();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public List<AdapterDatasetModel> getAdapterDatasetByAdapterIdList(AdapterVersion adapterVersion, List<Integer> datasetIdList) {
        try {
            if (CollectionUtil.isEmpty(datasetIdList)) {
                return null;
            }
            SqlCreator sqlCreator = new SqlCreator(AdapterDatasetModel.class);
            sqlCreator.inCondition("adapterDatasetId", datasetIdList);
            String sql = sqlCreator.selectData(adapterVersion.getDataSetTableName());
            Query query = getQuery(sqlCreator, sql);
            return query.list();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public void strategy(String schemaName,String version,String std_version,String adapter_std_version) throws Exception {
        List<AdapterMetadataModel> unAdapterMetadataModels =  adapterMetadataService.getAllUnAdaptMetadata(schemaName,version);//等待适配的标准数据元
        List<AdapterMetadataModel> adapterMetadataModel = new ArrayList<AdapterMetadataModel>();//之前已经适配好的适配方案
        //获取所有未匹配的
        //查找出  之前已经适配好的适配方案
        List<AdapterSchemeVersionModel> all = adapterSchemeVersionService.getAll(schemaName);
        if(all!=null){
            for(AdapterSchemeVersionModel adapterSchemeVersionModel:all){
                String vers = adapterSchemeVersionModel.getVersion();
                if(org.apache.commons.lang3.StringUtils.isNotBlank(vers)){
                    List<AdapterMetadataModel> adaptMetadata = adapterMetadataService.getAllAdaptMetadata(schemaName,adapterSchemeVersionModel.getVersion());
                    adapterMetadataModel.addAll(adaptMetadata);
                }
            }
        }
        MetadataMatchVO matchVO = new MetadataMatchVO();
        matchVO.setCodeAdapter(matchVO.geNameGroup(adapterMetadataModel));

        //設置匹配的机构数据緩存
        List<StdMetaDataModel> orgMetadatas = stdMetadataService.getList(schemaName,adapter_std_version, null, null, null, null, null);//查找出机构所有的metadatas
        for (StdMetaDataModel stdMetadata:orgMetadatas){
            StdDataSetModel stdDataset = stdDataSetModelDao.getDatasetName(schemaName,adapter_std_version, stdMetadata.getDatasetId());
            if(null != stdDataset){
                MetatdataStandardNameStrategy.getNameMap().put(stdMetadata.getName() + "_" + stdDataset.getName(),stdMetadata);
                MetatdataStandardNameStrategy.getRemarkMap().put(stdMetadata.getDefinition() + "_" + stdDataset.getName(),stdMetadata);
            }
        }

        //执行匹配
        MetadataStrategyExecute.setFirst(version, unAdapterMetadataModels.size());//设置第一次匹配
        Set<String> sqlList = new HashSet<String>();

        for (AdapterMetadataModel unAdapterMetadataModel : unAdapterMetadataModels) {
            threadPoolTaskExecutor.execute(new MetadataStrategyExecute(schemaName,unAdapterMetadataModel, matchVO, std_version,adapter_std_version,version, stdMetaDataModelDao,stdDataSetModelDao,adapterMetadataService));

            String metadataNameFirstCode = GetChineseFirst.cn2py(unAdapterMetadataModel.getStdMetadataName());//待匹配
            List<AdapterMetadataModel> adapterMetadatas = matchVO.getCodeAdapter().get(metadataNameFirstCode);//已存在
            if (adapterMetadatas != null && adapterMetadatas.size() > 0) {
                //获取待适配的数据集名
                Integer unAdaptStdId = unAdapterMetadataModel.getStdDatasetId();
                StdDataSetModel adapterDataset = stdDataSetModelDao.getDatasetName(schemaName,adapter_std_version, unAdaptStdId);
                if (adapterDataset != null) {
                    adapterDatasetService = SpringBeanUtil.getService(AdapterDatasetService.BEAN_ID);
                    AdapterDatasetModel entity = adapterDatasetService.getAdapterDatasetByCode(schemaName,version, adapterDataset.getCode());
                    String sqrSql = null;
                    if(null != entity){
                        sqrSql = adapterDatasetService.saveAdaptDatasetSql(schemaName,entity, adapterDataset, version);
                    }
                    if(null != sqrSql && !"".equals(sqrSql)){
                        sqlList.add(sqrSql);
                    }
                }
            }
        }

        if(CollectionUtils.isNotEmpty(sqlList)){
            List list=new ArrayList();
            Iterator it=sqlList.iterator();
            while(it.hasNext()){
                list.add((String) it.next());
            }
            super.insertBatch(list);
        }
    }


    public void saveAdaptDataset(AdapterDatasetModel strategyDataset,StdDataSetModel orgDataset,String version) throws Exception {
        if(null != strategyDataset){
            strategyDataset.setAdapterDatasetId(orgDataset.getId());
            strategyDataset.setAdapterDatasetCode(orgDataset.getCode());
            strategyDataset.setAdapterDatasetName(orgDataset.getName());
            JsonNode jsonNode = objectMapper.readTree(objectMapper.writeValueAsString(strategyDataset));
            SqlCreator sqlCreator = new SqlCreator(AdapterDatasetModel.class);
            String sql = sqlCreator.updateDataByTableKey(new AdapterVersion(version).getDataSetTableName(), jsonNode);
            Query query = getExeuteQuery(sqlCreator, sql);
            query.executeUpdate();
        }
    }

    public String saveAdaptDatasetSql(AdapterDatasetModel strategyDataset,StdDataSetModel orgDataset,String version) throws Exception {
        StringBuilder sqlBuffer = new StringBuilder();
        sqlBuffer.append(SqlConstants.UPDATE + new AdapterVersion(version).getDataSetTableName() + SqlConstants.SET);
        sqlBuffer.append(" adapter_dataset_id = " + orgDataset.getId());
        sqlBuffer.append(",adapter_dataset_code = '" + orgDataset.getCode() + "'");
        sqlBuffer.append(",adapter_dataset_name = '" + orgDataset.getName() + "'");
        sqlBuffer.append(" where id=" + strategyDataset.getId());
        return sqlBuffer.toString();
    }

    public String saveAdaptDatasetSql(String schemaName,AdapterDatasetModel strategyDataset,StdDataSetModel orgDataset,String version) throws Exception {
        StringBuilder sqlBuffer = new StringBuilder();
        sqlBuffer.append(SqlConstants.UPDATE + new AdapterVersion(version).getDataSetTableName() + SqlConstants.SET);
        sqlBuffer.append(" adapter_dataset_id = " + orgDataset.getId());
        sqlBuffer.append(",adapter_dataset_code = '" + orgDataset.getCode() + "'");
        sqlBuffer.append(",adapter_dataset_name = '" + orgDataset.getName() + "'");
        sqlBuffer.append(" where id=" + strategyDataset.getId());

        String myCatAnnotation = "/*#mycat\\:schema=" + schemaName + "*/ ";
        String completeSql = myCatAnnotation + sqlBuffer;

        return completeSql;
    }
}