package com.palmnest.dao.notice.impl;

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

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import cn.superdesk.libs.common.json.JsonUtils;

import com.palmnest.dao.hibernate.GenericDaoHibernate;
import com.palmnest.dao.notice.ApprovalDao;
import com.palmnest.model.User;
import com.palmnest.model.notice.AppNoticeModel;
import com.palmnest.model.notice.ApprovalModel;
import com.palmnest.model.notice.NoticeApprovalsetModel;

@Slf4j
@Repository("approvalDao")
public class ApprovalDaoImpl extends GenericDaoHibernate<ApprovalModel, Integer> implements ApprovalDao{
	public ApprovalDaoImpl() {
		super(ApprovalModel.class);

	}
	/**
	 * 根据项目、类型、单据id获取最后的审核信息
	 * @param orgId 项目id
	 * @param type 类型
	 * @param sourceId 单据id
	 * @return
	 */
	@Override
	public ApprovalModel getBySourceId(Integer orgId, Integer type,
			Integer sourceId) {
		String sql="FROM ApprovalModel WHERE type = ? AND sourceId = ? AND orgId = ?  and enabled=1 ORDER BY orderno DESC LIMIT 1";
		return (ApprovalModel)getSession().createQuery(sql).setInteger(0, type).setInteger(1, sourceId).setInteger(2, orgId).uniqueResult();
	}
	/**
	 * 获取订单的审核信息
	 * @param orgId
	 * @param type
	 * @param sourceId
	 * @return
	 */
	@Override
	public Integer getOrdernoBySourceId(Integer orgId, Integer type,
			Integer sourceId) {
		String sql="select orderno from tb_approval where org_id="+orgId+" and type="+type+" and source_id="+sourceId+" and enabled=1  ORDER BY orderno DESC LIMIT 1 ";
		List<Map<String, Object>> list = getJdbcTemplate().queryForList(sql);
		if (list != null && list.size() > 0) {
			String orderno=list.get(0).get("orderno") == null ? "" : list.get(0).get("orderno").toString();
			if(StringUtils.isBlank(orderno)){
				return 0;
			}
			return Integer.parseInt(orderno);
		}
		return 0;
	}
	@Override
	public List<ApprovalModel> getApprovalList(Integer orgId, Integer type,
			Integer sourceId) {
		String sql="FROM ApprovalModel WHERE type = ? AND sourceId = ? AND orgId = ? and enabled=1 ORDER BY orderno ";
		return getSession().createQuery(sql).setInteger(0, type).setInteger(1, sourceId).setInteger(2, orgId).list();
	}
	/**
	 * 根据审核角色获取所有的审核人信息
	 * @param roleId
	 * @return
	 */
	@Override
	public List<User> getAppUserByRoleId(String roleId) {
		StringBuilder sql=new StringBuilder(" SELECT * FROM tb_app_user a WHERE 1 = 1 AND a.ISENABLED = 1 AND a.device_type IS NOT NULL  ");
		sql.append("  AND EXISTS ( SELECT USER_ID, ROLE_ID FROM tr_app_user_role b WHERE a.id = b.USER_ID AND b.ROLE_ID = "+roleId+" )  ");
		log.info("getAppUserByRoleId-sql:{}",JsonUtils.toJson(sql));
		return getSession().createSQLQuery(sql.toString()).addEntity(User.class).list();
	}
}
