package org.tio.sitexxx.server.controller.wx;

import cn.hutool.core.util.EscapeUtil;
import cn.hutool.core.util.StrUtil;
import org.tio.sitexxx.server.utils.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.UploadFile;
import org.tio.http.server.annotation.RequestPath;
import org.tio.jfinal.kit.Ret;
import org.tio.sitexxx.im.server.handler.wx.WxChatApi;
import org.tio.sitexxx.service.model.main.User;
import org.tio.sitexxx.service.service.chat.ChatMsgService.MsgTemplate;
import org.tio.sitexxx.service.service.chat.GroupService;
import org.tio.sitexxx.service.service.ConfService;
import org.tio.sitexxx.service.utils.OssUtils;
import org.tio.sitexxx.service.utils.RetUtils;
import org.tio.sitexxx.service.vo.Const;
import org.tio.sitexxx.service.vo.OssConfig;
import org.tio.sitexxx.service.ThreadUtil;
import org.tio.sitexxx.service.vo.wx.SysMsgVo;
import org.tio.utils.resp.Resp;

import java.io.ByteArrayInputStream;

/**
 * 群信息接口
 * @author xufei
 * 2020年11月7日 下午6:26:46
 */
@RequestPath(value = "/group")
public class GroupController {
	private static Logger log = LoggerFactory.getLogger(GroupController.class);
	/**
	 * 修改群简介
	 * @param request
	 * @param groupid
	 * @param intro
	 * @return
	 */
	@RequestPath(value = "/modifyIntro")
	public Resp modifyIntro(HttpRequest request, Long groupid, String intro) {
		User curr = WebUtils.currUser(request);
		return GroupService.me.modifyIntro(curr, groupid, intro);
	}

	/**
	 * 修改群名字
	 * @param request
	 * @param groupid
	 * @param name
	 * @return
	 * @author xufei
	 * 2020年11月13日 下午2:23:29
	 */
	@RequestPath(value = "/modifyName")
	public Resp modifyName(HttpRequest request, Long groupid, String name) {
		User curr = WebUtils.currUser(request);
		if (curr == null){
			return Resp.fail("未登录");
		}
		if (StrUtil.isEmpty(name)) {
			return Resp.fail("参数为空");
		}
		name = EscapeUtil.escapeHtml4(name);
		Ret ret = GroupService.me.modifyName(curr.getId(), groupid, name);
		if (ret.isFail()) {
			return Resp.fail().msg(RetUtils.getRetMsg(ret));
		}
		String sendName = name;
		//消息触发
		ThreadUtil.getBsExecutor().execute(() -> {
			try {
				Ret ret1 = WxChatApi.updateGroupInfo(curr, groupid, sendName);
				if (ret1.isFail()) {
					log.error(RetUtils.getRetMsg(ret1));
				}
			} catch (Exception e) {
				log.error("", e);
			}
		});
		return Resp.ok(RetUtils.OPER_RIGHT);
	}

	/**
	 * 修改群头像
	 * @param request
	 * @param groupid
	 * @return
	 * @author xufei
	 * 2021年1月13日 下午7:08:07
	 */
	@RequestPath(value = "/modifyAvatar")
	public Resp modifyAvatar(HttpRequest request, Long groupid, UploadFile uploadFile) {
		if (uploadFile == null) {
			return Resp.fail("上传信息为空");
		}
		User curr = WebUtils.currUser(request);
		if (curr == null) {
            return Resp.fail("未登录");
        }
		Resp imgret;
		byte[] imageBytes = uploadFile.getData();
		int maxsize = ConfService.getInt("user.upload.avatar.maxsize", 512);
		if (imageBytes.length > 1024 * maxsize) {
			imgret = Resp.fail("文件尺寸不能大于" + maxsize + "KB");
			return imgret;
		}
		String filename = uploadFile.getName();
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(imageBytes);
		OssConfig ossConfig = ConfService.getOssConfig();
		String uploadPath = OssUtils.upload(ossConfig, filename, byteArrayInputStream, "ltimg/", "");

		Ret ret = GroupService.me.modifyUploadAvatar(curr.getId(), groupid, uploadPath);
		if (ret.isFail()) {
			return Resp.fail().msg(RetUtils.getRetMsg(ret));
		}
		//消息触发
		ThreadUtil.getBsExecutor().execute(() -> {
			try {
				Ret ret1 = WxChatApi.updateGroupAvatar(curr, groupid, uploadPath);
				if (ret1.isFail()) {
					log.error(RetUtils.getRetMsg(ret1));
				}
			} catch (Exception e) {
				log.error("", e);
			}
		});
		return Resp.ok(RetUtils.OPER_RIGHT);
	}

	/**
	 * 修改群公告
	 * @param request
	 * @param groupid
	 * @param notice
	 * @return
	 */
	@RequestPath(value = "/modifyNotice")
	public Resp modifyNotice(HttpRequest request, Long groupid, String notice) {
		User curr = WebUtils.currUser(request);
		if (curr == null) {
            return Resp.fail("未登录");
        }
		Resp resp = GroupService.me.modifyNotice(curr, groupid, notice);
		if(!resp.isOk()) {
			return resp;
		}
		if (StrUtil.isNotBlank(notice)) {
			SysMsgVo sysMsgVo = new SysMsgVo(curr.getNick(), MsgTemplate.updatenotice, notice, "updatenotice");
			//消息触发
			ThreadUtil.getBsExecutor().execute(() -> {
				try {
					Ret ret = WxChatApi.sendGroupMsgEach(sysMsgVo.toText(), Const.ContentType.TEXT, curr.getId(), groupid, Const.YesOrNo.YES, sysMsgVo);
					if (ret.isFail()) {
						log.error(RetUtils.getRetMsg(ret));
					}
				} catch (Exception e) {
					log.error("", e);
				}
			});
		}
		return resp;
	}

	/**
	 * 管理员操作
	 * @param request
	 * @param groupid
	 * @param uid
	 * @param grouprole
	 * @return
	 * @author xufei
	 * 2021年1月13日 下午3:17:35
	 */
	@RequestPath(value = "/manager")
	public Resp manager(HttpRequest request, Long groupid, Integer uid, Short grouprole) {
		User curr = WebUtils.currUser(request);
		if (curr == null) {
            return Resp.fail("未登录");
        }
		Ret ret = GroupService.me.manager(curr.getId(), uid, groupid, grouprole);
		if (ret.isFail()) {
			return Resp.fail().msg(RetUtils.getRetMsg(ret));
		}
		ThreadUtil.getBsExecutor().execute(() -> {
			try {
				Ret ret1 = WxChatApi.manager(curr, groupid, uid, grouprole);
				if (ret1.isFail()) {
					log.error(RetUtils.getRetMsg(ret1));
				}
			} catch (Exception e) {
				log.error("", e);
			}
		});
		return Resp.ok(RetUtils.OPER_RIGHT);
	}

	/**
	 * 好友显示操作
	 * @param request
	 * @param groupid
	 * @param friendflag
	 * @return
	 * @author xufei
	 * 2021年1月13日 下午3:52:10
	 */
	@RequestPath(value = "/modifyFriendFlag")
	public Resp modifyFriendFlag(HttpRequest request, Long groupid, Short friendflag) {
		Integer userId = WebUtils.currUserId(request);
		Ret ret = GroupService.me.friendFlag(userId, groupid, friendflag);
		if (ret.isFail()) {
			return Resp.fail().msg(RetUtils.getRetMsg(ret));
		}
		return Resp.ok(RetUtils.OPER_RIGHT);
	}

	/**
	 * 群审核开关修改-已调整
	 * @param request
	 * @param groupid
	 * @param mode
	 * @return
	 * @author xufei
	 * 2020年3月9日 下午4:37:18
	 */
	@RequestPath(value = "/modifyReview")
	public Resp modifyReview(HttpRequest request, Long groupid, Short mode) {
		String text;
		User curr = WebUtils.currUser(request);
		if (curr == null) {
            return Resp.fail("未登录");
        }
		SysMsgVo sysMsgVo = new SysMsgVo(curr.getNick(), "", "", "");
		switch (mode) {
		case Const.GroupJoinMode.REVIEW:
			text = MsgTemplate.reviewopen;
			sysMsgVo.setMsgbody(text);
			sysMsgVo.setMsgkey("reviewopen");
			break;
		case Const.GroupJoinMode.NO_REVIEW:
			text = MsgTemplate.reviewclose;
			sysMsgVo.setMsgbody(text);
			sysMsgVo.setMsgkey("reviewclose");
			break;
		default:
			return Resp.fail().msg("无效入群方式");
		}

		Ret ret = GroupService.me.modifyReview(curr, groupid, mode);
		if (ret.isFail()) {
			return Resp.fail().msg(RetUtils.getRetMsg(ret));
		}
		//消息触发
		ThreadUtil.getBsExecutor().execute(() -> {
			try {
				Ret ret1 = WxChatApi.sendGroupMsgEach(sysMsgVo.toText(), Const.ContentType.TEXT, curr.getId(), groupid, Const.YesOrNo.YES, sysMsgVo);
				if (ret1.isFail()) {
					log.error(RetUtils.getRetMsg(ret1));
				}
			} catch (Exception e) {
				log.error("", e);
			}
		});
		return Resp.ok(RetUtils.OPER_RIGHT);
	}
}
