package com.cloudcross.ssp.web.back.main.ad;

import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cloudcross.ssp.base.web.SimpleController;
import com.cloudcross.ssp.common.utils.Pager;
import com.cloudcross.ssp.model.Message;
import com.cloudcross.ssp.model.MessageRead;
import com.cloudcross.ssp.service.IMessageReadService;
import com.cloudcross.ssp.service.IMessageService;

@Controller("back.messageController")
@RequestMapping("/back/main/ad/message")
public class MessageController extends SimpleController{
	
	@Autowired
	private IMessageService messageService;
	
	@Autowired
	private IMessageReadService messageReadService;
	
	/**
	 * @return 返回到消息提醒第一页。
	 */
	@RequestMapping
	public String index() {	
		return redirect(page("list"));
	}
	
	@RequestMapping("/list")
	public String list(Model model,
			@RequestParam HashMap<String, Object> paramMap,
			@RequestParam(defaultValue="1") int page) {
		//按信息类型搜索用
		if (paramMap.containsKey("type") && paramMap.get("type")!=null &&  paramMap.get("type")!=""){
			int type = Integer.parseInt(paramMap.get("type").toString());
			if(type == 4){
				paramMap.put("type", null);
			}
		}
		int totalRow = messageService.countByParams(paramMap);
		 
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);	
		List<Message> messageList = messageService.findByParams(paramMap, pager);
		System.out.println(Long.valueOf(getLoginUser().getId()));
		long accountId = Long.valueOf(getLoginUser().getId());
		List<Long> messageReadList = messageReadService.selectByAccountId(accountId);
		for(Message message : messageList) {	
			if(messageReadList.contains(message.getId())){
				message.setRead(true);
			}else{
				message.setRead(false);
			}	
		}
		model.addAllAttributes(paramMap);
		model.addAttribute("pager", pager);
		model.addAttribute("messageList", messageList);
		return page("list");
	}
	
	@RequestMapping("isRead")
	public @ResponseBody String read(Model model,@RequestParam long messageId){
		MessageRead mr =new MessageRead();
		mr.setAccountId((long) getLoginUser().getId());
		mr.setMessageId(messageId);
		messageReadService.add(mr);
		return OK;
	}

}