package cn.hmsoft.frame.data.dao;

import java.util.List;

import org.springframework.stereotype.Repository;

import cn.hmsoft.frame.data.model.FrameOptr;
import cn.hmsoft.frame.data.model.FrameOptrRole;
import cn.hmsoft.frame.data.model.FrameRes;
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 FrameOptrDao extends PlatformDaoSupport<FrameOptr> {

	public Pager pageOptr(int optr_id, Integer start, Integer limit, String query, QueryOrder order) {
		String sql = "SELECT optr.*,fo.login_name create_login_name,fo.optr_name create_optr_name FROM"
				+ "	(SELECT op.*, role_names," + this.isNull("d.dept_name")
				+ " dept_name FROM frame_optr op LEFT JOIN (SELECT " + this.concatValues("role_name")
				+ " role_names, optr_id FROM frame_role r, frame_optr_role fo"
				+ "	WHERE r.role_id = fo.role_id GROUP BY optr_id) role ON role.optr_id = op.optr_id left join frame_dept d on d.dept_id=op.optr_dept"
				+ "	) optr, frame_optr fo WHERE fo.optr_id=optr.create_optr AND (optr.create_optr =? OR 1 =?)";
		if (StringHelper.isEmpty(query)) {
			return this.pageMapBySql(order, start, limit, sql, "顶级部门", optr_id, optr_id == 0 ? 1 : 2);
		}
		sql = sql + " and  (optr.optr_name like ? or optr.login_name like ? or optr.optr_desc like ?)";
		String value = this.generateLikeParamter(query);
		return this.pageMapBySql(order, start, limit, sql, "顶级部门",optr_id, optr_id == 0 ? 1 : 2, value, value, value);

	}

	private final static String LIST_ROLES_RES = "select r.* from frame_res r where res_status='Active' and res_id in (select distinct frr.res_id from frame_role_res frr,frame_optr_role optr where frr.role_id=optr.role_id and optr.optr_id=?) order by res_level,res_order,res_id";

	/******************
	 * 获取操作员所属角色所有权限
	 */
	public List<FrameRes> listRolesRes(int optr_id) {
		return this.listBySql(FrameRes.class, LIST_ROLES_RES, optr_id);
	}

	private final static String LIST_OPTR_RES = "select r.*,o.type type_status from frame_res r ,frame_optr_res o where r.res_status='Active' and  r.res_id=o.res_id and optr_id=?";

	/******************
	 * 获取操作员所属角色额外权限
	 */
	public List<FrameRes> listOptrRes(int optr_id) {
		return this.listBySql(FrameRes.class, LIST_OPTR_RES, optr_id);
	}

	/*****************
	 * 删除一个操作员的角色
	 */
	public void deleteOptrRole(FrameOptrRole or) {
		String sql = "delete from frame_optr_role  where optr_id=? and role_id=?";
		this.updateBySql(sql,or.getOptr_id(),or.getRole_id());
	}
}
