package com.yihu.hos.tenant.dao;

import com.yihu.hos.tenant.model.TenantModel;
import com.yihu.hos.web.framework.dao.SQLGeneralDAO;
import com.yihu.hos.web.framework.model.Result;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

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

/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/12/2.
 */
@Repository("tenantDao")
public class TenantDao extends SQLGeneralDAO {

    public static final String BEAN_ID = "tenantDao";


    public List<TenantModel> getTenantList(String name) throws Exception {
        List<TenantModel> list = (List<TenantModel>) super.hibernateTemplate.find("from TenantModel s where s.name=? and s.valid = 1", name);
        return list;
    }

    /**\
     * 分页列表
     * @param params
     * @return
     * @throws Exception
     */
    public Result getTenantList(Map<String, Object> params) throws Exception {
        StringBuilder sb = new StringBuilder("from TenantModel t where 1=1 ");
        Object valid = params.get("valid");
        Object name = params.get("name");
        if (!StringUtils.isEmpty(valid)) //是否有效
        {
            sb.append(" and t.valid = :valid");
        }
        //用户名过滤
        if (!StringUtils.isEmpty(name)) {
            sb.append(" and (t.name like ? or t.loginName like ?)");
        }
        sb.append(" order by t.created desc");
        Query query = super.hibernateTemplate.getSessionFactory().getCurrentSession().createQuery(sb.toString());
        if (!StringUtils.isEmpty(valid)) //是否有效
        {
            query.setInteger("valid",Integer.parseInt(valid.toString()));
        }
        if (!StringUtils.isEmpty(name)) {
            query.setString(0, "%" + name.toString() + "%");
            query.setString(1, "%" + name.toString() + "%");
        }

        return super.getDataGridResult(query, Integer.valueOf(params.get("page").toString()), Integer.valueOf(params.get("rows").toString()));

    }

    public void createDB(String dbName) throws Exception {
        String sql = "CREATE DATABASE IF NOT EXISTS "+dbName;
        super.execute(sql);
    }

}
