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

import cn.hutool.core.util.EscapeUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RSet;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.http.common.HttpRequest;
import org.tio.http.server.annotation.RequestPath;
import org.tio.jfinal.kit.Kv;
import org.tio.jfinal.kit.Ret;
import org.tio.jfinal.plugin.activerecord.Db;
import org.tio.jfinal.plugin.activerecord.Page;
import org.tio.jfinal.plugin.activerecord.Record;
import org.tio.jfinal.plugin.activerecord.SqlPara;
import org.tio.sitexxx.im.server.handler.wx.WxChatApi;
import org.tio.sitexxx.im.server.handler.wx.WxSynApi;
import org.tio.sitexxx.service.ThreadUtil;
import org.tio.sitexxx.service.init.RedisInit;
import org.tio.sitexxx.service.model.main.*;
import org.tio.sitexxx.service.service.chat.ChatIndexService;
import org.tio.sitexxx.service.service.chat.ChatService;
import org.tio.sitexxx.service.service.chat.FriendApplyService;
import org.tio.sitexxx.service.service.chat.FriendService;
import org.tio.sitexxx.service.utils.RetUtils;
import org.tio.sitexxx.service.vo.Const;
import org.tio.sitexxx.service.vo.RetCode.CommonCode;
import org.tio.sitexxx.server.utils.WebUtils;
import org.tio.utils.json.Json;
import org.tio.utils.resp.Resp;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 好友相关接口
 * @author xufei
 * 2021年1月7日 下午6:26:37
 */
@RequestPath(value = "/friend")
public class FriendController {
	private static Logger log = LoggerFactory.getLogger(FriendController.class);

	/**
	 * 修改好友备注名-已调整
	 * @param request
	 * @param frienduid
	 * @param remarkname
	 * @return
	 */
	@RequestPath(value = "/modifyRemarkname")
	public Resp modifyRemarkname(HttpRequest request, Integer frienduid, String remarkname) {
		Integer userId = WebUtils.currUserId(request);
		if (StrUtil.isNotBlank(remarkname)) {
			remarkname = EscapeUtil.escapeHtml4(remarkname);
		} else {
			remarkname = "";
		}
		Ret ret = FriendService.me.updateRemarkName(userId, frienduid, remarkname);
		if (ret.isFail()) {
			return Resp.fail().msg(RetUtils.getRetMsg(ret));
		}
		String finalRemarkname = remarkname;
		ThreadUtil.getBsExecutor().execute(()-> {
			Long fid = RetUtils.getOkTData(ret);
			if (WxSynApi.isSynVersion()) {
				WxSynApi.synFdRemarkName(userId, fid, finalRemarkname, RetUtils.getOkTData(ret, "chatlinkid"));
			} else {
				WxFriend sendFreind = FriendService.me.getFriendInfo(fid);
				WxChatItems chatItems = ChatService.me.getAllChatItems(RetUtils.getOkTData(ret, "chatlinkid"));
				WxChatApi.autoUseSysChatNtf(userId, Const.WxSysCode.FRIEND_INFO_UPDATE, "好友信息发生变更", Json.toJson(sendFreind), chatItems);
			}
		});
		return Resp.ok(RetUtils.OPER_RIGHT);
	}

	/**
	 * 忽略申请
	 * @param request
	 * @param applyid
	 * @return
	 * @throws Exception
	 * @author xufei
	 * 2021年2月4日 下午3:11:47
	 */
	@RequestPath(value = "/ignoreApply")
	public Resp ignoreApply(HttpRequest request, Integer applyid) throws Exception {
		User curr = WebUtils.currUser(request);
		WxFriendApplyItems items = FriendApplyService.me.getById(applyid);
		if (items == null) {
			return RetUtils.getFailResp(CommonCode.BIZ_NOT_EXIST.value);
		}
		Ret ret = FriendService.me.ignoreApply(curr, items);
		if (ret.isFail()) {
			return Resp.fail().msg(RetUtils.getRetMsg(ret));
		}
		return Resp.ok(RetUtils.OPER_RIGHT);
	}
	
	/**
	 * 忽略申请
	 * @return
	 * @author xufei
	 * 2021年2月4日 下午3:11:47
	 */
	@RequestPath(value = "/isFriends")
	public Resp isFriends(Long chatlinkid) {
		WxChatUserItem userItem = ChatIndexService.chatUserIndex(chatlinkid);
		if (!ChatService.existTwoFriend(userItem)) {
			return Resp.fail("你们不是互相不是好友");
		}
		return Resp.ok();
	}
	
	/**
	 * 新增朋友圈
	 * @param request
	 * @return
	 * @author xufei
	 * 2021年2月4日 下午3:11:47
	 */
	@RequestPath(value = "/addCircle")
	public Resp addCircle(HttpRequest request,UserCircle userCircle) {
		Integer userId = WebUtils.currUserId(request);
		userCircle.setUid(userId);
		userCircle.setCreateTime(new Date());
		userCircle.save();
		return Resp.ok();
	}
	
	/**
	 * 删除朋友圈
	 * @return
	 * @author xufei
	 * 2021年2月4日 下午3:11:47
	 */
	@RequestPath(value = "/delCircle")
	public Resp delCircle(Long id) {
		UserCircle.dao.deleteById(id);
		return Resp.ok();
	}
	
	/**
	 * 朋友圈列表
	 * @param request
	 * @return
	 * @author xufei
	 * 2021年2月4日 下午3:11:47
	 */
	@RequestPath(value = "/circleList")
	public Resp circleList(HttpRequest request,Integer pageNumber,Integer pageSize,Long uid) {
		Integer userId = WebUtils.currUserId(request);
		Kv params = Kv.create();
		params.set("uid", userId);
		params.set("cuid", uid);
		SqlPara sqlPara = Db.use(Const.Db.TIO_SITE_MAIN).getSqlPara("tiocircle.list", params);
		if(pageNumber == null) {
			pageNumber=1;
		}
		if(pageSize == null) {
			pageSize=10;
		}
		Page<Record> records = Db.use(Const.Db.TIO_SITE_MAIN).paginate(pageNumber, pageSize, sqlPara);
		if(records == null) {
			return Resp.ok();
		}
		List<Record> list = records.getList();
		if(CollectionUtils.isEmpty(list)) {
			return Resp.ok();
		}
		
		List<Long> circle = list.stream().map(item ->item.getLong("id")).collect(Collectors.toList());
		String ids = StringUtils.join(circle,",");
		
		List<Record> commentList = Db.use(Const.Db.TIO_SITE_MAIN).find("select c.id,c.uid,c.content,c.parent_id parentId,c.circleid,u.nick,su.nick parentName  from comment c inner join user u on u.id = c.uid left join user su on su.id = c.parentuid where circleid in ("+ids+") and uid in (select  uid  from  wx_friend where frienduid ="+userId+") ");
		ArrayList<Record> list2 = new ArrayList<>();
		Map<Long, List<Record>> commentMap = null;
		if(commentList != null) {
			commentMap = commentList.stream().collect(Collectors.groupingBy(item ->item.getLong("circleid")));
		}
		
		for (Record entry : list) {
			Record record = entry;
			Long cid = record.getLong("id");
			RedissonClient redissonClient = RedisInit.get();
			RSet<Object> set = redissonClient.getSet("likes_"+cid);
			if(!CollectionUtils.isEmpty(set)) {
				String likeIds = StringUtils.join(set,",");
				if(likeIds.contains(userId+"")) {
					record.set("isThumb", true);
				}else {
					record.set("isThumb", false);
				}
				List<Record> likesList = Db.use(Const.Db.TIO_SITE_MAIN).find("select u.nick,f.remarkname,u.id from  wx_friend f left join user u on u.id = f.frienduid  where  f.uid = "+userId+" and f.frienduid in ("+likeIds+")");
				record.set("likes", likesList);
				record.set("likesNum", likesList.size());
			}else {
				record.set("likes", null);
				record.set("likesNum", 0);
			}
			if(commentMap != null &&commentMap.get(cid)!=null) {
				List<Record> list3 = commentMap.get(cid);
				record.set("comment", list3);
				record.set("commentNum", list3.size());
			} else {
				record.set("comment", null);
				record.set("commentNum", 0);
			}
			list2.add(record);
		}
		records.setList(list2);
		return Resp.ok(records);
	}

	@RequestPath(value = "/comment")
	public Resp comment(HttpRequest request,Integer circleid,Integer parentid,String content ) {
		User curr = WebUtils.currUser(request);
		if (curr == null) {
			return Resp.fail("未登录");
		}
		Comment comment = new Comment();
		comment.setCircleid(circleid);
		comment.setUid(curr.getId());
		if(parentid == null) {
		   parentid =0;
		}
		comment.setParentId(parentid);
		comment.setContent(content);
		comment.setCreateTime(new Date());
		if(parentid != 0) {
		   Comment findById = Comment.dao.findById(parentid);
		   comment.setParentuid(findById.getUid());
		}
		comment.save();
		Record record = Db.use(Const.Db.TIO_SITE_MAIN)
			 .findFirst("select c.id,u.avatar,c.uid,c.content,c.parent_id parentId,c.circleid,u.nick,su.nick parentName,su.avatar parentAvatar  from comment c inner join user u on u.id = c.uid left join user su on su.id = c.parentuid where  c.id = ? and c.uid = ? ",comment.getId(),curr.getId());

		UserCircle userCircle = UserCircle.dao.findById(circleid);
		if(!userCircle.getUid().equals(curr.getId())) {
			ThreadUtil.getBsExecutor().execute(()->{
				WxChatApi.sendCommentMsg(curr,comment.getCircleid(),0,record,userCircle);
			});
		}
		return Resp.ok(record);
	}
	 
	@RequestPath(value = "/delComment")
	public Resp delComment(Integer id,String content) {
		Comment.dao.deleteById(id);
		return Resp.ok();
	}

	@RequestPath(value = "/likes")
	public Resp likes(HttpRequest request,Integer id ) {
		User curr = WebUtils.currUser(request);
		if (curr == null) {
            return Resp.fail("未登录");
        }
		RedissonClient redissonClient = RedisInit.get();
		RSet<Object> set = redissonClient.getSet("likes_"+id);
		set.add(curr.getId());
		ThreadUtil.getBsExecutor().execute(() -> {
			try {
			   	Record record = new Record();
			   	record.set("createTime", new Date());
			   	record.set("circleid", id);
			   	record.set("avatar", curr.getAvatar());
			   	record.set("nick", curr.getNick());
				UserCircle userCircle = UserCircle.dao.findById(id);
				if(userCircle.getUid().equals(curr.getId())) {
					return;
				}
				record.set("circle", userCircle);
			   	WxChatApi.sendCommentMsg(curr,id,1,record,userCircle);
			} catch (Exception e) {
				log.error("", e);
			}
		});
	   	return Resp.ok();
	}

	 @RequestPath(value = "/delLikes")
	 public Resp delLikes(HttpRequest request,Integer id) {
		 Integer userId = WebUtils.currUserId(request);
		 RedissonClient redissonClient = RedisInit.get();
		 RSet<Object> set = redissonClient.getSet("likes_"+id);
		 set.remove(userId);
		 return Resp.ok();
	 }
	 
	 /**
	 * 朋友圈列表
	 * @param request
	 * @return
	 * @author xufei
	 * 2021年2月4日 下午3:11:47
	 */
	@RequestPath(value = "/circleById")
	public Resp circleById(HttpRequest request,Long circleid) {
		 User curr = WebUtils.currUser(request);
		 Record find = Db.use(Const.Db.TIO_SITE_MAIN).findFirst("select  u.avatar,u.nick,c.id,c.uid,c.type,c.content,c.url,c.create_time  createtime  from  user_circle c  inner join user\r\n"
				+ "	u ON u.id = c.uid  where c.id = ?",circleid);

		List<Record> commentList = Db.use(Const.Db.TIO_SITE_MAIN).find("select c.id,c.uid,c.content,c.parent_id parentId,c.circleid,u.nick,su.nick parentName  from comment c inner join user u on u.id = c.uid left join user su on su.id = c.parentuid where circleid = ?",circleid);

		Map<Long, List<Record>> commentMap = null;
		if(commentList != null) {
		   commentMap = commentList.stream().collect(Collectors.groupingBy(item ->item.getLong("circleid")));
		}
		 Record record = new Record();
		 record.set("userCircle", find);
		 RedissonClient redissonClient = RedisInit.get();
		 RSet<Object> set = redissonClient.getSet("likes_"+circleid);
		 if(!CollectionUtils.isEmpty(set)) {
			 String likeIds = StringUtils.join(set,",");
			 List<Record> likesList = Db.use(Const.Db.TIO_SITE_MAIN).find("select u.nick,f.remarkname,u.id from  wx_friend f left join user u on u.id = f.frienduid  where  f.uid = "+curr.getId()+" and f.frienduid in ("+likeIds+")");
			 record.set("likes", likesList);
			 record.set("likesNum", likesList.size());
		 }else {
			 record.set("likes", null);
			 record.set("likesNum", 0);
		 }
		 if(commentMap != null &&commentMap.get(circleid)!=null) {
			List<Record> list3 = commentMap.get(circleid);
			record.set("comment", list3);
			record.set("commentNum", list3.size());
		}
		else {
			record.set("comment", null);
			record.set("commentNum", 0);
		}
		return Resp.ok(record);
	}
}
