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

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.model.Select2;
import com.yihu.hos.standard.model.standard.StdDictionaryEntryModel;
import com.yihu.hos.standard.service.bo.StandardVersion;
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.RequestParamTransformer;
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.io.IOException;
import java.util.*;

/**
 * @author Sand
 * @version 1.0
 * @created 16-7月-2015 20:57:06
 */
@Transactional
@Service("StdDictEntryService")
public class StdDictEntryService extends SQLGeneralDAO {

    public static final String BEAN_ID = "StdDictEntryService";

    public StdDictEntryService() {
    }

    public void finalize() throws Throwable {
    }

    public List<StdDictionaryEntryModel> getList(String stdVersion, Integer dictId, 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, dictId, queryMap, orderMap, limit, offset);
        } catch (Exception e) {
            e.printStackTrace();
        }

        throw new ApiException(ErrorCode.StandardDictEntryGetListFailed);
    }

    public Result add(String stdVersion, String dictEntry) {
        Boolean existFlg = false;
        try {
            StandardVersion standardVersion = new StandardVersion(stdVersion);
            StdDictionaryEntryModel stdDictionaryEntryModel = objectMapper.readValue(dictEntry, StdDictionaryEntryModel.class);
            existFlg = dictEntryCodeValidate(standardVersion, stdDictionaryEntryModel.getDictId(), stdDictionaryEntryModel.getCode());
            if (!existFlg) {
                this.add(standardVersion, stdDictionaryEntryModel);
                stdDictionaryEntryModel.setSuccessFlg(true);
                stdDictionaryEntryModel.setMessage("保存标准字典项成功");
                return stdDictionaryEntryModel;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (existFlg) {
            return Result.error("已存在标准字典项编码");
        } else {
            return Result.error("保存标准字典项失败");
        }
    }

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

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

    public Result delete(String stdVersion, Integer dictEntryId) {
        try {
            StandardVersion standardVersion = new StandardVersion(stdVersion);
            if (dictEntryId != null) {
                this.delete(standardVersion, dictEntryId);
                return Result.success("删除标准字典项成功");
            }
        } catch (Exception e) {
            throw new ApiException(ErrorCode.StandardDictEntryDeleteFailed);
        }
        return Result.error("删除标准字典项失败");
    }

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

    public Result update(String stdVersion, String dictEntry) {
        Boolean existFlg = false;
        try {
            StandardVersion standardVersion = new StandardVersion(stdVersion);

            StdDictionaryEntryModel stdDictionaryEntryModel = objectMapper.readValue(dictEntry, StdDictionaryEntryModel.class);
            existFlg = dictEntryCodeValidate(standardVersion, stdDictionaryEntryModel.getDictId(), stdDictionaryEntryModel.getId(), stdDictionaryEntryModel.getCode());
            if (!existFlg) {
                this.modify(standardVersion, stdDictionaryEntryModel);
                stdDictionaryEntryModel.setSuccessFlg(true);
                stdDictionaryEntryModel.setMessage("修改标准字典项成功");
                return stdDictionaryEntryModel;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (existFlg) {
            return Result.error("已存在标准字典项编码");
        } else {
            return Result.error("修改标准字典项失败");
        }
    }

    public Result get(String stdVersion, Integer dictEntryId) {
        try {
            StandardVersion standardVersion = new StandardVersion(stdVersion);
            if (dictEntryId != null) {
                StdDictionaryEntryModel stdDictionaryEntryModel = this.get(standardVersion, dictEntryId);
                stdDictionaryEntryModel.setSuccessFlg(true);
                stdDictionaryEntryModel.setMessage("获取标准字典项成功");
                return stdDictionaryEntryModel;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return Result.error("获取标准字典项失败");
    }

    public void add(StandardVersion standardVersion, StdDictionaryEntryModel stdDictionaryEntryModel) throws IOException {
        Session session = getCurrentSession();

        String dictEntryTableName = standardVersion.getDictEntryTableName();
        String sql = "select max(id) from " + dictEntryTableName;
        Query query = session.createSQLQuery(sql);
        Object object = query.uniqueResult();

        Integer id = object == null ? 1 : Integer.parseInt(object.toString()) + 1;
        stdDictionaryEntryModel.setId(id);

        JsonNode jsonNode = objectMapper.readTree(objectMapper.writeValueAsString(stdDictionaryEntryModel));
        SqlCreator sqlCreator = new SqlCreator(StdDictionaryEntryModel.class);
        sql = sqlCreator.insertData(dictEntryTableName, jsonNode);
        query = getExeuteQuery(sqlCreator, sql);
        query.executeUpdate();
    }

    public DetailModelResult getDetailModelList(String stdVersion, Integer dictId, String condition, String order, Integer rows, Integer page) {
        try {
            List<StdDictionaryEntryModel> detailModelList = getDictEntryList(StdDictionaryEntryModel.class, stdVersion, dictId, condition, order, rows, page);
            Integer count = getDictEntryInt(StdDictionaryEntryModel.class, stdVersion, dictId, condition);
            DetailModelResult result = DetailModelResult.success("获取标准字典项列表成功");
            result.setDetailModelList(detailModelList);
            result.setTotalCount(count);
            return result;
        } catch (Exception e) {
            return DetailModelResult.error("获取标准字典项列表失败");
        }
    }

    public List getDictEntryList(Class tClass, String stdVersion, Integer dictId, String condition, String order, Integer limit, Integer offset) {
        StandardVersion standardVersion = new StandardVersion(stdVersion);
        String tableName = standardVersion.getDictEntryTableName();
        SqlCreator sqlCreator = new SqlCreator(tClass);
        sqlCreator.equalCondition("dictId", dictId);
        if (!StringUtil.isEmpty(condition)) {
            try {
                JsonNode jsonNode = objectMapper.readTree(condition);
                String name = jsonNode.get("name").asText();
                sqlCreator.likeOrCondition("code", "value", name);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            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 getDictEntryInt(Class tClass, String stdVersion, Integer dictId, String condition) {
        StandardVersion standardVersion = new StandardVersion(stdVersion);
        String tableName = standardVersion.getDictEntryTableName();
        SqlCreator sqlCreator = new SqlCreator(tClass);
        sqlCreator.equalCondition("dictId", dictId);
        if (!StringUtil.isEmpty(condition)) {
            try {
                JsonNode jsonNode = objectMapper.readTree(condition);
                String name = jsonNode.get("name").asText();
                sqlCreator.likeOrCondition("code", "value", name);
            } catch (IOException 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;
    }

    public DetailModelResult getDictEntrySelectList(String stdVersion, Integer dictId, String condition, String order, Integer rows, Integer page) {
        try {
            List<StdDictionaryEntryModel> dictEntryModelList = getDictEntryList(StdDictionaryEntryModel.class, stdVersion, dictId, condition, order, rows, page);
            List<Select2> detailModelList = new ArrayList<>();
            for (StdDictionaryEntryModel dictEntry : dictEntryModelList) {
                Select2 select2 = new Select2();
                select2.setId(dictEntry.getId() + SqlConstants.COMMA + dictEntry.getCode());
                select2.setText(dictEntry.getValue());
                detailModelList.add(select2);
            }
            DetailModelResult result = DetailModelResult.success("获取标准字典项下拉列表成功");
            result.setDetailModelList(detailModelList);
            result.setTotalCount(detailModelList.size());
            return result;
        } catch (Exception e) {
            return DetailModelResult.error("获取标准字典项下拉列表失败");
        }
    }

    public StdDictionaryEntryModel getStEntryValueByCode(String version, Integer dictId, String entryCode) {
        try {
            SqlCreator sqlCreator = new SqlCreator(StdDictionaryEntryModel.class);
            sqlCreator.equalCondition("dictId", dictId);
            sqlCreator.equalCondition("code", entryCode);
            String sql = sqlCreator.selectData("std_dictionary_entry_" + version);
            Query query = getQuery(sqlCreator, sql);
            List<StdDictionaryEntryModel> list = query.list();
            if (list == null || list.size() == 0) {
                return null;
            } else {
                return list.get(0);
            }
        } catch (Exception e) {
            return null;
        }
    }

    private StdDictionaryEntryModel get(StandardVersion standardVersion, Integer dictEntryId) {
        String dictEntryTableName = standardVersion.getDictEntryTableName();

        SqlCreator sqlCreator = new SqlCreator(StdDictionaryEntryModel.class);
        sqlCreator.equalCondition("id", dictEntryId);
        String sql = sqlCreator.selectData(dictEntryTableName);
        Query query = getQuery(sqlCreator, sql);
        return (StdDictionaryEntryModel) query.uniqueResult();
    }

    private void modify(StandardVersion standardVersion, StdDictionaryEntryModel stdDictionaryEntryModel) throws IOException {
        JsonNode jsonNode = objectMapper.readTree(objectMapper.writeValueAsString(stdDictionaryEntryModel));
        SqlCreator sqlCreator = new SqlCreator(StdDictionaryEntryModel.class);
        String dictEntryTableName = standardVersion.getDictEntryTableName();
        String sql = sqlCreator.updateDataByTableKey(dictEntryTableName, jsonNode);
        Query query = getExeuteQuery(sqlCreator, sql);
        query.executeUpdate();
    }

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

    private List<StdDictionaryEntryModel> getList(StandardVersion standardVersion, Integer dictId, Map<String, Object> query, Map<String, String> order, Integer limit, Integer offset) {
        SqlCreator sqlCreator = new SqlCreator(StdDictionaryEntryModel.class);
        sqlCreator.equalCondition("dictId", dictId);
        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.getDictEntryTableName());
        Query sessionQuery = getQuery(sqlCreator, sql);
        if (limit != null) {
            sessionQuery.setMaxResults(limit);
            if (offset != null) {
                sessionQuery.setFirstResult((offset - 1) * limit);
            }
        }
        return (List<StdDictionaryEntryModel>) sessionQuery.list();
    }

}//end DictEntryManager