package cn.hmsoft.frame.data.dao;

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

import org.springframework.stereotype.Repository;

import cn.hmsoft.frame.constants.FrameStatus;
import cn.hmsoft.frame.data.model.FrameRole;
import cn.hmsoft.helper.StringHelper;
import cn.hmsoft.jdbc.core.PlatformDaoSupport;
import cn.hmsoft.jdbc.entity.Pager;
import cn.hmsoft.jdbc.entity.QueryOrder;

@Repository
public class FrameRoleDao extends PlatformDaoSupport<FrameRole> {

	public Pager pageRole(Integer optr_id, Integer start, Integer limit, String query, QueryOrder order) {
		final StringBuilder sql = new StringBuilder();
		sql.append("select r.*,optr.optr_count,res.res_count " + (optr_id == null ? "" : ",ff.optr_id")
				+ " from (select o.*,t.login_name create_login_name,t.optr_name create_optr_name from frame_role o,frame_optr t where o.create_optr=t.optr_id) r  ");
		sql.append(
				"left join (select role_id,count(1) optr_count from frame_optr_role group by role_id) optr on r.role_id=optr.role_id ");
		sql.append(
				"left join (select role_id,count(1) res_count from frame_role_res res group by role_id) res on res.role_id=r.role_id ");
		if (optr_id != null) {
			sql.append("left join (select * from frame_optr_role where optr_id=" + optr_id
					+ ") ff on ff.role_id=r.role_id");
		}
		if (StringHelper.isEmpty(query)) {
			return this.pageMapBySql(order, start, limit, sql.toString());
		}
		sql.append(" where role_name like ? or role_desc like ?");
		return this.pageMapBySql(order, start, limit, sql.toString(), "%" + query + "%", "%" + query + "%");
	}

	public List<Map<String, Object>> listRoleRes(int role_id) {
		String sql = "select rr.role_id, res.* from (select * from frame_res res where res_status=?) res LEFT JOIN frame_role_res rr"
				+ " on res.res_id=rr.res_id and rr.role_id=? order by res_level,res_order";
		return this.listMapBySql(sql, FrameStatus.Active.toString(), role_id);
	}
	
	public FrameRole listRole(Integer optr_id) {
		String sql = "select r.* from frame_role r ,frame_optr_role fo where r.role_id = fo.role_id and fo.optr_id = ? ";
		return this.findBySql(sql, optr_id);
	}
}
