package com.hotent.portal.controller;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import javax.annotation.Resource;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.hotent.base.annotation.NewVersion;
import com.hotent.base.feign.UCFeignService;
import com.hotent.base.jms.JmsActor;
import com.hotent.base.jms.JmsProducer;
import com.hotent.base.jms.Notice;
import com.hotent.base.jms.NoticeMessageType;
import com.hotent.base.util.*;
import com.hotent.portal.model.MessageReceiver;
import com.hotent.portal.model.SysExecutor;
import com.hotent.portal.persistence.manager.MessageReceiverManager;
import com.hotent.portal.service.MessageReceiverService;
import com.hotent.portal.vo.SysMsgTempletDetailVo;
import com.hotent.portal.vo.SysMsgTempletVo;
import com.hotent.uc.api.impl.model.Org;
import com.hotent.uc.api.impl.vo.DemensionVo;
import com.hotent.uc.api.model.IGroup;
import com.hotent.uc.api.service.IUserService;
import freemarker.template.TemplateException;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.hotent.base.controller.BaseController;
import com.hotent.base.model.CommonResult;
import com.hotent.base.query.PageList;
import com.hotent.base.query.QueryFilter;
import com.hotent.portal.model.MessageRead;
import com.hotent.portal.model.SysMessage;
import com.hotent.portal.params.MessaboxVo;
import com.hotent.portal.persistence.manager.MessageReadManager;
import com.hotent.portal.persistence.manager.SysMessageManager;
import com.hotent.uc.api.impl.util.ContextUtil;
import com.hotent.uc.api.model.IUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 内部消息
 * 
 * @company 广州宏天软件股份有限公司
 * @author zhangxianwen
 * @email zhangxw@jee-soft.cn
 * @date 2018年7月17日
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@RestController
@RequestMapping("/innermsg/messageReceiver/v1")
@Api(tags="内部消息接收")
@NewVersion
public class MessageReceiverController extends BaseController{
	@Resource
	MessageReadManager messageReadManager;
	@Resource
	SysMessageManager sysMessageManager;
	@Autowired
	MessageReceiverService messageReceiver;
	@Resource
	MessageReceiverManager messageReceiverManager;
	@Resource
	IUserService iUserService;
	@Resource
	UCFeignService ucFeignService;

	@RequestMapping(value="list", method=RequestMethod.POST, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "消息列表", httpMethod = "POST", notes = "消息列表")
	public PageList<SysMessage> listJson(@ApiParam(name="queryFilter",value="通用查询对象")@RequestBody QueryFilter queryFilter) throws Exception {
		PageList<SysMessage> res=messageReceiver.listJson(queryFilter);
		return res;
	}

	/**
	 * 获取全部的 消息消息不指定用户(内部使用接口，不添加到接口列表中)
	 * @author: 梁宏锦
	 * @date: 2024/06/04
	 **/
	@RequestMapping(value="listNoUser", method=RequestMethod.POST, produces = { "application/json; charset=utf-8" })
	public PageList<SysMessage> userList(@ApiParam(name="queryFilter",value="通用查询对象")@RequestBody QueryFilter queryFilter) throws Exception {
		PageList<SysMessage> res = messageReceiver.listNoUser(queryFilter);
		return res;
	}

	@RequestMapping(value="edit", method=RequestMethod.GET, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "消息编辑页面信息", httpMethod = "GET", notes = "消息编辑页面信息")
	public MessageRead edit(@ApiParam(name="id", value="主键", required = false)@RequestParam String id) throws Exception {
		MessageRead messageRead = null;
		if(StringUtil.isNotEmpty(id)){
			messageRead = messageReadManager.get(id);
		}
		 return messageRead;
	}

	@RequestMapping(value="get", method=RequestMethod.GET, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "消息明细页面", httpMethod = "GET", notes = "消息明细页面")
	public SysMessage get(@ApiParam(name="id", value="主键", required = false)@RequestParam String id) throws Exception {
		SysMessage sysMessage = sysMessageManager.getMsgById(id);
		IUser user = ContextUtil.getCurrentUser();
		//保存到已读表
		messageReadManager.addMessageRead(id, user);
		//sysMessageManager.update(sysMessage);
		return sysMessage;
	}
	
	@RequestMapping(value="remove",method=RequestMethod.DELETE, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "删除消息记录", httpMethod = "DELETE", notes = "删除消息记录")
	public CommonResult<String> remove(@ApiParam(name="ids",value="任务记录ID，多个用“,”号分隔", required = true) @RequestParam String ids) throws Exception{
		String[] aryIds = null;
		if(!StringUtil.isEmpty(ids)){
			aryIds = ids.split(",");
		}
		sysMessageManager.removeByIds(Arrays.asList(aryIds));
		return new CommonResult<String>(true,"删除消息成功","");
	}
	
	@RequestMapping(value="getMessBoxInfo", method=RequestMethod.GET, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "获取用户已读未读消息", httpMethod = "GET", notes = "获取用户已读未读消息")
	public MessaboxVo getMessBoxInfo(@ApiParam(name="account", value="用户账号", required = true)@RequestParam String account) throws Exception {
		return messageReceiver.getMessBoxInfo(account);
	}

	@RequestMapping(value="mark",method={RequestMethod.GET, RequestMethod.POST}, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "标记为已读", httpMethod = "GET,POST", notes = "标记为已读")
	public CommonResult<String> mark(@ApiParam(name="ids",value="任务记录ID，多个用“,”号分隔", required = true) @RequestParam String ids) throws Exception{
		return messageReceiver.mark(ids);
	}

	/**
	 * 当前用户标记为全部已读
	 * @author: 梁宏锦
	 * @date: 2024/06/05
	 * @param isPublic: 消息类型 0:个人消息 1:系统消息
	 **/
	@RequestMapping(value="markAll",method={RequestMethod.GET}, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "当前用户标记为全部已读", httpMethod = "GET", notes = "当前用户标记为全部已读")
	public CommonResult<String> markAll(@ApiParam(name="isPublic", value="消息类型")@RequestParam String isPublic) throws Exception {
		if(!"0".equals(isPublic) && !"1".equals(isPublic)) {
			return new CommonResult(true,"消息类型错误");
		}

		IUser user = ContextUtil.getCurrentUser();
		//读取未读消息列表
		List<SysMessage> list = sysMessageManager.getNotReadMsgByUserId(ContextUtil.getCurrentUserId(), Integer.valueOf(isPublic));
		for (int i = 0; i < list.size(); i++) {
			SysMessage msg = list.get(i);
			String msgId = msg.getId();

			List<MessageRead> readList = messageReadManager.getByMessageId(msgId);
			if(readList==null || readList.size()==0) {
				MessageRead messageRead = new MessageRead();
				messageRead.setId(UniqueIdUtil.getSuid());
				messageRead.setMsgId(msgId);
				messageRead.setReceiverId(user.getUserId());
				messageRead.setReceiver(user.getFullname());
				messageRead.setReceiverTime(LocalDateTime.now());
				messageReadManager.create(messageRead);
			}
		}

		return new CommonResult(true,"全部已读成功");
	}

	@RequestMapping(value="delFlag",method=RequestMethod.GET, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "删除消息(状态删除)", httpMethod = "GET", notes = "删除消息(状态删除)")
	public CommonResult<String> delFlag(@ApiParam(name="ids",value="任务记录ID，多个用“,”号分隔", required = true) @RequestParam String ids) throws Exception{
		String[] aryIds = null;
		if(!StringUtil.isEmpty(ids)){
			aryIds = ids.split(",");
			sysMessageManager.updateDelFlagByIds(Arrays.asList(aryIds));
		}
		return new CommonResult<String>(true,"删除消息成功","");
	}

	@RequestMapping(value="getNoReadMsgbadge",method=RequestMethod.GET, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "获取当前用户未读消息数量", httpMethod = "GET", notes = "获取当前用户未读消息数量")
	public CommonResult<Map<String, Object>> getNoReadMsgbadge() throws Exception{
		Map<String, Object> badge = sysMessageManager.getNoReadMsgbadge(ContextUtil.getCurrentUserId());
		return new CommonResult<Map<String, Object>>(true,"获取成功", badge);
	}
	
	@RequestMapping(value="getMsgbadge",method=RequestMethod.GET, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "获取当前用户未读消息数量", httpMethod = "GET", notes = "获取当前用户未读消息数量")
	public CommonResult<Integer> getMsgbadge(@ApiParam(name="isPublic", value="是否系统公告", required = false)@RequestParam(required = false) String isPublic) throws Exception{
		if(StringUtil.isEmpty(isPublic)) {
			isPublic = "0"; //是否公告 0:个人 1:系统公告
		}
		int badge = sysMessageManager.getNotReadMsgNum(ContextUtil.getCurrentUserId(), isPublic);
		return new CommonResult<Integer>(true,"获取成功",badge);
	}

	@RequestMapping(value="getSysMsg", method=RequestMethod.GET, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "消息明细(不更新已读状态)", httpMethod = "GET", notes = "消息明细(不更新已读状态)")
	public SysMessage getSysMsg(@ApiParam(name="id", value="主键", required = false)@RequestParam String id) throws Exception {
		SysMessage sysMessage = sysMessageManager.getMsgById(id);
		return sysMessage;
	}

	@PostMapping(value="/saveSysMsgInfo")
	@ApiOperation(value = "保存系统消息", httpMethod = "POST", notes = "保存系统消息")
	public CommonResult<String> saveSysMsgInfo(@ApiParam(name="sysMessage",value="保存系统消息", required = true)@RequestBody SysMessage sysMessage) throws Exception{
		String msg = StringUtil.isEmpty(sysMessage.getId()) ? "添加系统消息成功" : "更新系统消息成功";
		String id = sysMessage.getId();
		String curUserId = ContextUtil.getCurrentUserId();

		if(StringUtil.isEmpty(sysMessage.getSubject())) {
			return new CommonResult<>(false, "消息主题不能为空");
		}
		if(StringUtil.isEmpty(sysMessage.getDescription())) {
			return new CommonResult<>(false, "消息摘要信息不能为空");
		}
		if(StringUtil.isEmpty(sysMessage.getMessageSourceType())) {
			return new CommonResult<>(false, "消息类型不能为空");
		}
		//消息类型 0:固定内容 1:跳转地址 2:资讯 3:应用 4:流程 5:移动应用 6:模板消息
		if(SysMessage.MESSAGE_SOURCE_TYPE_CONTENT.equals(sysMessage.getMessageSourceType())) {
			if(StringUtil.isEmpty(sysMessage.getContent())) {
				return new CommonResult<>(false, "消息内容不能为空");
			}
		} else if(SysMessage.MESSAGE_SOURCE_TYPE_URL.equals(sysMessage.getMessageSourceType())) {
			if(StringUtil.isEmpty(sysMessage.getMessageUrl())) {
				return new CommonResult<>(false, "消息跳转地址不能为空");
			}
		} else if(SysMessage.MESSAGE_SOURCE_TYPE_NEWS.equals(sysMessage.getMessageSourceType())) {
			if(StringUtil.isEmpty(sysMessage.getResourceId())) {
				return new CommonResult<>(false, "消息资讯Id不能为空");
			}
		} else if(SysMessage.MESSAGE_SOURCE_TYPE_APP_PC.equals(sysMessage.getMessageSourceType())) {
			if(StringUtil.isEmpty(sysMessage.getAppId())) {
				return new CommonResult<>(false, "应用Id不能为空");
			}
		} else if(SysMessage.MESSAGE_SOURCE_TYPE_FLOW.equals(sysMessage.getMessageSourceType())) {
			if(StringUtil.isEmpty(sysMessage.getFlowId())) {
				return new CommonResult<>(false, "流程Id不能为空");
			}
		} else if(SysMessage.MESSAGE_SOURCE_TYPE_APP_MOBILE.equals(sysMessage.getMessageSourceType())) {
			if(StringUtil.isEmpty(sysMessage.getAppMobileId())) {
				return new CommonResult<>(false, "移动应用Id不能为空");
			}
		} else if(SysMessage.MESSAGE_SOURCE_TYPE_TEMPLATE.equals(sysMessage.getMessageSourceType())) {
			if(StringUtil.isEmpty(sysMessage.getTemplateId()) || StringUtil.isEmpty(sysMessage.getTemplateName()) ||
					StringUtil.isEmpty(sysMessage.getTemplateData())) {
				return new CommonResult<>(false, "模板Id/模板名称/模板内容不能为空");
			}
		}

		if(StringUtil.isNotEmpty(id)) {
			sysMessage.setUpdateBy(curUserId);
			sysMessage.setUpdateTime(LocalDateTime.now());
			sysMessageManager.saveOrUpdate(sysMessage);
		} else {
			sysMessage.setId(UniqueIdUtil.getSuid());
			sysMessage.setOwnerId(curUserId);
			sysMessage.setOwner("系统");
			sysMessage.setMessageType(NoticeMessageType.INNER.key());
			sysMessage.setMessageTag(SysMessage.MESSAGE_TAG_SYS);
			sysMessage.setCanReply(SysMessage.iS_REPLY_NO);
			sysMessage.setIsPublic(SysMessage.iS_PUBLIC_YES);
			sysMessage.setCreateTime(LocalDateTime.now());
			sysMessageManager.save(sysMessage);
		}
		return CommonResult.<String>ok().message(msg);
	}

	@PostMapping(value="/saveSysUserMsgInfo")
	@ApiOperation(value = "保存个人消息", httpMethod = "POST", notes = "保存系统消息")
	public CommonResult<String> saveSysUserMsgInfo(@ApiParam(name="sysMessage",value="保存系统消息", required = true)@RequestBody SysMessage sysMessage) throws Exception{
		String msg = StringUtil.isEmpty(sysMessage.getId()) ? "添加系统消息成功" : "更新系统消息成功";
		String id = sysMessage.getId();
		String curUserId = ContextUtil.getCurrentUserId();

		if(StringUtil.isEmpty(sysMessage.getSubject())) {
			return new CommonResult<>(false, "消息主题不能为空");
		}
		if(StringUtil.isEmpty(sysMessage.getDescription())) {
			return new CommonResult<>(false, "消息摘要信息不能为空");
		}
		if(StringUtil.isEmpty(sysMessage.getMessageSourceType())) {
			return new CommonResult<>(false, "消息类型不能为空");
		}
		//消息类型 0:固定内容 1:跳转地址 2:资讯 3:应用 4:流程 5:移动应用 6:模板消息
		if(SysMessage.MESSAGE_SOURCE_TYPE_CONTENT.equals(sysMessage.getMessageSourceType())) {
			if(StringUtil.isEmpty(sysMessage.getContent())) {
				return new CommonResult<>(false, "消息内容不能为空");
			}
		} else if(SysMessage.MESSAGE_SOURCE_TYPE_URL.equals(sysMessage.getMessageSourceType())) {
			if(StringUtil.isEmpty(sysMessage.getMessageUrl())) {
				return new CommonResult<>(false, "消息跳转地址不能为空");
			}
		} else if(SysMessage.MESSAGE_SOURCE_TYPE_NEWS.equals(sysMessage.getMessageSourceType())) {
			if(StringUtil.isEmpty(sysMessage.getResourceId())) {
				return new CommonResult<>(false, "消息资讯不能为空");
			}
		} else if(SysMessage.MESSAGE_SOURCE_TYPE_APP_PC.equals(sysMessage.getMessageSourceType())) {
			if(StringUtil.isEmpty(sysMessage.getAppId())) {
				return new CommonResult<>(false, "PC应用不能为空");
			}
		} else if(SysMessage.MESSAGE_SOURCE_TYPE_FLOW.equals(sysMessage.getMessageSourceType())) {
			if(StringUtil.isEmpty(sysMessage.getFlowId())) {
				return new CommonResult<>(false, "流程Id不能为空");
			}
		} else if(SysMessage.MESSAGE_SOURCE_TYPE_APP_MOBILE.equals(sysMessage.getMessageSourceType())) {
			if(StringUtil.isEmpty(sysMessage.getAppMobileId())) {
				return new CommonResult<>(false, "移动应用不能为空");
			}
		} else if(SysMessage.MESSAGE_SOURCE_TYPE_TEMPLATE.equals(sysMessage.getMessageSourceType())) {
			if(StringUtil.isEmpty(sysMessage.getTemplateId()) || StringUtil.isEmpty(sysMessage.getTemplateName()) ||
					StringUtil.isEmpty(sysMessage.getTemplateData())) {
				return new CommonResult<>(false, "模板Id/模板名称/模板内容不能为空");
			}
		}

		String receiverId = sysMessage.getReceiverId();
		IUser user = iUserService.getUserById(receiverId);
		if(user==null) {
			return new CommonResult<>(false, "未匹配到该用户");
		}

		if(StringUtil.isNotEmpty(id)) {
			sysMessage.setUpdateBy(curUserId);
			sysMessage.setUpdateTime(LocalDateTime.now());
			sysMessageManager.saveOrUpdate(sysMessage);

			SysMessage sysUserMessage = sysMessageManager.getMsgById(id);
			String rid = sysUserMessage.getRid();
			MessageReceiver receiver = messageReceiverManager.get(rid);
			receiver.setReceiverId(user.getUserId());
			receiver.setReceiver(user.getFullname());
			messageReceiverManager.saveOrUpdate(receiver);
		} else {
			sysMessage.setId(UniqueIdUtil.getSuid());
			sysMessage.setOwnerId(curUserId);
			sysMessage.setOwner("系统");
			sysMessage.setMessageType(NoticeMessageType.INNER.key());
			sysMessage.setMessageTag(SysMessage.MESSAGE_TAG_USER);
			sysMessage.setCanReply(SysMessage.iS_REPLY_NO);
			sysMessage.setIsPublic(SysMessage.iS_PUBLIC_NO);
			sysMessage.setCreateTime(LocalDateTime.now());
			sysMessageManager.save(sysMessage);

			String sysMessageId = sysMessage.getId();
			MessageReceiver receiver = new MessageReceiver();
			receiver.setId(UniqueIdUtil.getSuid());
			receiver.setMsgId(sysMessageId);
			receiver.setReceiverId(user.getUserId());
			receiver.setReceiver(user.getFullname());
			receiver.setReceiverType(SysExecutor.TYPE_USER);
			messageReceiverManager.create(receiver);
		}
		return CommonResult.<String>ok().message(msg);
	}

	@RequestMapping(value="submitMsg",method={RequestMethod.GET,RequestMethod.POST})
	@ApiOperation(value = "发送消息", httpMethod = "GET,POST", notes = "发送消息")
	public CommonResult<Integer> submitMsg(
			@ApiParam(name="subject", value="消息标题", required = true)@RequestParam String subject,
			@ApiParam(name="content", value="消息内容", required = true)@RequestParam String content,
			@ApiParam(name="users", value="用户账号", required = true)@RequestParam String users) throws Exception{
//		List<IUser> recievers = new ArrayList<>();
//		IUserService userService = AppUtil.getBean(IUserService.class);
//		String[] arys = users.split(",");
//		for (int i = 0; i < arys.length; i++) {
//			IUser user = userService.getUserById(arys[i]);
//			recievers.add(user);
//		}
//		this.sendMsgNoTemplate(notifyType, recievers, subject, content);

		String messageType = "inner";
		List<SysExecutor> recievers = new ArrayList<SysExecutor>();
		IUserService userService = AppUtil.getBean(IUserService.class);
		String[] arys = users.split(",");
		for (int i = 0; i < arys.length; i++) {
			IUser user = userService.getUserById(arys[i]);
			SysExecutor executor = new SysExecutor(user.getUserId(), user.getFullname(), SysExecutor.TYPE_USER);
			recievers.add(executor);
		}
		String ownerSource = SysMessage.OWNER_SOURCE_PLATFORM;
		String ownerSourceId = "-1";
		sysMessageManager.sendMsg(subject, content, messageType, null, "人力资源部", recievers,
				ownerSource, ownerSourceId);

		//IUserService userService = AppUtil.getBean(IUserService.class);
		//String[] arys = users.split(",");
		//for (int i = 0; i < arys.length; i++) {
		//	IUser user = userService.getUserById(arys[i]);
		//	SysMessage sysMessage = new SysMessage();
		//	sysMessage.setId(UniqueIdUtil.getSuid());
		//	sysMessage.setSubject(subject);
		//	sysMessage.setContent(content);
		//	sysMessage.setMessageType("inner");
		//	sysMessage.setOwnerId("-1");
		//	sysMessage.setOwner("x7系统");
		//	sysMessage.setReceiverId(user.getUserId());
		//	sysMessage.setReceiverName(user.getUsername());
		//	sysMessage.setCanReply((short)0);
		//	sysMessage.setIsPublic((short)1);
		//	sysMessage.setCreateTime(LocalDateTime.now());
		//	sysMessageManager.addMessageSend(sysMessage);
		//}

		return new CommonResult<Integer>(true,"发送成功");
	}

	@RequestMapping(value="submitSmsMsg",method={RequestMethod.GET,RequestMethod.POST})
	@ApiOperation(value = "发送短信消息", httpMethod = "GET,POST", notes = "发送短信消息")
	public CommonResult<Integer> submitSmsMsg(
			@ApiParam(name="subject", value="消息标题", required = true)@RequestParam String subject,
			@ApiParam(name="content", value="消息内容", required = true)@RequestParam String content,
			@ApiParam(name="users", value="用户账号", required = true)@RequestParam String users) throws Exception{
		List<IUser> recievers = new ArrayList<>();
		IUserService userService = AppUtil.getBean(IUserService.class);
		String[] arys = users.split(",");
		for (int i = 0; i < arys.length; i++) {
			IUser user = userService.getUserById(arys[i]);
			recievers.add(user);
		}
		String messageType = "sms";

		sendMsgNoTemplate(messageType, recievers, subject, content);
		return new CommonResult<Integer>(true,"发送成功");
	}

	@RequestMapping(value="submitDingTalkMsg",method={RequestMethod.GET,RequestMethod.POST})
	@ApiOperation(value = "发送钉钉消息", httpMethod = "GET,POST", notes = "发送钉钉消息")
	public CommonResult<Integer> submitDingTalkMsg(
			@ApiParam(name="subject", value="消息标题", required = true)@RequestParam String subject,
			@ApiParam(name="content", value="消息内容", required = true)@RequestParam String content,
			@ApiParam(name="users", value="用户账号", required = true)@RequestParam String users) throws Exception{
		List<IUser> recievers = new ArrayList<>();
		IUserService userService = AppUtil.getBean(IUserService.class);
		String[] arys = users.split(",");
		for (int i = 0; i < arys.length; i++) {
			IUser user = userService.getUserById(arys[i]);
			recievers.add(user);
		}
		String messageType = "dingTalk";
		sendMsgNoTemplate(messageType, recievers, subject, content);
		return new CommonResult<Integer>(true,"发送成功");
	}

	/**
	 * IUser 转换为 JmsActor
	 * @param users
	 * @return
	 */
	public static List<JmsActor> parseJmsActor(List<IUser> users){
		List<JmsActor> actors = new ArrayList<>();
		for (IUser user:users){
			JmsActor actor = new JmsActor();
			actor.setId(user.getUserId());
			actor.setAccount(user.getAccount());
			actor.setName(user.getFullname());
			actor.setEmail(user.getEmail());
			actor.setMobile(user.getMobile());
			actor.setWeixin(user.getWeixin());
			actor.setClientId(user.getClientId());
			actor.setClientToken(user.getClientToken());
			actors.add(actor);
		}
		return actors;
	}

	public static void sendMsgNoTemplate(String notifyType, List<IUser> recievers,String subject,String content) throws Exception{
		if(StringUtils.isEmpty(notifyType)){
			return;
		}
		NoticeMessageType[] messageTypes = parseNotifyType(notifyType);
		List<JmsActor> recieverAccounts = parseJmsActor(recievers);

		IUser sender = ContextUtil.getCurrentUser();

		Notice notice = new Notice();
		// 设置为不使用模板
		notice.setUseTemplate(false);
		notice.setVars(new HashMap<>());
		notice.setSubject(subject);
		notice.setContent(content);
		notice.setMessageTypes(messageTypes);
		notice.setSender(sender.getAccount());
		notice.setReceiver(recieverAccounts);
		JmsProducer jmsProducer = AppUtil.getBean(JmsProducer.class);
		jmsProducer.sendToQueue(notice);
	}
	public static NoticeMessageType[] parseNotifyType(String notifyType) {
		if(notifyType==null) {
			notifyType= "";
		}
		String[] arys = notifyType.split(",");
		List<String> list = new ArrayList<String>(Arrays.asList(arys));
		return parseNotifyType(list);
	}
	public static NoticeMessageType[] parseNotifyType(List<String> nofifyTypes) {
		List<NoticeMessageType> messageTypeArrays = new ArrayList<>();
		EnumSet<NoticeMessageType> it = EnumSet.allOf(NoticeMessageType.class);
		for (NoticeMessageType type : it) {
			if(nofifyTypes.indexOf(type.key()) > -1) {
				messageTypeArrays.add(type);
			}
		}
		NoticeMessageType[] messageTypes = new NoticeMessageType[messageTypeArrays.size()];
		messageTypeArrays.toArray(messageTypes);
		return messageTypes;
	}

	@RequestMapping(value="querySysMsgTempletList",method={RequestMethod.GET,RequestMethod.POST})
	@ApiOperation(value = "查询模板消息列表", httpMethod = "GET,POST", notes = "查询模板消息列表")
	public PageList<SysMsgTempletVo> querySysMsgTempletList(@ApiParam(name="queryFilter",value="查询对象")@RequestBody QueryFilter queryFilter) throws Exception{
		PageList<SysMsgTempletVo> res = sysMessageManager.querySysMsgTempletList(queryFilter);
		List<SysMsgTempletVo> list = res.getRows();
		for (int i = 0; i < list.size(); i++) {
			SysMsgTempletVo vo = list.get(i);

			List<SysMsgTempletDetailVo> detailList = sysMessageManager.querySysMsgTempletDetailList(vo.getId());
			vo.getDetailList().addAll(detailList);
		}
		return res;
	}

	/**
	 * 获取消息数量
	 * @param orgId 0全部组织
	 * @param type 0:月度 1:季度 2:年度
	 * @param year 年
	 * @param data 1
	 */
	@RequestMapping(value="queryMsgUserCount",method={RequestMethod.GET,RequestMethod.POST})
	@ApiOperation(value = "获取消息数量", httpMethod = "GET,POST", notes = "获取消息数量")
	public CommonResult<Integer> queryMsgUserCount(@ApiParam(name="orgId", value="组织id")@RequestParam String orgId,
				@ApiParam(name="type", value="类型")@RequestParam String type,
				@ApiParam(name="year", value="数据")@RequestParam String year,
				@ApiParam(name="data", value="数据")@RequestParam String data) throws Exception{
		String path = "";
		String startDate = "";
		String endDate = "";
		if("0".equals(type)) { //月度
			LocalDate[] area = ChartUtil.getDateRangeByMonth(Integer.valueOf(year), Integer.valueOf(data));
			startDate = area[0].toString();
			endDate = area[1].toString();
		} else if("1".equals(type)) { //季度
			LocalDate[] area = ChartUtil.getDateRangeByQuarter(Integer.valueOf(year), Integer.valueOf(data));
			startDate = area[0].toString();
			endDate = area[1].toString();
		} else if("2".equals(type)) { //年度
			LocalDate[] area = ChartUtil.getDateRangeByYear(Integer.valueOf(year));
			startDate = area[0].toString();
			endDate = area[1].toString();
		}
		if("0".equals(orgId)) {
			ObjectNode node = ucFeignService.getDefaultDem();
			DemensionVo demension = JsonUtil.toBean(node.toString(), DemensionVo.class);
			path = demension.getId() + ".";
		} else {
			ObjectNode orgNode = ucFeignService.getOrgById(orgId);
			Org org = JsonUtil.toBean(orgNode.toString(), Org.class);
			path = org.getPath();
		}
		Long num = sysMessageManager.queryMsgUserCount(path, startDate, endDate);
		return new CommonResult<Integer>(true,"查询成功", num.intValue());
	}

	/**
	 * 获取消息类型数量统计
	 * @param orgId 0全部组织
	 * @param type 0:月度 1:季度 2:年度
	 * @param year 年
	 * @param data 1
	 */
	@RequestMapping(value="queryMsgUserCountBySource",method={RequestMethod.GET,RequestMethod.POST})
	@ApiOperation(value = "获取消息类型数量统计", httpMethod = "GET,POST", notes = "获取消息类型数量统计")
	public CommonResult<JSONObject> queryMsgUserCountBySource(@ApiParam(name="orgId", value="组织id")@RequestParam String orgId,
				   @ApiParam(name="type", value="类型")@RequestParam String type,
				   @ApiParam(name="year", value="数据")@RequestParam String year,
				   @ApiParam(name="data", value="数据")@RequestParam String data) throws Exception{
		String path = "";
		String startDate = "";
		String endDate = "";
		if("0".equals(type)) { //月度
			LocalDate[] area = ChartUtil.getDateRangeByMonth(Integer.valueOf(year), Integer.valueOf(data));
			startDate = area[0].toString();
			endDate = area[1].toString();
		} else if("1".equals(type)) { //季度
			LocalDate[] area = ChartUtil.getDateRangeByQuarter(Integer.valueOf(year), Integer.valueOf(data));
			startDate = area[0].toString();
			endDate = area[1].toString();
		} else if("2".equals(type)) { //年度
			LocalDate[] area = ChartUtil.getDateRangeByYear(Integer.valueOf(year));
			startDate = area[0].toString();
			endDate = area[1].toString();
		}
		if("0".equals(orgId)) {
			ObjectNode node = ucFeignService.getDefaultDem();
			DemensionVo demension = JsonUtil.toBean(node.toString(), DemensionVo.class);
			path = demension.getId() + ".";
		} else {
			ObjectNode orgNode = ucFeignService.getOrgById(orgId);
			Org org = JsonUtil.toBean(orgNode.toString(), Org.class);
			path = org.getPath();
		}
		List<Map<String, Object>> list = sysMessageManager.queryMsgUserCountBySource(path, startDate, endDate);
		int sysNum = 0;
		int appNum = 0;
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> map = list.get(i);
			String source = (String) map.get("ownerSource");
			Long num = (Long) map.get("num");
			if("-1".equals(source)) {
				sysNum += num.intValue();
			} else {
				appNum += num.intValue();
			}
		}
		JSONObject json = JSONUtil.createObj();
		json.set("sysNum", sysNum);
		json.set("appNum", appNum);
		return new CommonResult<JSONObject>(true,"查询成功", json);
	}

	/**
	 * 获取应用统计排名
	 * @param orgId 0全部组织
	 * @param type 0:月度 1:季度 2:年度
	 * @param year 年
	 * @param data 1
	 */
	@RequestMapping(value="queryMsgUserByAppRank",method={RequestMethod.GET,RequestMethod.POST})
	@ApiOperation(value = "获取应用统计排名", httpMethod = "GET,POST", notes = "获取应用统计排名")
	public CommonResult<List<Map<String, Object>>> queryMsgUserByAppRank(@ApiParam(name="orgId", value="组织id")@RequestParam String orgId,
				 @ApiParam(name="type", value="类型")@RequestParam String type,
				 @ApiParam(name="year", value="数据")@RequestParam String year,
				 @ApiParam(name="data", value="数据")@RequestParam String data) throws Exception{
		String path = "";
		String startDate = "";
		String endDate = "";
		if("0".equals(type)) { //月度
			LocalDate[] area = ChartUtil.getDateRangeByMonth(Integer.valueOf(year), Integer.valueOf(data));
			startDate = area[0].toString();
			endDate = area[1].toString();
		} else if("1".equals(type)) { //季度
			LocalDate[] area = ChartUtil.getDateRangeByQuarter(Integer.valueOf(year), Integer.valueOf(data));
			startDate = area[0].toString();
			endDate = area[1].toString();
		} else if("2".equals(type)) { //年度
			LocalDate[] area = ChartUtil.getDateRangeByYear(Integer.valueOf(year));
			startDate = area[0].toString();
			endDate = area[1].toString();
		}
		if("0".equals(orgId)) {
			ObjectNode node = ucFeignService.getDefaultDem();
			DemensionVo demension = JsonUtil.toBean(node.toString(), DemensionVo.class);
			path = demension.getId() + ".";
		} else {
			ObjectNode orgNode = ucFeignService.getOrgById(orgId);
			Org org = JsonUtil.toBean(orgNode.toString(), Org.class);
			path = org.getPath();
		}
		List<Map<String, Object>> list = sysMessageManager.queryMsgUserByAppRank(path, startDate, endDate);
		return new CommonResult<List<Map<String, Object>>>(true,"查询成功", list);
	}

	/**
	 * 获取消息数量
	 * @param orgId 0全部组织
	 * @param type 0:月度 1:季度 2:年度
	 * @param year 年
	 * @param data 1
	 */
	@RequestMapping(value="queryMsgUserChart",method={RequestMethod.GET,RequestMethod.POST})
	@ApiOperation(value = "获取消息数量", httpMethod = "GET,POST", notes = "获取消息数量")
	public CommonResult<JSONArray> queryMsgUserChart(@ApiParam(name="orgId", value="组织id")@RequestParam String orgId,
								  @ApiParam(name="type", value="类型")@RequestParam String type,
								  @ApiParam(name="year", value="数据")@RequestParam String year,
								  @ApiParam(name="data", value="数据")@RequestParam String data) throws Exception{
		String path = "";
		if("0".equals(orgId)) {
			ObjectNode node = ucFeignService.getDefaultDem();
			DemensionVo demension = JsonUtil.toBean(node.toString(), DemensionVo.class);
			path = demension.getId() + ".";
		} else {
			ObjectNode orgNode = ucFeignService.getOrgById(orgId);
			Org org = JsonUtil.toBean(orgNode.toString(), Org.class);
			path = org.getPath();
		}

		String startDate = "";
		String endDate = "";
		if("0".equals(type)) { //月度
			LocalDate[] area = ChartUtil.getDateRangeByMonth(Integer.valueOf(year), Integer.valueOf(data));
			startDate = area[0].toString();
			endDate = area[1].toString();

			List<Map<String, Object>> mapList = sysMessageManager.queryMsgUserChartByDays(path, startDate, endDate);
			Map<String, Object> map = new HashedMap();
			for (int i = 0; i < mapList.size() ; i++) {
				Map<String, Object> m = mapList.get(i);
				map.put(m.get("dateStr").toString(), m.get("num").toString());
			}

			List<LocalDate> list = ChartUtil.getDaysInMonth(Integer.valueOf(year), Integer.valueOf(data));
			JSONArray jsonArray = JSONUtil.createArray();
			for (int i = 0; i < list.size(); i++) {
				LocalDate date = list.get(i);
				String num = (String)map.get(date.toString());
				JSONObject json = JSONUtil.createObj();
				json.set("time", date.toString());
				json.set("value", num==null? 0: Integer.valueOf(num));
				jsonArray.add(json);
			}
			return new CommonResult<JSONArray>(true,"查询成功", jsonArray);
		} else if("1".equals(type)) { //季度
			LocalDate[] area = ChartUtil.getDateRangeByQuarter(Integer.valueOf(year), Integer.valueOf(data));
			startDate = area[0].toString();
			endDate = area[1].toString();

			List<Map<String, Object>> mapList = sysMessageManager.queryMsgUserChartByMonth(path, startDate, endDate);
			Map<String, Object> map = new HashedMap();
			for (int i = 0; i < mapList.size() ; i++) {
				Map<String, Object> m = mapList.get(i);
				map.put(m.get("dateStr").toString(), m.get("num").toString());
			}

			List<String> list = ChartUtil.getDaysInQuarter(Integer.valueOf(year), Integer.valueOf(data));
			JSONArray jsonArray = JSONUtil.createArray();
			for (int i = 0; i < list.size(); i++) {
				String date = list.get(i);
				String num = (String)map.get(date);
				JSONObject json = JSONUtil.createObj();
				json.set("time", date.toString());
				json.set("value", num==null? 0: Integer.valueOf(num));
				jsonArray.add(json);
			}
			return new CommonResult<JSONArray>(true,"查询成功", jsonArray);
		} else if("2".equals(type)) { //年度
			LocalDate[] area = ChartUtil.getDateRangeByYear(Integer.valueOf(year));
			startDate = area[0].toString();
			endDate = area[1].toString();

			List<Map<String, Object>> mapList = sysMessageManager.queryMsgUserChartByMonth(path, startDate, endDate);
			Map<String, Object> map = new HashedMap();
			for (int i = 0; i < mapList.size() ; i++) {
				Map<String, Object> m = mapList.get(i);
				map.put(m.get("dateStr").toString(), m.get("num").toString());
			}

			List<String> list = ChartUtil.getYearRange(Integer.valueOf(year));
			JSONArray jsonArray = JSONUtil.createArray();
			for (int i = 0; i < list.size(); i++) {
				String date = list.get(i);
				String num = (String)map.get(date.toString());
				JSONObject json = JSONUtil.createObj();
				json.set("time", date.toString());
				json.set("value", num==null? 0: Integer.valueOf(num));
				jsonArray.add(json);
			}
			return new CommonResult<JSONArray>(true,"查询成功", jsonArray);
		} else {
			return new CommonResult<JSONArray>(false,"类型错误");
		}
	}

}
