package com.hotent.portal.persistence.manager.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hotent.base.query.PageBean;
import com.hotent.base.query.QueryOP;
import com.hotent.base.util.BeanUtils;
import com.hotent.portal.params.MessaboxVo;
import com.hotent.portal.vo.SysMsgTempletDetailVo;
import com.hotent.portal.vo.SysMsgTempletVo;
import com.hotent.uc.api.service.IUserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

import com.hotent.base.manager.impl.BaseManagerImpl;
import com.hotent.base.model.CommonResult;
import com.hotent.base.query.PageList;
import com.hotent.base.query.QueryFilter;
import com.hotent.base.util.SQLUtil;
import com.hotent.base.util.StringUtil;
import com.hotent.base.util.UniqueIdUtil;
import com.hotent.portal.model.MessageReceiver;
import com.hotent.portal.model.SysExecutor;
import com.hotent.portal.model.SysMessage;
import com.hotent.portal.persistence.dao.SysMessageDao;
import com.hotent.portal.persistence.manager.MessageReceiverManager;
import com.hotent.portal.persistence.manager.SysMessageManager;
import com.hotent.uc.api.impl.util.ContextUtil;
import com.hotent.uc.api.model.IUser;

/**
 * 系统信息处理实现类
 * 
 * @company 广州宏天软件股份有限公司
 * @author hugh
 * @email zxh@jee-soft.cn
 * @date 2018年6月21日
 */
@Service("sysMessageManager")
public class SysMessageManagerImpl extends BaseManagerImpl<SysMessageDao, SysMessage> implements SysMessageManager{

	@Resource
	MessageReceiverManager messageReceiverManager;
	@Resource
	IUserService iUserService;
	
	@Override
	public PageList<SysMessage> getMsgByUserId(QueryFilter queryFilter) {
		page(queryFilter.getPageBean());
		Map<String,Object> map = new HashMap<>();
		map = queryFilter.getInitParams();
		Map<String, Object> params = queryFilter.getParams();
		if (params != null) {
			map.putAll(params);
		}
		queryFilter.setQuerys(new ArrayList<>());
		return new PageList<>(baseMapper.getMsgByUserId(convert2IPage(queryFilter.getPageBean()),map,convert2Wrapper(queryFilter, currentModelClass())));
	}

	@Override
	public PageList<SysMessage> getMsgListNoUser(QueryFilter queryFilter) {
		page(queryFilter.getPageBean());
		Map<String,Object> map = new HashMap<>();
		map = queryFilter.getInitParams();
		Map<String, Object> params = queryFilter.getParams();
		if (params != null) {
			map.putAll(params);
		}
		queryFilter.setQuerys(new ArrayList<>());
		return new PageList<>(baseMapper.getMsgListNoUser(convert2IPage(queryFilter.getPageBean()),map,convert2Wrapper(queryFilter, currentModelClass())));
	}

	@Override
	public List<SysMessage> getNotReadMsgByUserId(String userId, int isPublish) {
		return baseMapper.getNotReadMsgByUserId(userId, isPublish);
	}

	@Override
	public void updateDelFlagByIds(List<String> ids) {
		baseMapper.updateDelFlagByIds(ids);
	}

	@Override
	public SysMessage getMsgById(String id) {
		return baseMapper.getMsgById(id);
	}

	@Override
	public CommonResult<String> sendMsg(String subject, String content,String messageType, String senderId, String senderName, List<SysExecutor> receivers,
										String ownerSource, String ownerSourceId) {
		try {
			String id = UniqueIdUtil.getSuid();
			SysMessage sysMessage = new SysMessage();
			sysMessage.setId(id);
			sysMessage.setSubject(subject);
			sysMessage.setContent(content);
			sysMessage.setOwnerId(StringUtil.isEmpty(senderId)?"-1":senderId);
			sysMessage.setOwner(StringUtil.isEmpty(senderName)?"系统":senderName);
			sysMessage.setMessageType(messageType);
			sysMessage.setCanReply((short)0);
			sysMessage.setIsPublic((short)0);
			sysMessage.setCreateTime(LocalDateTime.now());
			//processDefId_ -> 1798300861001138176
			sysMessage.setOwnerSource(StringUtil.isEmpty(ownerSource)?"-1":ownerSource);
			sysMessage.setOwnerSourceId(StringUtil.isEmpty(ownerSourceId)? null: ownerSourceId);
			this.create(sysMessage);

			for (SysExecutor sysExecutor : receivers) {
				MessageReceiver receiver = new MessageReceiver();
				receiver.setId(UniqueIdUtil.getSuid());
				receiver.setMsgId(id);
				receiver.setReceiverId(sysExecutor.getId());
				receiver.setReceiver(sysExecutor.getName());
				receiver.setReceiverType(sysExecutor.getType());
				messageReceiverManager.create(receiver);
			}
			return new CommonResult<>(true, "发送消息成功!");
		} catch (Exception e) {
			throw e;
		}
	}

	/**
	 * 获取用户已读未读消息
	 * @param account
	 * @return
	 * @throws Exception
	 */
	@Override
	public MessaboxVo getMessBoxInfo(String account) throws Exception {
		IUser user = iUserService.getUserByAccount(account);
		int messCount = 0;
		int noReadMessCount = 0;
		if(BeanUtils.isNotEmpty(user)){
			QueryFilter queryFilter = QueryFilter.build().withPage(new PageBean(1,PageBean.WITHOUT_PAGE));
			queryFilter.addFilter("receiverId", ContextUtil.getCurrentUserId(), QueryOP.EQUAL);
			PageList<SysMessage> sysMessageList = this.getMsgByUserId(queryFilter);
			messCount = (int)sysMessageList.getTotal();
			if(messCount>0){
				for (SysMessage message : sysMessageList.getRows()) {
					if(BeanUtils.isEmpty(message.getReceiveTime())){
						++noReadMessCount;
					}
				}
			}
		}
		return new MessaboxVo(messCount, noReadMessCount);
	}


	@Override
	public void addMessageSend(SysMessage sysMessage) {
		String messageId=sysMessage.getId();
		String receiverIds = sysMessage.getReceiverId();
		String receiverNames = sysMessage.getReceiverName();
		String receiverOrgIds = sysMessage.getReceiverOrgId();
		String receiverOrgNames = sysMessage.getReceiverOrgName();
		IUser sender = ContextUtil.getCurrentUser();
		messageId = UniqueIdUtil.getSuid();
		sysMessage.setId(messageId);
		sysMessage.setOwnerId(sender.getUserId());
		sysMessage.setOwner(sender.getFullname());
		sysMessage.setCreateTime(LocalDateTime.now());
		
		//如果是公告，则不存在接收人，不在接收人表中添加信息，不能回复，
		if (SysMessage.iS_PUBLIC_YES.equals(sysMessage.getIsPublic())) {
			this.create(sysMessage);
			return;//直接返回，不做以后操作
		}
		//把发送给组织的也设置给人员字段，保存到数据库
		String receriver = "";
		if (StringUtil.isNotEmpty(receiverNames)&&StringUtil.isNotEmpty(receiverOrgNames)) {
			receriver = receiverNames+","+receiverOrgNames;
		}else if (StringUtil.isNotEmpty(receiverNames)&&StringUtil.isEmpty(receiverOrgNames)) {
			receriver=receiverNames;
		}else if(StringUtil.isEmpty(receiverNames)&&StringUtil.isNotEmpty(receiverOrgNames)){
			receriver=receiverOrgNames;
		}
		sysMessage.setReceiverName(receriver);
		this.create(sysMessage);
		
		
		//转换人员
		if (StringUtil.isNotEmpty(receiverIds)) {
			String[] idArr = receiverIds.split(",");
			String[] nameArr = receiverNames.split(",");
			for (int i = 0; i < idArr.length; i++) {
				String id=idArr[i];
				if (StringUtil.isEmpty(id)) continue;
				String name="";
				if (nameArr.length>i)
					name=nameArr[i];
				MessageReceiver receiver = new MessageReceiver();
				receiver.setId(UniqueIdUtil.getSuid());
				receiver.setMsgId(messageId);
				receiver.setReceiverType(MessageReceiver.TYPE_USER);
				receiver.setReceiverId(id);
				receiver.setReceiver(name);
				messageReceiverManager.create(receiver);
			}
		}
		//转换组织
		if (StringUtil.isNotEmpty(receiverOrgIds)) {
			String[] orgIdArr = receiverOrgIds.split(",");
			String[] orgNameArr = receiverOrgNames.split(",");
			for (int i = 0; i < orgIdArr.length; i++) {
				String id=orgIdArr[i];
				if (StringUtil.isEmpty(id)) continue;
				String name="";
				if (orgNameArr.length>i)
					name=orgNameArr[i];
				MessageReceiver receiver = new MessageReceiver();
				receiver.setId(UniqueIdUtil.getSuid());
				receiver.setMsgId(messageId);
				receiver.setReceiverType(MessageReceiver.TYPE_GROUP);
				receiver.setReceiverId(id);
				receiver.setReceiver(name);
				messageReceiverManager.create(receiver);
			}
		}
	}
	/**
	 * 获取最新一条的未读的消息
	 */
	@Override
	public SysMessage getNotReadMsg(String userId) {
		String dbtype = SQLUtil.getDbType();
		if(dbtype.equals("db2")){
			return baseMapper.getOneNotReadMsgByUserIdDb2(userId);
			}else if(dbtype.equals("oracle")){
			return baseMapper.getOneNotReadMsgByUserIdOracl(userId);
			}else if(dbtype.equals("mssql")){
			return baseMapper.getOneNotReadMsgByUserIdMssql(userId);
			}else{
			return baseMapper.getOneNotReadMsgByUserIdMysql(userId);	
			}
	}

	/**
	 * 获取未读消息数量
	 * @param userId
	 * @return
	 */
	@Override
	public Map<String, Object> getNoReadMsgbadge(String userId) {
		return baseMapper.getNoReadMsgbadge(userId);
	}
	
	/**
	 * 获取未读消息的条数
	 */
	@Override
	public int getNotReadMsgNum(String userId, String isPublic) {
		return baseMapper.getNotReadMsgNum(userId, isPublic).size();
	}

	@Override
	public int getMsgSize(String receiverId, String isPublic) {
		return baseMapper.getMsgSize(receiverId, isPublic).size();
	}

	@Override
	public PageList<SysMsgTempletVo> querySysMsgTempletList(QueryFilter queryFilter) {
		PageBean pageBean = queryFilter.getPageBean();
		IPage<SysMsgTempletVo> result = baseMapper.querySysMsgTempletList(convert2IPageNew(pageBean), convert2Wrapper(queryFilter, currentModelClass(SysMsgTempletVo.class)));
		return new PageList<SysMsgTempletVo>(result);
	}

	@Override
	public List<SysMsgTempletDetailVo> querySysMsgTempletDetailList(String refId) {
		return baseMapper.querySysMsgTempletDetailList(refId);
	}
	/**
	 * 获取 消息模板
	 * @param templetCode 模板编号
	 */
	@Override
	public List<Map<String, Object>> getSysMsgTempletByCode(String templetCode) {
		return baseMapper.getSysMsgTempletByCode(templetCode);
	}

	/**
	 * 获取 消息模板子表
	 * @param refId 主表ID
	 */
	@Override
	public List<Map<String, Object>> getSysMsgTempletChildById(String refId) {
		return baseMapper.getSysMsgTempletChildById(refId);
	}

	public IPage convert2IPageNew(PageBean pageBean) {
		return pageBean == null ? new Page<>()
				: new Page(pageBean.getPage(), pageBean.getPageSize(), pageBean.showTotal());
	}

	public Class currentModelClass(Class<?> cls) {
		return ReflectionKit.getSuperClassGenericType(cls, 1);
	}

	// 获取消息数量
	@Override
	public Long queryMsgUserCount(String path, String startDate, String endDate) {
		return baseMapper.queryMsgUserCount(path, startDate, endDate);
	}
	// 获取消息类型数量统计
	@Override
	public List<Map<String, Object>> queryMsgUserCountBySource(String path, String startDate, String endDate) {
		return baseMapper.queryMsgUserCountBySource(path, startDate, endDate);
	}

	// 获取应用统计排名
	@Override
	public List<Map<String, Object>> queryMsgUserByAppRank(String path, String startDate, String endDate) {
		return baseMapper.queryMsgUserByAppRank(path, startDate, endDate);
	}

	// 获取天统计信息
	@Override
	public List<Map<String, Object>> queryMsgUserChartByDays(String path, String startDate, String endDate) {
		return baseMapper.queryMsgUserChartByDays(path, startDate, endDate);
	}
	// 获取月度统计信息
	@Override
	public List<Map<String, Object>> queryMsgUserChartByMonth(String path, String startDate, String endDate) {
		return baseMapper.queryMsgUserChartByMonth(path, startDate, endDate);
	}
}
