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


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.core.datatype.StringUtil;
import com.yihu.hos.rest.models.standard.adapter.AdapterDictModel;
import com.yihu.hos.rest.models.standard.bo.AdapterVersion;
import com.yihu.hos.web.framework.dao.SQLGeneralDAO;
import com.yihu.hos.web.framework.model.DetailModelResult;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.web.framework.util.sql.SqlCreator;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Iterator;
import java.util.List;

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

    public static final String BEAN_ID = "AdapterDictService";

    public AdapterDictService() {
    }

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

    public Result add(String adapterVersion, String dict) {
        try {
            AdapterVersion version = new AdapterVersion(adapterVersion);
            ObjectMapper objectMapper = new ObjectMapper();
            AdapterDictModel adapterDictModel = objectMapper.readValue(dict, AdapterDictModel.class);
            Session session = getCurrentSession();
            String sql = "select max(id) from " + version.getMetaDataTableName();
            Query query = session.createSQLQuery(sql);
            Object object = query.uniqueResult();
            adapterDictModel.setId(object == null ? 1 : Integer.parseInt(object.toString()) + 1);

            JsonNode jsonNode = objectMapper.readTree(objectMapper.writeValueAsString(adapterDictModel));
            SqlCreator sqlCreator = new SqlCreator(AdapterDictModel.class);
            sql = sqlCreator.insertData(version.getMetaDataTableName(), jsonNode);
            query = getExeuteQuery(sqlCreator, sql);
            query.executeUpdate();
            adapterDictModel.setSuccessFlg(true);
            adapterDictModel.setMessage("保存适配字典成功");
            return adapterDictModel;
        } catch (Exception e) {
           return Result.error("保存适配字典失败");
        }
    }

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

    public Result modify(String adapterVersion, String dict) {
        try {
            AdapterVersion version = new AdapterVersion(adapterVersion);
            ObjectMapper objectMapper = new ObjectMapper();
            AdapterDictModel adapterDictModel = objectMapper.readValue(dict, AdapterDictModel.class);
            JsonNode jsonNode = objectMapper.readTree(objectMapper.writeValueAsString(adapterDictModel));

            SqlCreator sqlCreator = new SqlCreator(AdapterDictModel.class);
            String sql = sqlCreator.updateDataByTableKey(version.getMetaDataTableName(), jsonNode);
            Query query = getExeuteQuery(sqlCreator, sql);
            query.executeUpdate();
            adapterDictModel.setSuccessFlg(true);
            adapterDictModel.setMessage("修改适配字典成功");
            return adapterDictModel;
        } catch (Exception e) {
            return Result.error("修改适配字典失败");
        }
    }


    public DetailModelResult getDetailResult(String adapterVersion, String condition, String order, Integer rows, Integer page) {
        try {
            List dictList = getDictList(AdapterDictModel.class, adapterVersion, condition, order, rows, page);
            Integer count = getDictInt(AdapterDictModel.class, adapterVersion, condition);
            DetailModelResult result = DetailModelResult.success("获取适配字典列表成功");
            result.setDetailModelList(dictList);
            result.setTotalCount(count);
            return result;
        } catch (Exception e) {
            return DetailModelResult.error("获取适配字典列表成功");
        }
    }

    public Result get(String version, Integer dictId) {
        try {
            AdapterVersion adapterVersion = new AdapterVersion(version);
            AdapterDictModel adapterDictModel = (AdapterDictModel) get(AdapterDictModel.class, adapterVersion.getDictTableName(), dictId);
            adapterDictModel.setSuccessFlg(true);
            adapterDictModel.setMessage("获取适配字典成功");
            return adapterDictModel;
        } catch (Exception e) {
            return Result.error("获取适配字典失败");
        }
    }

    public List getDictList(Class tClass, String adapterVersion, String condition, String order, Integer limit, Integer offset) {
        AdapterVersion version = new AdapterVersion(adapterVersion);
        String tableName = version.getDictTableName();
        SqlCreator sqlCreator = new SqlCreator(tClass);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (!StringUtil.isEmpty(condition)) {
                JsonNode jsonNode = objectMapper.readTree(condition);
                String name = jsonNode.get("name").asText();
                sqlCreator.likeOrCondition("stdDictCode", "stdDictName", 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);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        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 getDictInt(Class tClass, String adapterVersion, String condition) {
        AdapterVersion version = new AdapterVersion(adapterVersion);
        String tableName = version.getDictTableName();
        SqlCreator sqlCreator = new SqlCreator(tClass);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (!StringUtil.isEmpty(condition)) {
                JsonNode jsonNode = objectMapper.readTree(condition);
                String name = jsonNode.get("name").asText();
                sqlCreator.likeOrCondition("stdDictCode", "stdDictName", name);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        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;
    }



}