package com.iamberry.app.api.controller;

import static com.iamberry.app.config.Response.SUCCESS;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.iamberry.app.api.util.Jdpush;
import com.iamberry.app.config.Response;
import com.iamberry.app.core.dto.JpushMessageDTO;
import com.iamberry.app.core.entity.Message;
import com.iamberry.app.core.entity.User;
import com.iamberry.app.core.serch.SerchParam;
import com.iamberry.wechat.core.entity.PageBean;
import com.iamberry.wechat.core.entity.banner.MessageDTO;

/**
 * MessageController
 *
 * @author lc
 * @date 2016年9月13日17:50:59
 */
@Controller
@RequestMapping("/secure/message")
public class MessageController extends BaseController {

	@InitBinder("message")
	public void initBinderMessage(WebDataBinder binder) {
		binder.setFieldDefaultPrefix("message.");
	}

	
	/**
	 * 查询所有消息 并分页
	 * 2016年9月14日09:40:10
	 * @author lc
	 * @param page	分页信息
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView getMessageList(@RequestParam(value= "pageSize",defaultValue= "15" ,required=false) Integer pageSize, 
			@RequestParam(value = "pageNO", defaultValue = "1",required=false) Integer pageNO,
			SerchParam params,
			HttpServletRequest request) throws Exception {
		StringBuffer url = new StringBuffer("/secure/message/list?pageSize=" + pageSize);
		ModelAndView mv = new ModelAndView("message/messageList");
		//String goodName = request.getParameter("goodsInfoGoodname");
		PageBean page = new PageBean();	//分页信息
		page.setPageSize(pageSize);
		page.setPageNumber(pageNO);
		
		if (StringUtils.isNoneEmpty(params.getTitle())) {
			url.append("&title=" + params.getTitle());
		}
		if (StringUtils.isNoneEmpty(params.getBeginDate())) {
			url.append("&beginDate=" + params.getBeginDate());
		}
		if (StringUtils.isNoneEmpty(params.getEndDate())) {
			url.append("&endDate=" + params.getEndDate());
		}
		if (StringUtils.isNoneEmpty(params.getUsername())) {
			url.append("&username=" + params.getUsername());
		}
		
System.out.println(url);
		page.setParams(params);
		
		List<Message> messages = messageService.selectMessageRecoreds(page);
		url.append("&pageNO=");
		int count = messageService.selectMessageCount(params);
		int pageCount =  count % page.getPageSize() == 0? count/page.getPageSize():(count/page.getPageSize())+1;
		//分页用
		mv.addObject("list", messages);
		mv.addObject("pageNO", pageNO);
		mv.addObject("url", url);
		mv.addObject("params", params);
		mv.addObject("pageSize", pageCount);	
		return mv;
	}
	
	/**
	 * 查询所有用户信息 并分页
	 * 2016年9月14日09:40:10
	 * @author lc
	 * @param page	分页信息
	 * @return
	 */
	@RequestMapping("/listuser")
	public ModelAndView getUserList(@RequestParam(value= "pageSize",defaultValue= "15" ,required=false) Integer pageSize, 
			@RequestParam(value = "pageNO", defaultValue = "1",required=false) Integer pageNO, 
			SerchParam params,
			HttpServletRequest request) throws Exception {
		StringBuffer url = new StringBuffer("/secure/message/listuser?pageSize=" + pageSize);
		ModelAndView mv = new ModelAndView("message/userList");
		PageBean page = new PageBean();	//分页信息
		page.setPageSize(pageSize);
		page.setPageNumber(pageNO);
		if (StringUtils.isNoneEmpty(params.getUsername())) {
			url.append("&username=" + params.getUsername());
		}
		
		page.setParams(params);//设置查询条件
		List<User> users = messageService.selectUser(page);
		url.append("&pageNO=");
		int count = messageService.selectUserCount(params);
		int pageCount =  count % page.getPageSize() == 0? count/page.getPageSize():(count/page.getPageSize())+1;
		//分页用
		mv.addObject("memberList", users);
		mv.addObject("pageNO", pageNO);
		mv.addObject("url", url);
		mv.addObject("username", params.getUsername());
		mv.addObject("pageSize", pageCount);	
		return mv;
	}
	
	/**
	 * 进入添加页面
	 * 2016年4月21日
	 * @author 穆再兴
	 * @return
	 */
	@RequestMapping(value ="/insert", method = RequestMethod.GET)
	public ModelAndView toinsertMessage(){
		ModelAndView mv = new ModelAndView("message/insertMessage");
		return mv;
	}
	
	/**
	 * 添加一个消息
	 * 2016年9月14日09:48:12
	 * @author lc
	 * @return
	 */
	@RequestMapping(value ="/insert", method = RequestMethod.POST)
	public ModelAndView insertMessage(HttpServletRequest req,Message message){
		ModelAndView mv = new ModelAndView("message/insertMessage");
		
		Integer n = 0;
		//这里判断是否需要推送，调用推送util
		if(message.getIs_needsend()==1){ //1需要推送，2不需要
			String sendresult = Jdpush.buildPushObject_all_notifi(message);
			message.setSend_result(sendresult);
		}
		//设置调用推送结果，
		n =  messageService.insertMessage(message);
		
		if(n > 0){
			mv.addObject("msgObj", new MessageDTO(true, "操作结果", "添加成功！"));
		}else{
			mv.addObject("msgObj", new MessageDTO(true, "操作结果", "添加失败！"));
		}
		
		return mv;
	}
	
	
	@RequestMapping(value = "/sendMessage", method = RequestMethod.GET)
	private ModelAndView sendMessage() {
		ModelAndView mv = new ModelAndView("/message/sendMessage");
		return mv;
	}
	
	/**
	 * 发送极光推送
	 * @param content 内容
	 * @param tag 目标人群的标签
	 * @param platform 平台
	 * @return
	 */
	@RequestMapping(value = "/sendMessage", method = RequestMethod.POST)
	private ModelAndView sendMessage2(JpushMessageDTO jpushmessage) {
		ModelAndView mv = new ModelAndView("/message/sendMessage");
		String  resultCode = Jdpush.sendmessage_jpushmessage(jpushmessage);
		
		Message message = new Message();
		message.setTitle(jpushmessage.getContent());
		message.setContent(jpushmessage.getContent());
		message.setUser(Long.parseLong(jpushmessage.getTag())); //tag 有规范，徐特殊处理
		message.setRemark(jpushmessage.getPlatform());
		message.setSend_result(resultCode);
		message.setUrl(request.getParameter("url"));
		//添加到数据库
		messageService.insertMessage(message);
System.out.println(resultCode);
		return mv;
	}
	
	/**
	 * 点击发送极光推送
	 * @param content 内容
	 * @return
	 */
	@RequestMapping(value = "/sendMessageByid", method = RequestMethod.POST)
	@ResponseBody
	private MessageDTO sendMessageByid(@RequestParam(value = "recordId") Long recordId) {
		Message message = messageService.selectUserMessageByid(recordId);
		//修改到数据库
		String sendresult = Jdpush.buildPushObject_all_notifi(message);
		message.setSend_result(sendresult);
		int i = messageService.updateMessage(message);
		return new MessageDTO(true, "操作结果",sendresult);
	}
	
	/**
	 * 获取用户已读，未读消息
	 * @param token 用户token
	 * @param isread 1已读，2 未读
	 * @return 用户已读，未读的条数 
	 */
	@RequestMapping(value = "/select_userMessage_byisread", method = RequestMethod.POST)
	@ResponseBody
	private Response selectUserMessageByisread(@RequestParam(value = "token") String token,@RequestParam("isread") Long isread) {
		int messCount = messageService.selectUserMessageByisread(token,isread);
		if (messCount == -1){
			return Response.INVALID_TOKEN;
		}
		return SUCCESS.setData(messCount, messCount);
	}
	
	/**
	 * 根据用户token获取用户的所有消息
	 * @param token 用户token
	 * @return 用户的所有消息
	 */
	@RequestMapping(value = "/select_userMessage_recoreds", method = RequestMethod.POST)
	@ResponseBody
	private Response selectUserMessageRecoreds(@RequestParam(value = "token") String token) {
		List<Message> messages = messageService.selectUserMessageRecoreds(token);
		if (messages == null){
			return Response.INVALID_TOKEN;
		}
		return SUCCESS.setData(messages, messages.size());
	}
	
	/**
	 * 根据消息id获取消息实体类--并修改为已读
	 * @param recordId 消息实体类主键id
	 * @return 消息实体类
	 */
	@RequestMapping(value = "/select_userMessage_byid", method = RequestMethod.POST)
	@ResponseBody
	private Response selectUserMessageByid(@RequestParam(value = "recordId") Long recordId) {
		Message message = messageService.selectUserMessageByid(recordId);
		if (message == null){
			return Response.NOT_FOUND;
		}
		return SUCCESS.setData(message, 1);
	}
}
