package cn.com.qmth.stmms.biz.basic.service.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Service;

import cn.com.qmth.stmms.biz.basic.bean.RoleInfoQuery;
import cn.com.qmth.stmms.biz.basic.bean.RoleInfoVo;
import cn.com.qmth.stmms.biz.basic.model.RoleInfo;
import cn.com.qmth.stmms.biz.basic.service.RoleInfoService;
import cn.com.qmth.stmms.biz.common.BaseQueryService;

@Service("roleInfoService")
public class RoleInfoServiceImpl extends BaseQueryService<RoleInfo> implements RoleInfoService {

	@PersistenceContext
	private EntityManager entityManager;
	
	@SuppressWarnings("unchecked")
	@Override
	public List<RoleInfoVo> findByQuery(RoleInfoQuery req) {
		int offset = (req.getPageNumber() - 1) * req.getPageSize();
		StringBuilder sql = new StringBuilder();
		sql.append(" select t.name,t.code, u.name updaterName,t.update_time updateTime ");
		sql.append(" from b_role_info t left join b_user u on t.updater_id=u.id where t.school_id=" + req.getSchoolId());
		if(StringUtils.isNotBlank(req.getRole())) {
			sql.append(" and t.code='"+req.getRole()+"' ");
		}
		sql.append(" and t.code in('SCHOOL_ADMIN','SUBJECT_HEADER','SCHOOL_VIEWER','INSPECTOR','COLLEGE_ADMIN')");
		sql.append(" order by t.update_time desc,t.id ");
		sql.append(" limit " + offset + "," + req.getPageSize());
		Query query = entityManager.createNativeQuery(sql.toString());
		query.unwrap(SQLQuery.class).setResultTransformer(Transformers.aliasToBean(RoleInfoVo.class));
		List<RoleInfoVo> ret = query.getResultList();
		return ret;
	}

	@Override
	public Integer countByQuery(RoleInfoQuery req) {
		StringBuilder sql = new StringBuilder();
		sql.append("select count(1) ");
		sql.append(" from b_role_info t left join b_user u on t.updater_id=u.id where t.school_id=" + req.getSchoolId());
		if(StringUtils.isNotBlank(req.getRole())) {
			sql.append(" and t.code='"+req.getRole()+"' ");
		}
		sql.append(" and t.code in('SCHOOL_ADMIN','SUBJECT_HEADER','SCHOOL_VIEWER','INSPECTOR','COLLEGE_ADMIN')");
		Query query = entityManager.createNativeQuery(sql.toString());
		return Integer.valueOf(query.getResultList().get(0).toString());
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<RoleInfoVo> allList(Integer schoolId) {
		StringBuilder sql = new StringBuilder();
		sql.append(" select t.name,t.code ");
		sql.append(" from b_role_info t  where t.school_id=" + schoolId);
		sql.append(" and t.code in('SCHOOL_ADMIN','SUBJECT_HEADER','SCHOOL_VIEWER','INSPECTOR','COLLEGE_ADMIN')");
		sql.append(" order by t.seq ");
		Query query = entityManager.createNativeQuery(sql.toString());
		query.unwrap(SQLQuery.class).setResultTransformer(Transformers.aliasToBean(RoleInfoVo.class));
		List<RoleInfoVo> ret = query.getResultList();
		return ret;
	}
}
