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

import com.slodon.b2b2c.core.constant.VideoConst;
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.*;
import com.slodon.b2b2c.member.pojo.Member;
import com.slodon.b2b2c.model.member.MemberModel;
import com.slodon.b2b2c.model.video.*;
import com.slodon.b2b2c.video.example.*;
import com.slodon.b2b2c.video.pojo.*;
import com.slodon.b2b2c.vo.video.*;
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.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Api(tags = "front-作者个人页")
@RestController
@RequestMapping("v3/video/front/video/author")
public class FrontAuthorController extends BaseController {

    @Resource
    private AuthorModel authorModel;
    @Resource
    private SvideoCommentModel svideoCommentModel;
    @Resource
    private SvideoReplyModel svideoReplyModel;
    @Resource
    private SvideoVideoModel svideoVideoModel;
    @Resource
    private VideoGoodsModel videoGoodsModel;
    @Resource
    private SvideoVideoLikeModel svideoVideoLikeModel;
    @Resource
    private AuthorFollowModel authorFollowModel;
    @Resource
    private VideoSettingModel videoSettingModel;
    @Resource
    private MemberModel memberModel;

    @ApiOperation("个人主页信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorId", value = "作者id,作者个人页必传", paramType = "query"),
    })
    @GetMapping("personPage")
    public JsonResult<FrontAuthorVO> personPage(HttpServletRequest request, Integer authorId) {
        Member member = UserUtil.getUser(request, Member.class);
        Author author = null;
        if (member.getMemberId() != null) {
            author = synAuthorInfo(member);
        }
        FrontAuthorVO authorVO;
        //根据商品id分组查询商品量
        String fields = "goods_id";
        VideoGoodsExample videoGoodsExample = new VideoGoodsExample();
        if (StringUtil.isNullOrZero(authorId)) {
            //设置默认头像
            if (StringUtil.isEmpty(author.getMemberAvatar())) {
                author.setMemberAvatar(videoSettingModel.getVideoSettingBySettingName("author_default_profile").getValue());
            }
            authorVO = new FrontAuthorVO(author);

            //查询收到新的评论
            SvideoCommentExample example = new SvideoCommentExample();
            example.setToAuthorId(author.getAuthorId());
            example.setIsRead(VideoConst.IS_READ_0);
            int commentNum = svideoCommentModel.getSvideoCommentCount(example);
            //查询收到新的回复
            SvideoReplyExample replyExample = new SvideoReplyExample();
            replyExample.setIsRead(VideoConst.IS_READ_0);
            replyExample.setToAuthorId(author.getAuthorId());
            Integer replyNum = svideoReplyModel.getSvideoReplyCount(replyExample);
            authorVO.setMsgNum(commentNum + replyNum);
            authorVO.setIsSelf(true);
            //查询商品数
            videoGoodsExample.setAuthorId(author.getAuthorId());
            authorVO.setGoodsNum(videoGoodsModel.getVideoGoodsFieldCount(fields, videoGoodsExample));
            authorVO.setLiveNum(0);
        } else {
            Author authorDb = authorModel.getAuthorByAuthorId(authorId);
            //设置默认头像
            if (StringUtil.isEmpty(authorDb.getMemberAvatar())) {
                authorDb.setMemberAvatar(videoSettingModel.getVideoSettingBySettingName("author_default_profile").getValue());
            }
            //无昵称,用会员账号
            if (StringUtil.isEmpty(authorDb.getMemberNickname())) {
                authorDb.setMemberNickname(authorDb.getMemberName());
            }
            authorVO = new FrontAuthorVO(authorDb);

            //查询审核通过视频数
            SvideoVideoExample videoExample = new SvideoVideoExample();
            if (author != null) {
                //登录状态下判断是否自己
                if (author.getAuthorId().equals(authorId)) {
                    videoExample.setAuthorId(authorId);
                    videoExample.setState(VideoConst.STATE_2);

                    authorVO.setIsSelf(true);
                } else {
                    //查询是否关注
                    AuthorFollowExample example = new AuthorFollowExample();
                    example.setQueryAuthorId("notNull");
                    example.setFromAuthorId(author.getAuthorId());
                    example.setToAuthorId(authorId);
                    List<AuthorFollow> list = authorFollowModel.getAuthorFollowList(example, null);
                    if (!CollectionUtils.isEmpty(list)) {
                        authorVO.setIsFollow(true);
                    }

                    videoExample.setAuthorId(authorId);
                    videoExample.setState(VideoConst.STATE_2);
                }
            } else {
                videoExample.setAuthorId(authorId);
                videoExample.setState(VideoConst.STATE_2);
            }
            videoExample.setIsDelete(VideoConst.IS_DELETE_0);
            authorVO.setVideoNum(svideoVideoModel.getSvideoVideoCount(videoExample));
            authorVO.setLiveNum(0);
            //查询商品数
            videoGoodsExample.setAuthorId(authorDb.getAuthorId());
            authorVO.setGoodsNum(videoGoodsModel.getVideoGoodsFieldCount(fields, videoGoodsExample));
        }
        //设置默认背景
        if (StringUtil.isEmpty(authorVO.getBackgroundImage())) {
            authorVO.setBackgroundImage(FileUrlUtil.getFileUrl(videoSettingModel.getVideoSettingBySettingName("author_default_background").getValue(), null));
        }
        return SldResponse.success(authorVO);
    }

    /**
     * 同步作者信息
     *
     * @param member
     * @return
     */
    public Author synAuthorInfo(Member member) {
        //初始化作者信息
        Author author = new Author();
        //查询是否同步作者信息
        AuthorExample example = new AuthorExample();
        example.setMemberId(member.getMemberId());
        List<Author> list = authorModel.getAuthorList(example, null);
        if (!CollectionUtils.isEmpty(list)) {
            return list.get(0);
        }
        //查询数据库会员信息
        Member memberDb = memberModel.getMemberByMemberId(member.getMemberId());

        author.setMemberId(memberDb.getMemberId());
        author.setMemberName(memberDb.getMemberName());
        author.setMemberNickname(memberDb.getMemberName());
        author.setRoleType(VideoConst.ROLE_TYPE_1);
        author.setGrade(memberDb.getGender());
        author.setIntegral(memberDb.getMemberIntegral());
        //如果发布权限审核开关未开启，默认审核通过
        if ("0".equals(videoSettingModel.getVideoSettingBySettingName("member_review_switch").getValue())) {
            author.setPermissionState(VideoConst.PERMISSION_STATE_2);
        } else {
            author.setPermissionState(VideoConst.PERMISSION_STATE_0);
        }
        author.setCreateTime(new Date());
        return authorModel.saveAuthor(author);
    }

    @ApiOperation("申请发布权限")
    @PostMapping("apply")
    public JsonResult apply(HttpServletRequest request) {
        Member member = UserUtil.getUser(request, Member.class);
        Author authorDb = authorModel.getAuthorByMemberId(member.getMemberId());
        AssertUtil.isTrue(authorDb.getPermissionState() == VideoConst.PERMISSION_STATE_1, "审核中，请耐心等待");
        AssertUtil.isTrue(authorDb.getPermissionState() == VideoConst.PERMISSION_STATE_2, "您已审核通过，无需重复申请");

        Author author = new Author();
        author.setAuthorId(authorDb.getAuthorId());
        author.setPermissionState(VideoConst.PERMISSION_STATE_1);
        author.setUpdateTime(new Date());
        authorModel.updateAuthor(author);
        return SldResponse.success("申请成功");
    }

    @ApiOperation("个人主页动态列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorId", value = "作者id,作者个人页必传", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", defaultValue = "20", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面位置", defaultValue = "1", paramType = "query")
    })
    @GetMapping("videoList")
    public JsonResult<PageVO<VideoVO>> videoList(HttpServletRequest request, Integer authorId) {
        Member member = UserUtil.getUser(request, Member.class);
        Author author = null;
        if (member.getMemberId() != null) {
            author = authorModel.getAuthorByMemberId(member.getMemberId());
        }
        PagerInfo pager = WebUtil.handlerPagerInfo(request);
        SvideoVideoExample example = new SvideoVideoExample();
        if (author != null && StringUtil.isNullOrZero(authorId)) {
            example.setAuthorId(author.getAuthorId());
        } else {
            example.setAuthorId(authorId);
            //登录状态，并且不是自己的查审核通过的
            if (author != null && !authorId.equals(author.getAuthorId())) {
                example.setState(VideoConst.STATE_2);
            }
        }
        example.setIsDelete(VideoConst.IS_DELETE_0);
        List<SvideoVideo> list = svideoVideoModel.getSvideoVideoList(example, pager);
        List<VideoVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(video -> {
                //设置默认头像
                if (StringUtil.isEmpty(video.getMemberAvatar())) {
                    video.setMemberAvatar(videoSettingModel.getVideoSettingBySettingName("author_default_profile").getValue());
                }
                //无昵称,用会员账号
                if (StringUtil.isEmpty(video.getMemberNickname())) {
                    video.setMemberNickname(video.getMemberName());
                }
                vos.add(new VideoVO(video));
            });
        }
        return SldResponse.success(new PageVO<>(vos, pager));
    }

    @ApiOperation("个人主页商品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorId", value = "作者id,作者个人页必传", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", defaultValue = "20", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面位置", defaultValue = "1", paramType = "query")
    })
    @GetMapping("goodsList")
    public JsonResult<PageVO<VideoGoodsVO>> goodsList(HttpServletRequest request, Integer authorId) {
        Author svideoAuthor = null;
        if (StringUtil.isNullOrZero(authorId)) {
            Member member = UserUtil.getUser(request, Member.class);
            svideoAuthor = authorModel.getAuthorByMemberId(member.getMemberId());
            authorId = svideoAuthor.getAuthorId();
        }
        PagerInfo pager = WebUtil.handlerPagerInfo(request);
        String fields = "goods_id";
        VideoGoodsExample example = new VideoGoodsExample();
        example.setAuthorId(authorId);
        example.setGroupBy(fields);
        example.setOrderBy(fields);
        List<VideoGoods> list = videoGoodsModel.getVideoGoodsFieldList(fields, example, pager);
        List<VideoGoodsVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            Integer finalAuthorId = authorId;
            list.forEach(videoGoods -> {
                example.setAuthorId(finalAuthorId);
                example.setGoodsId(videoGoods.getGoodsId());
                example.setGroupBy(null);
                example.setOrderBy(null);
                List<VideoGoods> videoGoodsList = videoGoodsModel.getVideoGoodsList(example, null);
                //点击次数求和
                Integer clickNum = 0;
                for (VideoGoods goods : videoGoodsList) {
                    clickNum = clickNum + goods.getClickNum();
                }
                VideoGoodsVO vo = new VideoGoodsVO(videoGoodsList.get(0));
                vo.setClickNum(clickNum);
                vos.add(vo);
            });
        }
        return SldResponse.success(new PageVO<>(vos, pager));
    }

    @ApiOperation("我的视频-喜欢列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageSize", value = "分页大小", defaultValue = "20", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面位置", defaultValue = "1", paramType = "query")
    })
    @GetMapping("likeList")
    public JsonResult<PageVO<VideoLikeVO>> likeList(HttpServletRequest request) {
        Member member = UserUtil.getUser(request, Member.class);
        //查询作者信息
        Author author = authorModel.getAuthorByMemberId(member.getMemberId());

        PagerInfo pager = WebUtil.handlerPagerInfo(request);
        SvideoVideoLikeExample example = new SvideoVideoLikeExample();
        example.setAuthorId(author.getAuthorId());
        List<SvideoVideoLike> list = svideoVideoLikeModel.getSvideoVideoLikeList(example, pager);
        List<VideoLikeVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(videoLike -> {
                SvideoVideo svideoVideo = svideoVideoModel.getSvideoVideoByVideoId(videoLike.getVideoId());
                AssertUtil.notNull(svideoVideo, "视频不存在");
                vos.add(new VideoLikeVO(svideoVideo));
            });
        }
        return SldResponse.success(new PageVO<>(vos, pager));
    }

    @ApiOperation("编辑资料")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberAvatar", value = "会员头像"),
            @ApiImplicitParam(name = "memberNickname", value = "会员昵称"),
            @ApiImplicitParam(name = "backgroundImage", value = "背景图片"),
            @ApiImplicitParam(name = "introduction", value = "简介")
    })
    @PostMapping("updateInfo")
    public JsonResult updateInfo(HttpServletRequest request, String memberAvatar, String memberNickname,
                                 String backgroundImage, String introduction) {
        Member member = UserUtil.getUser(request, Member.class);
        //查询作者信息
        Author authorDb = authorModel.getAuthorByMemberId(member.getMemberId());

        Author author = new Author();
        author.setAuthorId(authorDb.getAuthorId());
        author.setMemberAvatar(memberAvatar);
        author.setMemberNickname(memberNickname);
        author.setBackgroundImage(backgroundImage);
        author.setIntroduction(introduction);
        author.setUpdateTime(new Date());
        authorModel.updateAuthor(author);
        return SldResponse.success("修改成功");
    }

    @ApiOperation("查看评论或回复")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageSize", value = "分页大小", defaultValue = "20", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面位置", defaultValue = "1", paramType = "query")
    })
    @GetMapping("lookMessage")
    public JsonResult<PageVO<VideoMessageVO>> lookMessage(HttpServletRequest request) {
        Member member = UserUtil.getUser(request, Member.class);
        //查询作者信息
        Author author = authorModel.getAuthorByMemberId(member.getMemberId());

        PagerInfo pager = WebUtil.handlerPagerInfo(request);
        SvideoCommentExample example = new SvideoCommentExample();
        example.setToAuthorId(author.getAuthorId());
        List<VideoMessageVO> list = svideoCommentModel.getMessageList(example, pager);
        if (!CollectionUtils.isEmpty(list)) {
            //key-视频id,value-视频类型
            Map<Integer, Integer> map = new HashMap<>();
            list.forEach(videoMessageVO -> {
                //设置默认头像
                if (StringUtil.isEmpty(videoMessageVO.getMemberAvatar())) {
                    videoMessageVO.setMemberAvatar(FileUrlUtil.getFileUrl(videoSettingModel.getVideoSettingBySettingName("author_default_profile").getValue(), null));
                } else {
                    videoMessageVO.setMemberAvatar(FileUrlUtil.getFileUrl(videoMessageVO.getMemberAvatar(), null));
                }
                videoMessageVO.setVideoImage(FileUrlUtil.getFileUrl(videoMessageVO.getVideoImage(), null));
                if (map.containsKey(videoMessageVO.getVideoId())) {
                    videoMessageVO.setVideoType(map.get(videoMessageVO.getVideoId()));
                } else {
                    SvideoVideo svideoVideo = svideoVideoModel.getSvideoVideoByVideoId(videoMessageVO.getVideoId());
                    AssertUtil.notNull(svideoVideo, "视频不存在");
                    videoMessageVO.setVideoType(svideoVideo.getVideoType());

                    map.put(videoMessageVO.getVideoId(), svideoVideo.getVideoType());
                }
            });
        }
        //更新评论消息已读
        SvideoComment svideoComment = new SvideoComment();
        svideoComment.setIsRead(VideoConst.IS_READ_1);
        svideoCommentModel.updateComment(svideoComment, example);
        //更新评论回复已读
        SvideoReplyExample replyExample = new SvideoReplyExample();
        replyExample.setToAuthorId(author.getAuthorId());
        SvideoReply svideoReply = new SvideoReply();
        svideoReply.setIsRead(VideoConst.IS_READ_1);
        svideoReplyModel.updateReply(svideoReply, replyExample);
        return SldResponse.success(new PageVO<>(list, pager));
    }

    @ApiOperation("粉丝关注列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "followType", value = "关注类型：1关注，2粉丝", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", defaultValue = "20", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面位置", defaultValue = "1", paramType = "query")
    })
    @GetMapping("followList")
    public JsonResult<PageVO<FollowVO>> followList(HttpServletRequest request, Integer followType) {
        Member member = UserUtil.getUser(request, Member.class);
        //查询作者信息
        Author author = authorModel.getAuthorByMemberId(member.getMemberId());

        PagerInfo pager = WebUtil.handlerPagerInfo(request);
        AuthorFollowExample example = new AuthorFollowExample();
        example.setAuthorId(author.getAuthorId());
        example.setFollowType(followType);
        List<AuthorFollow> list = authorFollowModel.getAuthorFollowList(example, pager);
        List<FollowVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            Author finalAuthor = author;
            list.forEach(follow -> {
                Author authorNew = null;
                if (finalAuthor.getAuthorId().equals(follow.getFromAuthorId())) {
                    authorNew = authorModel.getAuthorByAuthorId(follow.getToAuthorId());
                } else {
                    authorNew = authorModel.getAuthorByAuthorId(follow.getFromAuthorId());
                }
                //设置默认头像
                if (StringUtil.isEmpty(authorNew.getMemberAvatar())) {
                    authorNew.setMemberAvatar(videoSettingModel.getVideoSettingBySettingName("author_default_profile").getValue());
                }
                //无昵称,用会员账号
                if (StringUtil.isEmpty(authorNew.getMemberNickname())) {
                    authorNew.setMemberNickname(authorNew.getMemberName());
                }
                FollowVO vo = new FollowVO(authorNew);
                //关注列表都是已关注
                if (followType == VideoConst.FOLLOW_TYPE_1) {
                    vo.setIsFollow(true);
                } else {
                    //粉丝列表等于3说明是互相关注
                    if (follow.getType() == VideoConst.FOLLOW_TYPE_3) {
                        vo.setIsFollow(true);
                    }
                }
                vos.add(vo);
            });
        }
        return SldResponse.success(new PageVO<>(vos, pager));
    }
}
