package com.yihu.wlyy.service.app.message;

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

import javax.transaction.Transactional;

import com.yihu.wlyy.entity.message.Message;
import com.yihu.wlyy.repository.message.MessageDao;
import com.yihu.wlyy.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;

import com.yihu.wlyy.entity.consult.ConsultTeam;
import com.yihu.wlyy.repository.consult.ConsultTeamDao;
import com.yihu.wlyy.service.BaseService;

/**
 * 消息业务处理类
 * @author George
 *
 */
@Component
@Transactional(rollbackOn = Exception.class)
public class MessageService extends BaseService {

	@Autowired
	private ConsultTeamDao consultTeamDao;
	@Autowired
	private MessageDao messageDao;

	/**
	 * 汇总查询医生的消息总数
	 * @param doctor
	 * @return
	 */
	public JSONObject findDoctorAllMessageAmount(String doctor) {
		// 三师咨询未读消息总数
		int consult = 0;
		try {
			consult = consultTeamDao.amountAllDoctorUnread(doctor);
		} catch (Exception e) {
		}
		// 签约未读消息总数
		int sign = messageDao.amountUnreadByReceiver(doctor);
		// 体征指标未读消息总数
		int healthIndex = messageDao.amountUnreadHealthByReceiver(doctor);
		JSONObject json = new JSONObject();
		json.put("consultTeam", consult);
		json.put("sign", sign);
		json.put("healthIndex", healthIndex);
		return json;
	}

	/**
	 * 查询医生未读消息和最后消息
	 *
	 * @param doctor
	 * @return
	 */
	public JSONObject findDoctorAllMessage(String doctor){
		// 三师咨询未读消息总数
		int consult = 0;
		JSONObject consultJson =  new JSONObject();
		try {
			consult = consultTeamDao.amountAllDoctorUnread(doctor);
		} catch (Exception e) {
		}

		consultJson.put("amount",consult);

		if(consult > 0){
			PageRequest pageRequest = new PageRequest(0,1);
			Page<Object> msgs = consultTeamDao.AllDoctorUnreadLast(doctor,pageRequest);

			if(msgs != null && msgs.getSize() > 0){
				for(Object msg : msgs){
					Object[] msgArray = (Object[])msg;
					JSONObject msgJson = new JSONObject();
					msgJson.put("msg",msgArray[0].toString() + "向您发来一个咨询");
					msgJson.put("msgTime",msgArray[1] != null? DateUtil.dateToStr((Date) msgArray[1],DateUtil.YYYY_MM_DD):"");
					consultJson.put("lastMessage",msgJson);
				}
			}
		}

		int famousConsult = 0;
		JSONObject famousJson = new JSONObject();

		try {
			famousConsult = consultTeamDao.amountAlFamouslDoctorUnread(doctor);
		} catch (Exception e) {
		}

		famousJson.put("amount",famousConsult);

		if(famousConsult > 0){
			PageRequest pageRequest = new PageRequest(0,1);
			Page<Object> msgs = consultTeamDao.AllDoctorFamousUnreadLast(doctor,pageRequest);

			if(msgs != null && msgs.getSize() > 0){
				for(Object msg : msgs){
					Object[] msgArray = (Object[])msg;
					JSONObject msgJson = new JSONObject();
					msgJson.put("msg",msgArray[0].toString() + "向您发来一个咨询");
					msgJson.put("msgTime",msgArray[1] != null? DateUtil.dateToStr((Date) msgArray[1],DateUtil.YYYY_MM_DD):"");
					famousJson.put("lastMessage",msgJson);
				}
			}
		}

		// 签约未读消息总数
		int sign = messageDao.amountUnreadByReceiver(doctor);
		JSONObject signJson =  new JSONObject();
		signJson.put("amount",sign);
		if(sign > 0){
			PageRequest pageRequest = new PageRequest(0,1);
			Page<Message> msgs = messageDao.amountUnreadLastByReceiver(doctor,pageRequest);

			if(msgs != null && msgs.getSize() > 0){
				for(Message msg : msgs){
					JSONObject msgJson = new JSONObject();
					if(msg.getSignStatus().equals("4")){
						msgJson.put("msg", msg.getSenderName() + "申请与您解除家庭签约");
					}else{
						msgJson.put("msg", msg.getSenderName() + "申请与您签约家庭医生");
					}
					msgJson.put("msgTime",msg.getCzrq() != null? DateUtil.dateToStr(msg.getCzrq(),DateUtil.YYYY_MM_DD):"");
					signJson.put("lastMessage",msgJson);
				}
			}
		}

		// 体征指标未读消息总数
		int healthIndex = messageDao.amountUnreadHealthByReceiver(doctor);
		JSONObject indexJson =  new JSONObject();
		indexJson.put("amount",healthIndex);
		if(sign > 0){
			PageRequest pageRequest = new PageRequest(0,1);
			Page<Message> msgs = messageDao.amountUnreadHealthLastByReceiver(doctor,pageRequest);

			if(msgs != null && msgs.getSize() > 0){
				for(Message msg : msgs){
					JSONObject msgJson = new JSONObject();
					msgJson.put("msg",msg.getContent());
					msgJson.put("msgTime",msg.getCzrq() != null? DateUtil.dateToStr(msg.getCzrq(),DateUtil.YYYY_MM_DD):"");
					indexJson.put("lastMessage",msgJson);
				}
			}
		}

		JSONObject json = new JSONObject();
		json.put("consult", consultJson);
		json.put("famousConsult", famousJson);
		json.put("sign", signJson);
		json.put("healthIndex", indexJson);
		return json;
	}

	/**
	 * 查询健康咨询列表
	 * @param doctor 医生标识
	 * @param id
	 * @param pagesize 分页大小
	 * @return
	 */
	public Page<ConsultTeam> findConsultListByDoctor(String doctor, long id, int pagesize) {
		if (pagesize <= 0) {
			pagesize = 10;
		}
		// 排序
		Sort sort = new Sort(Direction.DESC, "id");
		// 分页信息
		PageRequest pageRequest = new PageRequest(0, pagesize, sort);
			//健康咨询
		if (id > 0) {
			return consultTeamDao.findListByUnreadDoctor(doctor, id, pageRequest);
		} else {
			return consultTeamDao.findListByUnreadDoctor(doctor, pageRequest);
		}

	}

	/**
	 * 查询体征消息列表
	 * @param doctor 医生标识
	 * @param id
	 * @param pagesize 分页大小
	 * @return
	 */
	public Page<Message> findHealthListByDoctor(String doctor, long id, int pagesize, String isRead) {
		if (pagesize <= 0) {
			pagesize = 10;
		}
		// 排序
		Sort sort = new Sort(Direction.DESC, "id");
		// 分页信息
		PageRequest pageRequest = new PageRequest(0, pagesize, sort);
		// 设置查询条件
		Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
		filters.put("receiver", new SearchFilter("receiver", Operator.EQ, doctor));
		filters.put("type", new SearchFilter("type", Operator.EQ, "2"));
		if (id > 0) {
			filters.put("id", new SearchFilter("id", Operator.LT, id));
		}
		if (StringUtils.isNoneEmpty(isRead)) {
			filters.put("read", new SearchFilter("read", Operator.EQ, Integer.parseInt(isRead)));
		}
		Specification<Message> spec = DynamicSpecifications.bySearchFilter(filters.values(), Message.class);
		return messageDao.findAll(spec, pageRequest);
	}

	/**
	 * 更新体征消息为已读
	 * @param msgid
	 */
	public int readHealth(long msgid) {
		return messageDao.read(msgid);
	}

	/**
	 * 根据参数查询指定的消息
	 * @return
	 */
	public Message findMessage(String sender, String receiver, String signStatus) {

		return messageDao.findByParams(sender, receiver, signStatus);
	}

}
