package com.yihu.hos.rest.services.standard.standard;

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.rest.models.standard.bo.StandardVersion;
import com.yihu.hos.rest.models.standard.standard.StandardVersionModel;
import com.yihu.hos.rest.models.standard.standard.StdDataSetModel;
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.util.sql.BeanTransformer;
import com.yihu.hos.web.framework.util.sql.RequestParamTransformer;
import com.yihu.hos.web.framework.util.sql.SqlCreator;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;


/**
 * 数据集管理器.
 *
 * @author Sand
 * @version 1.0
 * @created 30-6月-2015 16:19:05
 */
@Transactional
@Service("StdDatasetService")
public class StdDatasetService extends SQLGeneralDAO {

    public static final String BEAN_ID = "StdDatasetService";
    @Autowired
    StandardService standardService;

    public StdDatasetService() {
    }

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

    public List<StdDataSetModel> getList(String stdVersion, String condition, String order, Integer limit, Integer offset) {
        try {
            Map queryMap = RequestParamTransformer.parseJsonToMap(condition);
            Map orderMap = RequestParamTransformer.parseJsonToMap(order);
            StandardVersion standardVersion = new StandardVersion(stdVersion);
            return this.getList(standardVersion, queryMap, orderMap, limit, offset);
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new ApiException(ErrorCode.StandardDatasetGetListFailed);
    }

    public Result add(String stdVersion, String dataset) {
        if (StringUtil.isEmpty(stdVersion)) {
            return Result.error("并无该标准版本");
        }
        Boolean existFlg = false;
        try {
            StandardVersion standardVersion = new StandardVersion(stdVersion);
            ObjectMapper objectMapper = new ObjectMapper();
            StdDataSetModel stdDataSetModel = objectMapper.readValue(dataset, StdDataSetModel.class);
            existFlg = datasetCodeValidate(standardVersion, stdDataSetModel.getCode());
            if (!existFlg) {
                this.add(standardVersion.getDataSetTableName(), stdDataSetModel);
                stdDataSetModel.setSuccessFlg(true);
                stdDataSetModel.setMessage("保存数据集成功");
                return stdDataSetModel;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (existFlg) {
            return Result.error("已存在标准数据集编码");
        } else {
            return Result.error("保存数据集失败");
        }
    }

    public Boolean datasetCodeValidate(StandardVersion standardVersion, String code) {
        Map<String, Object> query = new HashMap<>();
        Map<String, String> order = new HashMap<>();
        query.put("code", code);

        List<StdDataSetModel> list = this.getList(standardVersion, query, order, 1, 1);
        if (!CollectionUtil.isEmpty(list)) {
            return true;
        }
        return false;
    }

    public Result delete(String stdVersion, Integer datasetId) {
        if (StringUtil.isEmpty(stdVersion)) {
            return Result.error("并无该标准版本");
        }
        try {
            StandardVersion standardVersion = new StandardVersion(stdVersion);
            if (datasetId != null) {
                this.delete(standardVersion, datasetId);
            }
            return Result.success("删除数据集成功");
        } catch (Exception e) {
            return Result.success("删除数据集失败");
        }
    }

    public Boolean datasetCodeValidate(StandardVersion standardVersion, Integer datasetId,  String code) {
        SqlCreator sqlCreator = new SqlCreator(StdDataSetModel.class);
        sqlCreator.equalCondition("code", code);
        sqlCreator.neCondition("id", datasetId);
        String sql = sqlCreator.selectData(standardVersion.getDataSetTableName());
        Query sessionQuery = getQuery(sqlCreator, sql);
        List<StdDataSetModel> list = sessionQuery.list();
        if (!CollectionUtil.isEmpty(list)) {
            return true;
        }
        return false;
    }

    public Result update(String stdVersion, String dataset) {
        if (StringUtil.isEmpty(stdVersion)) {
            return Result.error("并无该标准版本");
        }
        Boolean existFlg = false;
        try {
            StandardVersion standardVersion = new StandardVersion(stdVersion);
            ObjectMapper objectMapper = new ObjectMapper();
            StdDataSetModel stdDataSetModel = objectMapper.readValue(dataset, StdDataSetModel.class);
            existFlg = datasetCodeValidate(standardVersion, stdDataSetModel.getId(), stdDataSetModel.getCode());
            if (!existFlg) {
                this.update(standardVersion, stdDataSetModel);
                stdDataSetModel.setSuccessFlg(true);
                stdDataSetModel.setMessage("修改数据集成功");
                return stdDataSetModel;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (existFlg) {
            return Result.error("已存在标准数据集编码");
        } else {
            return Result.error("修改数据集失败");
        }
    }

    public Result get(String stdVersion, Integer datasetId) {
        if (StringUtil.isEmpty(stdVersion)) {
            return Result.error("并无该数据集信息");
        }

        try {
            StandardVersion standardVersion = new StandardVersion(stdVersion);
            if (datasetId != null) {
                StdDataSetModel stdDataSetModel = this.get(standardVersion, datasetId);
                stdDataSetModel.setSuccessFlg(true);
                stdDataSetModel.setMessage("获取标准数据集成功");
                return stdDataSetModel;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return Result.error("获取标准数据集失败");
    }

    private StdDataSetModel get(StandardVersion standardVersion, Integer datasetId) {
        String dataSetTable = standardVersion.getDataSetTableName();
        SqlCreator sqlCreator = new SqlCreator(StdDataSetModel.class);
        sqlCreator.equalCondition("id", datasetId);
        String sql = sqlCreator.selectData(dataSetTable);
        Query query = getQuery(sqlCreator, sql);
        return (StdDataSetModel) query.uniqueResult();
    }

    private void update(StandardVersion standardVersion, StdDataSetModel stdDataSetModel) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(objectMapper.writeValueAsString(stdDataSetModel));
        SqlCreator sqlCreator = new SqlCreator(StdDataSetModel.class);
        String dataSetTable = standardVersion.getDataSetTableName();
        String sql = sqlCreator.updateDataByTableKey(dataSetTable, jsonNode);
        Query query = getExeuteQuery(sqlCreator, sql);
        query.executeUpdate();
    }

    private void delete(StandardVersion standardVersion, Integer datasetId) {
        Session session = getCurrentSession();
        String sql = "delete from " + standardVersion.getDataSetTableName() + " where id = :id";
        Query query = session.createSQLQuery(sql);
        query.setInteger("id", datasetId);
        query.executeUpdate();
        sql = "delete from " + standardVersion.getMetaDataTableName() + " where dataset_id = :datasetId";
        query = session.createSQLQuery(sql);
        query.setInteger("datasetId", datasetId);
        query.executeUpdate();
    }

    private void add(String dataSetTable, StdDataSetModel stdDataSetModel) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        stdDataSetModel.setId(getMaxId(dataSetTable));

        JsonNode jsonNode = objectMapper.readTree(objectMapper.writeValueAsString(stdDataSetModel));
        SqlCreator sqlCreator = new SqlCreator(StdDataSetModel.class);
        String sql = sqlCreator.insertData(dataSetTable, jsonNode);
        Query query = getExeuteQuery(sqlCreator, sql);
        query.executeUpdate();
    }

    private List<StdDataSetModel> getList(StandardVersion standardVersion, Map<String, Object> query, Map<String, String> order, Integer limit, Integer offset) {
        SqlCreator sqlCreator = new SqlCreator(StdDataSetModel.class);
        for (String key : query.keySet()) {
            sqlCreator.equalCondition(key, query.get(key));
        }
        for (String key : order.keySet()) {
            sqlCreator.order(key, order.get(key));
        }

        String sql = sqlCreator.selectData(standardVersion.getDataSetTableName());
        Query sessionQuery = getQuery(sqlCreator, sql);
        if (limit != null) {
            sessionQuery.setMaxResults(limit);
            if (offset != null) {
                sessionQuery.setFirstResult((offset - 1) * limit);
            }
        }
        return (List<StdDataSetModel>) sessionQuery.list();
    }

    public DetailModelResult getDetailModelList(String stdVersion, String condition, String order, Integer rows, Integer page) {
        try {
            List<StdDataSetModel> dataSetModelList = getDatasetList(StdDataSetModel.class, stdVersion, condition, order, rows, page);
            List<StdDataSetModel> totalList = getDatasetList(StdDataSetModel.class, stdVersion, condition, order, null, null);
            Integer count = totalList.size();
//            Integer count = getDatasetInt(StdDataSetModel.class, stdVersion, condition);
            DetailModelResult result = DetailModelResult.success("获取标准数据集列表成功");
            result.setDetailModelList(dataSetModelList);
            result.setTotalCount(count);
            return result;
        } catch (Exception e) {
            return DetailModelResult.error("获取标准数据集列表失败");
        }
    }

    public List getDatasetList(Class tClass, String stdVersion, String condition, String order, Integer limit, Integer offset) throws IOException {
        StandardVersion standardVersion = new StandardVersion(stdVersion);
        String tableName = standardVersion.getDataSetTableName();
        SqlCreator sqlCreator = new SqlCreator(tClass);
        ObjectMapper objectMapper = new ObjectMapper();
        if (!StringUtil.isEmpty(condition)) {
            JsonNode jsonNode = objectMapper.readTree(condition);
            if(jsonNode.get("initVal")!=null && !jsonNode.get("initVal").asText().isEmpty()){
                String initName = jsonNode.get("initVal").asText();
                sqlCreator.neCondition("code",initName);
            }else if(jsonNode.get("name")!=null && !jsonNode.get("name").asText().isEmpty()){
                String name = jsonNode.get("name").asText();
                sqlCreator.likeOrCondition("code", "name", name);
            } else if (jsonNode.get("stdId") != null && !jsonNode.get("stdId").asText().isEmpty()) {
                String[] stdLs = jsonNode.get("stdId").asText().split(",");
                List<Integer> stdIdLs = new ArrayList<>();
                for (String s : stdLs) {
                    stdIdLs.add(Integer.valueOf(s));
                }
                sqlCreator.inCondition("id", stdIdLs);
            }
        }
        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, String stdVersion, String condition) {
        try {
            StandardVersion standardVersion = new StandardVersion(stdVersion);
            String tableName = standardVersion.getDataSetTableName();
            SqlCreator sqlCreator = new SqlCreator(tClass);
            ObjectMapper objectMapper = new ObjectMapper();
            if (!StringUtil.isEmpty(condition)) {
                JsonNode jsonNode = objectMapper.readTree(condition);
                String name = jsonNode.get("name").asText();
                sqlCreator.likeOrCondition("code", "name", 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 List datasetVersionListByName(String rsResourceImportDatasetDialogName) {

        try {
            String hql = "FROM StandardVersionModel WHERE publishTime is not null order by publishTime";
            Query query = getCurrentSession().createQuery(hql);
            List<StandardVersionModel> versionModelList = query.list();
            String sql = SqlConstants.EMPTY;
            BeanTransformer transformer = new BeanTransformer(StdDataSetModel.class);
            for (StandardVersionModel versionModel : versionModelList) {
                SqlCreator sqlCreator = new SqlCreator(StdDataSetModel.class);
                StandardVersion version = new StandardVersion(versionModel.getVersion());
                sql = sql + sqlCreator.selectData(version.getDataSetTableName())  + SqlConstants.UNION;
            }

            if (!StringUtil.isEmpty(sql)) {
                sql = sql.substring(0, sql.length() - SqlConstants.UNION.length());
                SQLQuery sqlQuery = getCurrentSession().createSQLQuery(sql);
                sqlQuery.setResultTransformer(transformer);
                List<StdDataSetModel> modelList = sqlQuery.list();
                List<StdDataSetModel> distinctModelList = new ArrayList<>();
                Map<String, StdDataSetModel> datasetModelMap = new HashMap<>();
                for (StdDataSetModel model : modelList) {
                    datasetModelMap.put(model.getCode(), model);
                }
                for (String key : datasetModelMap.keySet()) {
                    StdDataSetModel s=datasetModelMap.get(key);
                    if(s.getName().contains(rsResourceImportDatasetDialogName)){
                        distinctModelList.add(datasetModelMap.get(key));
                    }
                }
                return distinctModelList;
            } else {
                return new ArrayList<>();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ApiException(ErrorCode.GetDataSetListFailed);
        }
    }
}

