package com.xxfc.platform.im.biz;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.github.pagehelper.PageInfo;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.admin.vo.ImiVo;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.xxfc.platform.im.dto.CommentVo;
import com.xxfc.platform.im.dto.PraiseVo;
import com.xxfc.platform.im.model.Comment;
import com.xxfc.platform.im.model.Msg;
import com.xxfc.platform.im.model.Praise;
import com.xxfc.platform.im.utils.AddressUtils;
import com.xxfc.platform.im.vo.MsgVo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class MsgBiz {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    UserBiz userBiz;

    /**
     * 获取消息列表
     *
     * @return
     * @throws Exception
     */
    public ObjectRestResponse getMsgList(Integer page, Integer limit, Integer type) throws Exception {
        //获取所有朋友圈
        AppUserDTO appUserDTO = userBiz.getUserInfo();
        Integer userId = null;
        if(appUserDTO != null) {
            userId = appUserDTO.getImUserid();
        }
        log.info("获取消息列表： page = {}, limit = {}, type = {}", page, limit, type);
         page = page == null ? 1 : page;
         limit = limit == null ? 10 : limit;
        Pageable pageable = PageRequest.of(--page, limit);
        Query query = null;
        List<Msg> msgList = null;
        if (type != null) {
            query = new Query(Criteria.where("body.type").is(type));
            int totalSize = mongoTemplate.find(query, Msg.class, "s_msg").size();
            query.with(pageable);
            query.with(new Sort(Sort.Direction.DESC, "time"));
            msgList = fetchAndAttach(mongoTemplate.find(query, Msg.class, "s_msg"), userId);
            PageInfo<MsgVo> goodPageInfo = new PageInfo<>(replaceMsgResult(msgList));
            goodPageInfo.setPageSize(totalSize%limit == 0 ?totalSize/limit : totalSize/limit + 1);
            return ObjectRestResponse.succ(goodPageInfo);
        } else {
            List<Integer> ids = new ArrayList<>();
            ids.add(2);
            ids.add(4);
            query = new Query(Criteria.where("body.type").in(ids));
            int totalSize = mongoTemplate.find(query, Msg.class, "s_msg").size();
            query.with(pageable);
            query.with(new Sort(Sort.Direction.DESC, "time"));
            msgList = fetchAndAttach(mongoTemplate.find(query, Msg.class, "s_msg"), userId);

            PageInfo<MsgVo> goodPageInfo = new PageInfo<>(replaceMsgResult(msgList));
            goodPageInfo.setPageSize(totalSize%limit == 0 ?totalSize/limit : totalSize/limit + 1);
            return ObjectRestResponse.succ(goodPageInfo);
        }

    }

    public ObjectRestResponse getHotMsgList(Integer page, Integer limit) {
        log.info("获取消息列表： page = {}, limit = {}, type = {}", page, limit);
        page = page == null ? 1 : page;
        limit = limit == null ? 10 : limit;
        Pageable pageable = PageRequest.of(--page, limit);
        List<Integer> ids = new ArrayList<>();
        ids.add(2);
        ids.add(4);
        Query query = new Query(Criteria.where("body.type").in(ids));
        int totalSize = mongoTemplate.find(query, Msg.class, "s_msg").size();
        query.with(pageable);
        query.with(new Sort(Sort.Direction.DESC, "count.praise"));
        List<Msg> msgList = mongoTemplate.find(query, Msg.class, "s_msg");
        PageInfo<MsgVo> goodPageInfo = new PageInfo<>(replaceMsgResult(msgList));
        goodPageInfo.setPageSize(totalSize%limit == 0 ?totalSize/limit : totalSize/limit + 1);
        return ObjectRestResponse.succ(goodPageInfo);
    }

    public ObjectRestResponse get(String id){
        //获取所有朋友圈
        AppUserDTO appUserDTO = userBiz.getUserInfo();
        Integer userId = null;
        if(appUserDTO != null) {
            userId = appUserDTO.getImUserid();
        }
        if(id == null) {
            return ObjectRestResponse.paramIsEmpty();
        }
        Query query = new Query(Criteria.where("id").is(new ObjectId(id)));
        List<Msg> msgList = fetchAndAttach(mongoTemplate.find(query, Msg.class, "s_msg"), userId);
        List<MsgVo> msgVoList = replaceMsgResult(msgList);
        if(msgVoList.size() > 0) {
            return ObjectRestResponse.succ(msgVoList.get(0));
        }
        return ObjectRestResponse.succ();
}

    /**
     * 添加评论和点赞
     *
     * @param list
     * @param userId
     * @return
     */
    private List<Msg> fetchAndAttach(List<Msg> list, Integer userId) {
        for (Msg msg : list) {
            //添加评论
            Query query = new Query(Criteria.where("msgId").is(msg.getId()));
            query.with(new Sort(Sort.Direction.DESC, "time"));
            List<Comment> comments = mongoTemplate.find(query, Comment.class, "s_comment");
            msg.setComments(replaceCommentResult(comments));

            //添加点赞
            List<Praise> praise = mongoTemplate.find(query, Praise.class, "s_praise");
            msg.setPraises(replacePraiseResult(praise));
            if(userId != null) {
                msg.setIsPraise(this.exists(userId, msg.getId()) ? 1 : 0);
                msg.setIsCollect(this.existsCollect(userId, msg.getId()) ? 1 : 0);
            } else {
                msg.setIsPraise(0);
                msg.setIsCollect(0);
            }
        }
        return list;
    }

    /**
     * 判断是否点赞
     *
     * @param userId
     * @param msgId
     * @return
     */
    public boolean exists(int userId, ObjectId msgId) {
        Query query = new Query(Criteria.where("msgId").is(msgId).and("userId").is(userId));
        List<Praise> praise = mongoTemplate.find(query, Praise.class, "s_praise");
        return 0 != praise.size();
    }

    /**
     * 判断是否评论
     *
     * @param userId
     * @param msgId
     * @return
     */
    public boolean existsCollect(int userId, ObjectId msgId) {
        Query query = new Query(Criteria.where("msgId").is(msgId).and("userId").is(userId));
        List<Comment> comments = mongoTemplate.find(query, Comment.class, "s_comment");
        return 0 != comments.size();
    }

    public List<MsgVo> replaceMsgResult(List<Msg> list) {
        List<MsgVo> msgVoList = new ArrayList<>();
        for(Msg msg : list) {
            MsgVo msgVo = new MsgVo();
            BeanUtil.copyProperties(msg, msgVo, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
            //添加用户昵称和头像
            ImiVo imiVo = userBiz.getUserInfo(msg.getUserId());
            if(imiVo != null) {
                msgVo.setNickname(imiVo.getNickname());
                msgVo.setPicUrl(imiVo.getHeadimgurl());
            }
             String address = AddressUtils.getMapaddress(msg.getLatitude().toString(), msg.getLongitude().toString());
            msgVo.setAddress(address);
            msgVo.setMsgId(msg.getId().toString());
            msgVoList.add(msgVo);
        }
        return msgVoList;
    }

    public List<PraiseVo> replacePraiseResult(List<Praise> list) {
        List<PraiseVo> praiseVoArrayList = new ArrayList<>();
        for(Praise praise : list) {
            PraiseVo praiseVo = new PraiseVo();
            BeanUtil.copyProperties(praise, praiseVo, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
            //添加用户昵称和头像
            ImiVo imiVo = userBiz.getUserInfo(praise.getUserId());
            if(imiVo != null) {
                praiseVo.setNickname(imiVo.getNickname());
                praiseVo.setPicUrl(imiVo.getHeadimgurl());
            }
            praiseVoArrayList.add(praiseVo);
        }
        return praiseVoArrayList;
    }

    public List<CommentVo> replaceCommentResult(List<Comment> list) {
        List<CommentVo> commentVoList = new ArrayList<>();
        for(Comment comment : list) {
            CommentVo commentVo = new CommentVo();
            BeanUtil.copyProperties(comment, commentVo, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
            //添加用户昵称和头像
            ImiVo imiVo = userBiz.getUserInfo(comment.getUserId());
            if(imiVo != null) {
                commentVo.setNickname(imiVo.getNickname());
                commentVo.setPicUrl(imiVo.getHeadimgurl());
            }
            commentVoList.add(commentVo);
        }
        return commentVoList;
    }

}
