package com.slodon.b2b2c.controller.video.front;

import com.slodon.b2b2c.core.controller.BaseController;
import com.slodon.b2b2c.core.response.JsonResult;
import com.slodon.b2b2c.core.response.PageVO;
import com.slodon.b2b2c.core.response.PagerInfo;
import com.slodon.b2b2c.core.response.SldResponse;
import com.slodon.b2b2c.core.util.FileUrlUtil;
import com.slodon.b2b2c.core.util.StringUtil;
import com.slodon.b2b2c.core.util.UserUtil;
import com.slodon.b2b2c.core.util.WebUtil;
import com.slodon.b2b2c.member.pojo.Member;
import com.slodon.b2b2c.video.example.SvideoCommentExample;
import com.slodon.b2b2c.video.example.SvideoCommentLikeExample;
import com.slodon.b2b2c.video.example.SvideoReplyExample;
import com.slodon.b2b2c.video.example.SvideoReplyLikeExample;
import com.slodon.b2b2c.model.video.*;
import com.slodon.b2b2c.video.pojo.*;
import com.slodon.b2b2c.vo.video.ReplyTreeVO;
import com.slodon.b2b2c.vo.video.VideoCommentVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(tags = "front-视频播放页评论管理")
@RestController
@RequestMapping("v3/video/front/video/comment")
public class FrontCommentController extends BaseController {

    @Resource
    private SvideoCommentModel svideoCommentModel;
    @Resource
    private SvideoReplyModel svideoReplyModel;
    @Resource
    private AuthorModel authorModel;
    @Resource
    private SvideoCommentLikeModel svideoCommentLikeModel;
    @Resource
    private SvideoReplyLikeModel svideoReplyLikeModel;
    @Resource
    private VideoSettingModel videoSettingModel;

    @ApiOperation("视频评论列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "videoId", value = "视频id", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", defaultValue = "20", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面位置", defaultValue = "1", paramType = "query")
    })
    @GetMapping("list")
    public JsonResult<PageVO<VideoCommentVO>> list(HttpServletRequest request, Integer videoId) {
        Member member = UserUtil.getUser(request, Member.class);
        Author author = authorModel.getAuthorByMemberId(member.getMemberId());

        PagerInfo pager = WebUtil.handlerPagerInfo(request);
        SvideoCommentExample example = new SvideoCommentExample();
        example.setVideoId(videoId);
        example.setOrderBy("create_time desc");
        List<SvideoComment> list = svideoCommentModel.getSvideoCommentList(example, pager);
        List<VideoCommentVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(comment -> {
                //设置默认头像
                if (StringUtil.isEmpty(comment.getMemberAvatar())) {
                    comment.setMemberAvatar(videoSettingModel.getVideoSettingBySettingName("author_default_profile").getValue());
                }
                VideoCommentVO vo = new VideoCommentVO(comment);
                //查询是否点赞
                SvideoCommentLikeExample commentLikeExample = new SvideoCommentLikeExample();
                commentLikeExample.setCommentId(comment.getCommentId());
                commentLikeExample.setAuthorId(author.getAuthorId());
                List<SvideoCommentLike> commentLikeList = svideoCommentLikeModel.getSvideoCommentLikeList(commentLikeExample, null);
                if (!CollectionUtils.isEmpty(commentLikeList)) {
                    vo.setIsLike(true);
                }
                //是否自己的评论
                if (author.getAuthorId().equals(comment.getFromAuthorId())) {
                    vo.setIsSelf(true);
                }
                //查询回复列表
                SvideoReplyExample replyExample = new SvideoReplyExample();
                replyExample.setCommentId(comment.getCommentId());
                replyExample.setParentReplyId(0);
                replyExample.setOrderBy("create_time");
                List<SvideoReply> replyList = svideoReplyModel.getSvideoReplyList(replyExample, null);
                List<ReplyTreeVO> replyVOList = new ArrayList<>();
                if (!CollectionUtils.isEmpty(replyList)) {
                    List<ReplyTreeVO> replyTreeList = getReplyTreeList(replyList, author.getAuthorId());
                    replyVOList.addAll(treeToList(replyTreeList));
                }
                vo.setReplyList(replyVOList);
                vos.add(vo);
            });
        }
        return SldResponse.success(new PageVO<>(vos, pager));
    }

    @ApiOperation("发表评论")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "videoId", value = "视频id", required = true),
            @ApiImplicitParam(name = "content", value = "评论内容", required = true)
    })
    @PostMapping("publish")
    public JsonResult publishComment(HttpServletRequest request, Integer videoId, String content) {
        Member member = UserUtil.getUser(request, Member.class);
        //查询作者信息
        Author author = authorModel.getAuthorByMemberId(member.getMemberId());

        SvideoComment comment = new SvideoComment();
        comment.setVideoId(videoId);
        comment.setFromAuthorId(author.getAuthorId());
        comment.setFromAuthorName(StringUtil.isEmpty(author.getMemberNickname()) ? author.getMemberName() : author.getMemberNickname());
        comment.setMemberAvatar(author.getMemberAvatar());
        comment.setContent(content);
        comment.setCreateTime(new Date());
        SvideoComment svideoComment = svideoCommentModel.saveSvideoComment(comment);
        //设置默认头像
        if (StringUtil.isEmpty(svideoComment.getMemberAvatar())) {
            svideoComment.setMemberAvatar(FileUrlUtil.getFileUrl(videoSettingModel.getVideoSettingBySettingName("author_default_profile").getValue(), null));
        } else {
            svideoComment.setMemberAvatar(svideoComment.getMemberAvatar().startsWith("http") ? svideoComment.getMemberAvatar() : FileUrlUtil.getFileUrl(svideoComment.getMemberAvatar(), null));
        }
        return SldResponse.success(svideoComment);
    }

    @ApiOperation("评论点赞")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "commentId", value = "评论id", required = true)
    })
    @PostMapping("clickPraise")
    public JsonResult clickPraise(HttpServletRequest request, Integer commentId) {
        Member member = UserUtil.getUser(request, Member.class);
        //查询作者信息
        Author author = authorModel.getAuthorByMemberId(member.getMemberId());

        Integer praiseNum = svideoCommentModel.clickPraise(commentId, author);
        return SldResponse.success(praiseNum);
    }

    @ApiOperation("删除评论")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "commentId", value = "评论id", required = true)
    })
    @PostMapping("del")
    public JsonResult delComment(HttpServletRequest request, Integer commentId) {
        svideoCommentModel.deleteSvideoComment(commentId);
        return SldResponse.success("删除成功");
    }

    @ApiOperation("评论回复")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "commentId", value = "评论id", required = true),
            @ApiImplicitParam(name = "parentReplyId", value = "父级回复id", defaultValue = "0", required = true),
            @ApiImplicitParam(name = "content", value = "评论内容", required = true)
    })
    @PostMapping("reply")
    public JsonResult reply(HttpServletRequest request, Integer commentId, String content,
                            @RequestParam(value = "parentReplyId", required = false, defaultValue = "0") Integer parentReplyId) {
        Member member = UserUtil.getUser(request, Member.class);
        //查询作者信息
        Author author = authorModel.getAuthorByMemberId(member.getMemberId());

        SvideoReply reply = new SvideoReply();
        reply.setCommentId(commentId);
        reply.setParentReplyId(parentReplyId);
        reply.setFromAuthorId(author.getAuthorId());
        reply.setFromAuthorName(StringUtil.isEmpty(author.getMemberNickname()) ? author.getMemberName() : author.getMemberNickname());
        reply.setMemberAvatar(author.getMemberAvatar());
        reply.setContent(content);
        reply.setCreateTime(new Date());
        SvideoReply svideoReply = svideoReplyModel.saveSvideoReply(reply);
        //设置默认头像
        if (StringUtil.isEmpty(svideoReply.getMemberAvatar())) {
            svideoReply.setMemberAvatar(FileUrlUtil.getFileUrl(videoSettingModel.getVideoSettingBySettingName("author_default_profile").getValue(), null));
        } else {
            svideoReply.setMemberAvatar(svideoReply.getMemberAvatar().startsWith("http") ? svideoReply.getMemberAvatar() : FileUrlUtil.getFileUrl(svideoReply.getMemberAvatar(), null));
        }
        return SldResponse.success(svideoReply);
    }

    @ApiOperation("回复点赞")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "replyId", value = "回复id", required = true)
    })
    @PostMapping("replyClickPraise")
    public JsonResult replyClickPraise(HttpServletRequest request, Integer replyId) {
        Member member = UserUtil.getUser(request, Member.class);
        //查询作者信息
        Author author = authorModel.getAuthorByMemberId(member.getMemberId());

        Integer praiseNum = svideoReplyModel.clickPraise(replyId, author);
        return SldResponse.success(praiseNum);
    }

    @ApiOperation("删除回复")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "replyId", value = "回复id", required = true)
    })
    @PostMapping("delReply")
    public JsonResult delReply(HttpServletRequest request, Integer replyId) {
        svideoReplyModel.deleteSvideoReply(replyId);
        return SldResponse.success("删除成功");
    }

    /**
     * 把集合转换成树结构
     *
     * @param list
     * @param authorId
     * @return
     */
    public List<ReplyTreeVO> getReplyTreeList(List<SvideoReply> list, Integer authorId) {
        List<ReplyTreeVO> voList = new ArrayList<>();
        if (CollectionUtils.isEmpty(list)) {
            return voList;
        }
        for (SvideoReply reply : list) {
            //设置默认头像
            if (StringUtil.isEmpty(reply.getMemberAvatar())) {
                reply.setMemberAvatar(videoSettingModel.getVideoSettingBySettingName("author_default_profile").getValue());
            }
            ReplyTreeVO vo = new ReplyTreeVO(reply);
            //查询是否点赞
            SvideoReplyLikeExample replyLikeExample = new SvideoReplyLikeExample();
            replyLikeExample.setReplyId(reply.getReplyId());
            replyLikeExample.setAuthorId(authorId);
            List<SvideoReplyLike> replyLikeList = svideoReplyLikeModel.getSvideoReplyLikeList(replyLikeExample, null);
            if (!CollectionUtils.isEmpty(replyLikeList)) {
                vo.setIsLike(true);
            }
            //是否自己的评论
            if (authorId.equals(reply.getFromAuthorId())) {
                vo.setIsSelf(true);
            }
            //查询子回复列表
            SvideoReplyExample replyExample = new SvideoReplyExample();
            replyExample.setParentReplyId(reply.getReplyId());
            replyExample.setCommentId(reply.getCommentId());
            replyExample.setOrderBy("create_time");
            List<SvideoReply> replyList = svideoReplyModel.getSvideoReplyList(replyExample, null);
            if (!CollectionUtils.isEmpty(replyList)) {
                vo.setChildren(getReplyTreeList(replyList, authorId));
            } else {
                vo.setChildren(new ArrayList<>());
            }
            voList.add(vo);
        }
        return voList;
    }

    /**
     * 用于将树形结构的list转为线性
     *
     * @param treeList
     * @return
     */
    private List<ReplyTreeVO> treeToList(List<ReplyTreeVO> treeList) {
        List<ReplyTreeVO> list = new ArrayList<>();
        for (ReplyTreeVO tree : treeList) {
            list.add(tree);
            List<ReplyTreeVO> children = tree.getChildren();
            if (!CollectionUtils.isEmpty(children)) {
                List<ReplyTreeVO> entityList = this.treeToList(children);
                list.addAll(entityList);
            }
        }
        if (!CollectionUtils.isEmpty(list)) {
            for (ReplyTreeVO tree : list) {
                tree.setChildren(null);
            }
        }
        return list;
    }

}
