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

import com.yihu.hos.web.framework.dao.SQLGeneralDAO;
import com.yihu.hos.web.framework.constant.ErrorCode;
import com.yihu.hos.web.framework.constant.SqlConstants;
import com.yihu.hos.web.framework.exception.ApiException;
import com.yihu.hos.web.framework.model.DictItem;
import com.yihu.hos.web.framework.model.DictionaryResult;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.web.framework.util.sql.RequestParamTransformer;
import com.yihu.hos.standard.model.standard.resultModel.PublisherResultModel;
import com.yihu.hos.system.model.SystemOrganization;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

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

    public static final String BEAN_ID = "StdPublisherService";

    public DictionaryResult getDictionaryResult(String condition, String order, Integer limit, Integer offset) {
        try {
            DictionaryResult dictionaryResult = DictionaryResult.success("获取发布机构列表成功");
            List<DictItem> detailModelList = new ArrayList<DictItem>();
            List<SystemOrganization> stdPublisherModelList = getList(condition, order, limit, offset);
            for(SystemOrganization systemOrganization : stdPublisherModelList){
                DictItem items = new DictItem();
                String id = systemOrganization.getCode();
                String name = systemOrganization.getFullName();
                items.setCode(id.toString());
                items.setValue(name);
                detailModelList.add(items);
            }
            dictionaryResult.setDetailModelList(detailModelList);
            return dictionaryResult;
        } catch (Exception e) {
            return DictionaryResult.error("获取发布机构列表失败");
        }
    }

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

        throw new ApiException(ErrorCode.GetPublisherListFaield);
    }

    private List<SystemOrganization> getList(Map<String, Object> query, Map<String, String> order, Integer limit, Integer offset) {
        Session session = getCurrentSession();
        Criteria criteria = session.createCriteria(SystemOrganization.class);
        if (query != null) {
            for (String key : query.keySet()) {
                criteria.add(Restrictions.eq(key, query.get(key)));
            }
        }
        if (limit != null) {
            criteria.setMaxResults(limit);
            if (offset != null) {
                criteria.setFirstResult((offset - 1) * limit);
            }
        }
        if (order != null) {
            for (String key : order.keySet()) {
                if (order.get(key).equals(SqlConstants.ASC)) {
                    criteria.addOrder(Order.asc(key));
                } else if (order.get(key).equals(SqlConstants.DESC)) {
                    criteria.addOrder(Order.desc(key));
                }
            }
        }
        List<SystemOrganization> systemOrganizationList = criteria.list();

        return systemOrganizationList;
    }

    public Result get(String stdPublisherId) {
        try {
            Session session = getCurrentSession();
            Criteria criteria = session.createCriteria(SystemOrganization.class);
            criteria.add(Restrictions.eq("id", stdPublisherId));
            SystemOrganization systemOrganization = (SystemOrganization) criteria.uniqueResult();
            PublisherResultModel publisherResultModel = new PublisherResultModel();
            publisherResultModel.setCode(systemOrganization.getCode());
            publisherResultModel.setName(systemOrganization.getFullName());
            publisherResultModel.setSuccessFlg(true);
            publisherResultModel.setMessage("获取机构信息成功");
            return publisherResultModel;
        } catch (Exception e) {
            return Result.error("获取机构信息失败");
        }
    }

    public Result getStandardPublisher() {
        try {
            String paramSql = "select s.param_value from system_param s where s.param_key = '"+ SqlConstants.STANDARD_ORG+"'";
            Query paramQuery = getCurrentSession().createSQLQuery(paramSql);
            String publisherCode = (String) paramQuery.uniqueResult();
            Criteria criteria = getCurrentSession().createCriteria(SystemOrganization.class);
            criteria.add(Restrictions.eq("code", publisherCode));
            SystemOrganization systemOrganization = (SystemOrganization) criteria.uniqueResult();
            PublisherResultModel publisherResultModel = new PublisherResultModel();
            publisherResultModel.setCode(systemOrganization.getCode());
            publisherResultModel.setName(systemOrganization.getFullName());
            publisherResultModel.setSuccessFlg(true);
            publisherResultModel.setMessage("获取机构信息成功");
            return publisherResultModel;
        } catch (Exception e) {
            throw new ApiException(ErrorCode.GetPublisherFailed);
        }
    }
}
