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

import com.fasterxml.jackson.databind.JsonNode;
import com.yihu.hos.web.framework.dao.SQLGeneralDAO;
import com.yihu.hos.web.framework.constant.ErrorCode;
import com.yihu.hos.web.framework.exception.ApiException;
import com.yihu.hos.web.framework.util.sql.RequestParamTransformer;
import com.yihu.hos.web.framework.util.sql.SqlCreator;
import com.yihu.hos.standard.model.standard.StdDatasetCatalogModel;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @created Airhead 2015/12/28.
 */
@Transactional
@Service("StdDatasetCatalogService")
public class StdDatasetCatalogService extends SQLGeneralDAO {

    public static final String BEAN_ID = "StdDatasetCatalogService";

    public StdDatasetCatalogService() {

    }

    public void finalize() throws Throwable {

    }

    public List<StdDatasetCatalogModel> getList(String condition, String order, Integer limit, Integer offset) {
        try {
            Map queryMap = RequestParamTransformer.parseJsonToMap(condition);
            Map orderMap = RequestParamTransformer.parseJsonToMap(order);
            return this.getList(queryMap, orderMap, limit, offset);
        } catch (Exception e) {
            e.printStackTrace();
        }

        throw new ApiException(ErrorCode.StandardDatasetCatalogGetListFailed);
    }

    public Object add(String catalog) throws Exception {
        try {
            StdDatasetCatalogModel stdDatasetCatalogModel = objectMapper.readValue(catalog, StdDatasetCatalogModel.class);
            this.add(stdDatasetCatalogModel);

            return stdDatasetCatalogModel.getId();
        } catch (IOException e) {
            e.printStackTrace();
        }

        throw new ApiException(ErrorCode.StandardDatasetCatalogSaveFailed);
    }

    public void delete(Integer catalogId) throws Exception {
        try {
            if (catalogId != null) {
                StdDatasetCatalogModel cdaCatalogModel = get(catalogId);
                deleteEntity(cdaCatalogModel);
            }
        } catch (DataAccessException e) {
            throw new ApiException(ErrorCode.StandardDatasetCatalogDeleteFailed);
        }
    }

    public Object update(String catalog) throws Exception {
        try {
            StdDatasetCatalogModel stdDatasetCatalogModel = objectMapper.readValue(catalog, StdDatasetCatalogModel.class);
            this.modify(stdDatasetCatalogModel);

            return stdDatasetCatalogModel;
        } catch (IOException e) {
            e.printStackTrace();
        }

        throw new ApiException(ErrorCode.StandardDatasetCatalogUpdateFailed);
    }

    public StdDatasetCatalogModel get(Integer catalogId) {
        if (catalogId == null) {
            throw new ApiException(ErrorCode.StandardDatasetCatalogMissID);
        }
        
        try {
            if (catalogId != null) {
                Session session = getCurrentSession();
                String hql = "FROM StdDatasetCatalogModel where id = ?";
                Query query = session.createQuery(hql);
                query.setParameter(0, catalogId);
                return (StdDatasetCatalogModel) query.uniqueResult();
            }

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

        throw new ApiException(ErrorCode.StandardDatasetCatalogGetFailed);
    }

    private void modify(StdDatasetCatalogModel stdDatasetCatalogModel)  throws Exception {
        updateEntity(stdDatasetCatalogModel);
    }

    private void add(StdDatasetCatalogModel stdDatasetCatalogModel)  throws Exception {
        Session session = getCurrentSession();
        String sql = "select max(id) from " + StdDatasetCatalogModel.TABLE_NAME;
        Query query = session.createSQLQuery(sql);
        Object object = query.uniqueResult();
        stdDatasetCatalogModel.setId(object == null ? 1 : Integer.parseInt(object.toString()) + 1);

        JsonNode jsonNode = objectMapper.readTree(objectMapper.writeValueAsString(stdDatasetCatalogModel));
        SqlCreator sqlCreator = new SqlCreator(StdDatasetCatalogModel.class);
        sql = sqlCreator.insertData(StdDatasetCatalogModel.TABLE_NAME, jsonNode);
        query = getExeuteQuery(sqlCreator, sql);
        query.executeUpdate();
    }

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