package org.cs.mgr.user.dao.impl;

import java.util.HashMap;
import java.util.Map;

import org.cs.core.dao.impl.BaseDao;
import org.cs.mgr.user.dao.IMsgDao;
import org.cs.mgr.user.model.Msg;
import org.cs.util.Pager;
import org.springframework.stereotype.Repository;

@Repository
public class MsgDao extends BaseDao<Msg> implements IMsgDao {

	@Override
	public int count(int userId) {
		
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT IFNULL(SUM(IF(amr.id IS NULL,1,0)),0) num");
		sb.append(" FROM app_msg am");
		sb.append(" LEFT JOIN app_msg_record amr ON amr.msg_id=am.id");
		sb.append(" WHERE am.user_id=? OR am.user_id=0");
		sb.append(" ORDER BY am.create_date DESC");
		
		return jdbcTemplate.queryForObject(sb.toString(), Integer.class,userId);
	}

	@Override
	public Pager getMyMsgs(String userId,Pager page) {
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT am.id,am.title,am.note,am.create_date createDate,IF(amr.id IS NULL,0,1) isRead");
		sb.append(" FROM app_msg am");
		sb.append(" LEFT JOIN app_msg_record amr ON amr.msg_id=am.id");
		sb.append(" WHERE am.user_id=:userId OR am.user_id=0");
		sb.append(" ORDER BY am.create_date DESC");
		
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("userId", userId);
		
		Pager pager = findPageBySql(sb.toString(), page, params);
		
		return pager;
	}

}
