
package org.tio.sitexxx.im.server.handler.wx.group;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;
import org.tio.jfinal.kit.Ret;
import org.tio.sitexxx.im.common.CommandHandler;
import org.tio.sitexxx.im.common.ImPacket;
import org.tio.sitexxx.im.common.ImSessionContext;
import org.tio.sitexxx.im.common.bs.wx.group.WxGroupChatReq;
import org.tio.sitexxx.im.server.handler.AbsImServerHandler;
import org.tio.sitexxx.im.server.handler.wx.WxChatApi;
import org.tio.sitexxx.im.server.handler.wx.WxChatQueueApi;
import org.tio.sitexxx.im.server.utils.ImUtils;
import org.tio.sitexxx.service.Command;
import org.tio.sitexxx.service.ThreadUtil;
import org.tio.sitexxx.service.model.main.*;
import org.tio.sitexxx.service.service.base.IpInfoService;
import org.tio.sitexxx.service.service.base.SensitiveWordsService;
import org.tio.sitexxx.service.service.base.UserService;
import org.tio.sitexxx.service.service.chat.ChatIndexService;
import org.tio.sitexxx.service.service.chat.FriendService;
import org.tio.sitexxx.service.service.chat.GroupService;
import org.tio.sitexxx.service.service.chat.SynService;
import org.tio.sitexxx.service.service.ConfService;
import org.tio.sitexxx.service.utils.RetUtils;
import org.tio.sitexxx.service.vo.AppCode;
import org.tio.sitexxx.service.vo.Const;
import org.tio.sitexxx.service.vo.Devicetype;
import org.tio.sitexxx.service.vo.SimpleUser;
import org.tio.sitexxx.service.vo.wx.WxMsgCardVo;
import org.tio.utils.SystemTimer;
import org.tio.utils.json.Json;

import java.util.Map;
import java.util.Objects;

/**
 * Wx群聊处理者
 * @author tanyaowu 

 */
@CommandHandler(Command.WxGroupChatReq)
public class WxGroupChatReqHandler extends AbsImServerHandler {

	private static Logger log = LoggerFactory.getLogger(WxGroupChatReqHandler.class);

	@Override
	public void handler(ImPacket packet, ChannelContext channelContext, boolean isWebsocket, User curr, SimpleUser currSimpleUser) throws Exception {
		WxGroupChatReq wxGroupChatReq = Json.toBean(packet.getBodyStr(), WxGroupChatReq.class);
		Long chatlinkid = wxGroupChatReq.getChatlinkid();
		String c = StrUtil.trim(wxGroupChatReq.getC()); //聊天内容
		if (wxGroupChatReq.getCardid() == null && StrUtil.isBlank(c) && StrUtil.isBlank(wxGroupChatReq.getMapjson())) {
			// 聊天内容是空
			return;
		}
		Devicetype devicetype = ImUtils.getDevicetype(channelContext);
		if(Const.SENSITIVE_FLAG) {
			c = SensitiveWordsService.findAndReplace(c);
		}
		Long groupid = wxGroupChatReq.getG(); //
		if (StrUtil.isNotBlank(c) && c.length() > 2048) {
			// 聊天内容太长
			ImUtils.info(channelContext, "你发的内容有点长^_^", null);
			return;
		}
		if (chatlinkid == null) {
			log.error("会话id为空");
		} else {
			groupid = Math.abs(chatlinkid);
			Ret check = GroupService.checkGroupMsg(groupid, curr.getId());
			if (check.isFail()) {
				Integer send = check.getInt("send");
				if (send != null && send == 1) {
					return;
				}
				WxChatApi.sendFriendErrorMsg(channelContext, curr.getId(), curr.getId(), chatlinkid, AppCode.FriendErrorCode.SYS_ERROR, RetUtils.getRetMsg(check));
				return;
			}
			Short limitopen = ConfService.getShort(Const.ConfMapping.WX_GROUP_MSG_SEND_LIMIT_OPEN, Const.YesOrNo.YES);
			if (Objects.equals(limitopen, Const.YesOrNo.YES)) {
				WxChatGroupItem groupItem = ChatIndexService.chatGroupIndex(curr.getId(), groupid);
				if (Objects.equals(groupItem.getGrouprole(), Const.GroupRole.MEMBER)) {
					ImSessionContext imSessionContext = ImUtils.getImSessionContext(channelContext);
					long lastGroupChatTime = imSessionContext.getLastGroupChatTime();
					int interval = ConfService.getInt("im.group.chat.time.interval", 2000);
					long currtime = SystemTimer.currTime;
					if ((currtime - lastGroupChatTime) <= interval) {
						//发言过快
						ImUtils.info(channelContext, "发言过快", null);
						return;
					}
					imSessionContext.setLastGroupChatTime(currtime);
				}
			}
			chatlinkid = RetUtils.getOkTData(check);
			short contenttype = Const.ContentType.TEXT;
			//发送名片
			if (wxGroupChatReq.getCardid() != null) {
				Ret ret;
				//判断权限
				WxChatGroupItem groupItem = ChatIndexService.chatGroupIndex(curr.getId(), groupid);
				if (groupItem != null) {
					if (groupItem.getGrouprole() == Const.GroupRole.MEMBER) {
						WxChatApi.sendFriendErrorMsg(channelContext, curr.getId(), curr.getId(), -groupid, AppCode.GroupErrorCode.SYS_ERROR, "暂无权限发送名片");
						return;
					}
				}
				if (Objects.equals(wxGroupChatReq.getCardtype(), Const.MsgCardType.FRIEND)) {
					ret = FriendService.me.getFdCard(curr.getId(), wxGroupChatReq.getCardid().intValue());
				} else if (Objects.equals(wxGroupChatReq.getCardtype(), Const.MsgCardType.GROUP)) {
					ret = GroupService.me.getGroupCard(curr.getId(), wxGroupChatReq.getCardid());
				} else {
					WxChatApi.sendFriendErrorMsg(channelContext, curr.getId(), curr.getId(), -groupid, AppCode.GroupErrorCode.SYS_ERROR, "无效名片类型");
					return;
				}
				if (ret.isFail()) {
					WxChatApi.sendFriendErrorMsg(channelContext, curr.getId(), curr.getId(), -groupid, AppCode.GroupErrorCode.SYS_ERROR, RetUtils.getRetMsg(ret));
					return;
				}
				WxMsgCardVo cardVo = RetUtils.getOkTData(ret);
				cardVo.setShareToBizid(groupid);
				c = Json.toJson(cardVo);
				contenttype = Const.ContentType.MSG_CARD;
			}
			//发送图片
			if (StrUtil.isNotBlank(wxGroupChatReq.getMapjson())) {
				contenttype = Const.ContentType.POSITION;
				c = wxGroupChatReq.getMapjson();
			}
			//发送引用
			if (StrUtil.isNotBlank(wxGroupChatReq.getReferenceId())) {
				contenttype = Const.ContentType.REFERENCE;
				WxGroupMsg msg = GroupService.me.getGroupMsg(Long.parseLong(wxGroupChatReq.getReferenceId()));
				Reference reference = new Reference();
				if (msg.getContenttype() == Const.ContentType.REFERENCE) {
					reference.setType((int) Const.ContentType.TEXT);
					Reference reference1 = JSON.parseObject(msg.getC(), Reference.class);
					reference.setReferenceContent(reference1.getContent());
				} else {
					reference.setType(Integer.valueOf(msg.getContenttype()));
					reference.setReferenceContent(msg.getC());
				}
				User user = UserService.ME.getById(msg.getUid());
				if (user != null) {
					reference.setReferenceName(user.getNick());
				}
				reference.setReferenceId(String.valueOf(msg.getMid()));
				reference.setContent(wxGroupChatReq.getC());
				reference.setReferenceUserId(String.valueOf(msg.getUid()));
				c = Json.toJson(reference);
			}
			Short finalContentType = contenttype;
			String finalC = c;
			Long finalGroupId = groupid;
			ThreadUtil.getBsExecutor().execute(() -> {
				try {
					Ret ret = WxChatApi.sendGroupMsgEach(finalC, finalContentType, curr.getId(), finalGroupId, null,
							null, wxGroupChatReq.getAt());
					if (ret.isFail()) {
						WxChatApi.sendFriendErrorMsg(channelContext, curr.getId(), curr.getId(), -finalGroupId, AppCode.GroupErrorCode.SYS_ERROR,
								RetUtils.getRetMsg(ret));
					}
				} catch (Exception e) {
					log.error(e.getMessage());
				}
			});
			//新增焦点补偿逻辑
			Map<String, Short> focusMap = SynService.me.focusDevice(curr.getId(), devicetype.getValue());
			if (focusMap == null || focusMap.get(-groupid + "") == null) {
				log.error("补偿焦点会话:chatlinkid:{},focusMap:{}", -groupid, Json.toJson(focusMap));
				IpInfo ipInfo = IpInfoService.ME.save(channelContext.getClientNode().getIp());
				WxChatQueueApi.joinFocusQueue(channelContext, curr, chatlinkid, groupid, Const.ChatMode.GROUP, devicetype.getValue(), ipInfo.getId());
			}
		}
	}
}
