package com.palmnest.dao.notice.impl;

import java.math.BigInteger;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.palmnest.application.bean.Page;
import com.palmnest.dao.hibernate.GenericDaoHibernate;
import com.palmnest.dao.notice.PhoneMessageDao;
import com.palmnest.model.notice.PhoneMessageModel;

@Repository("phoneMessageDao")
public class PhoneMessageDaoImpl extends GenericDaoHibernate<PhoneMessageModel, Integer> implements PhoneMessageDao {
	public PhoneMessageDaoImpl() {
		super(PhoneMessageModel.class);

	}

	@Override
	public Page getDataList(Map<String, Object> map, int pageNo, int pageSize)
			throws Exception {

		StringBuffer sbf = new StringBuffer();
		sbf.append("  select phm.id,content,phones,DATE_FORMAT(send_time,'%Y/%m/%d %T') send_time  ");
		sbf.append("  ,state,phones_quantity,total,platform_id,ifnull(apus.USERNAME,approval_user) approval_user,DATE_FORMAT(approval_time,'%Y/%m/%d %T') approval_time  ");
		sbf.append("  ,DATE_FORMAT(phm.createTime,'%Y/%m/%d %T') createTime,phm.creator,phm.modifier,DATE_FORMAT(phm.modifyTime,'%Y/%m/%d %T') modifyTime  ");
		sbf.append("  ,phm.isEnabled,aus.FULL_NAME fullName,aus.USERNAME  ");
		sbf.append("  ,'' roleId,0 isApproval,0 isPublish,'' roleName,phm.approval_type approvalType,phm.orgId  ");
		sbf.append("  from tb_phone_message phm  ");
		sbf.append("  left join tb_app_user aus on phm.creator=aus.id  ");
		sbf.append(" left join tb_app_user apus on phm.approval_user=apus.id ");
		sbf.append("  where 1=1   ");
		if (map.get("c_beginTime") != null) {
			sbf.append(" and createTime>'");
			sbf.append(map.get("c_beginTime").toString() + " 00:00:00'");
		}
		if (map.get("c_endTime") != null) {
			sbf.append(" and createTime<'");
			sbf.append(map.get("c_endTime").toString() + " 23:59:59'");
		}
		if (map.get("a_beginTime") != null) {
			sbf.append(" and approval_time>'");
			sbf.append(map.get("a_beginTime").toString() + " 00:00:00'");
		}
		if (map.get("a_endTime") != null) {
			sbf.append(" and approval_time<'");
			sbf.append(map.get("a_endTime").toString() + " 23:59:59'");
		}
		if (map.get("state") != null) {
			sbf.append(" and state=" + map.get("state").toString());
		}
		if (map.get("orgIds") != null) {
			sbf.append(" and orgId in(" + map.get("orgIds") + ")");
		}
		
		//多级审核下的过滤条件
				if(null != map.get("approvalType")){
					sbf.append(" and  phm.approval_type="+map.get("approvalType"));
				}
		
		sbf.append(" ORDER BY state,createTime DESC");
		return pagedQueryByJdbcTemplate(sbf.toString(), pageNo, pageSize);
	}

	@Override
	public Integer getTotal(String orgIds) {
		String sql = "SELECT COUNT(t.id) total" +
				" FROM tb_phone_message t where state = 0 AND isEnabled = 1 AND orgId IN (" + orgIds + ")";
		return ((BigInteger) getSession().createSQLQuery(sql).uniqueResult()).intValue();
	}
}
