package com.palmnest.dao.notice.impl;

import java.util.List;

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

import com.palmnest.application.bean.Page;
import com.palmnest.dao.hibernate.GenericDaoHibernate;
import com.palmnest.dao.notice.EmailConfigDao;
import com.palmnest.model.notice.EmailConfigModel;

@Repository("emailConfigDao")
public class EmailConfigDaoImpl extends GenericDaoHibernate<EmailConfigModel, Integer> implements EmailConfigDao {
	public EmailConfigDaoImpl() {
		super(EmailConfigModel.class);

	}

	/**
	 * longmeizhen
	 */
	@Override
	public List<EmailConfigModel> getAll() {
		String strHql = "from EmailConfigModel where isEnabled='1' ";
		List<EmailConfigModel> functions = getSession().createQuery(strHql).list();
		return functions;
	}

	/**
	 * 根据邮箱地址或者查询所有的发送邮箱账号配置
	 * longmeizhen
	 */
	@Override
	public Page getEmailConfigList(String orgIds, String email, int pageNo, int pageSize) throws Exception {
		StringBuilder strHql = new StringBuilder("select org.name as orgName,em.* from tb_email_config em  ");
		strHql.append(" left join tb_organization org on org.id=em.orgId ");
		strHql.append(" where em.isEnabled='1' ");
		if (StringUtils.isNotBlank(email)) {
			strHql.append(" and email_address like '%" + email + "%' ");
		}
		if (StringUtils.isNotBlank(orgIds)) {
			String[] orgStr = orgIds.split(";");
			String str = "";
			if (orgStr != null && orgStr.length > 0) {
				for (int i = 0; i < orgStr.length; i++) {
					str = str + orgStr[i] + ",";
				}
			}
			if (StringUtils.isNotEmpty(str)) {
				str = str.substring(0, str.length() - 1);
				strHql.append(" and em.orgId in (" + str + ") ");
			}

		}
		strHql.append(" order by createTime desc ");
		return pagedQueryByJdbcTemplate(strHql.toString(), pageNo, pageSize);
	}

	@Override
	public EmailConfigModel getEmailByOrg(String orgId) {
		String sql = "from EmailConfigModel where isEnabled='1' and orgId=?";
		List<EmailConfigModel> list = getSession().createQuery(sql).setString(0, orgId).list();
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}
}
