package com.qmth.qrzk.repository.user.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qmth.qrzk.repository.common.base.BaseDao;
import com.qmth.qrzk.repository.exception.BizException;
import com.qmth.qrzk.repository.pager.service.ZujuanService;
import com.qmth.qrzk.repository.service.query.TaskQueryParams;
import com.qmth.qrzk.repository.task.Message;
import com.qmth.qrzk.repository.user.model.User;

@Service
public class MessageServiceImpl {
	
	private final static Logger log = Logger.getLogger(MessageServiceImpl.class);
	
	@Autowired private BaseDao dao;
	@Autowired
	private CourseServiceImpl courseService;
	
	@Autowired
	private BookServiceImpl bookService;
	
	@Autowired
	private TaskBatchImpl taskBatchService;
	
	@Autowired
	private UserServiceImpl userService;
	
	@Autowired
	private ZujuanService zujuanService;
	
	public List<Message> queryRelatedMessage(TaskQueryParams params){
		List<Message> resultList = dao.getPagerList("queryRelatedMessage", params);
		return resultList;
	}
	
	/**
	 * 修改消息为已读
	 * @param taskId
	 */
	public void updateMsgStatus(int taskId, Integer userId){
		Message msg = dao.get("getMessageByTaskId", taskId);
		Date date = new Date();
		if(msg != null && msg.getMsgStatus() == 1 && userId.equals(msg.getReceivedId())){//修改
			msg.setMsgStatus(2);
			msg.setUpdateTime(date);
			dao.update("updateMessage", msg);
		}
	}
	
	/**
	 * 保存消息
	 * @param taskId
	 * @param nextUserId
	 * @param curUser
	 * @throws BizException
	 */
	public void saveMessage(int taskId,int nextUserId,User curUser){
		Message msg = dao.get("getMessageByTaskId", taskId);
		Date date = new Date();
		if(msg != null){//修改
			msg.setUpdateTime(date);
			msg.setReceivedId(nextUserId);
			msg.setSenderId(curUser.getId());
			msg.setMsgStatus(1);
			msg.setType(1);
			
			dao.update("updateMessage", msg);
		}else{//新增
			msg = new Message();
			msg.setTaskId(taskId);
			msg.setCreateTime(date);
			msg.setReceivedId(nextUserId);
			msg.setSenderId(curUser.getId());
			msg.setMsgStatus(1);
			msg.setType(1);
			
			dao.update("addMessage", msg);
		}
		
	}
	
}
