package com.ruoyi.generator.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.generator.domain.Community.*;
import com.ruoyi.generator.mapper.community.*;
import com.ruoyi.generator.service.*;
import com.ruoyi.generator.vo.CommunityArticleVo;
import com.ruoyi.generator.vo.CommunityCircleVo;
import com.ruoyi.generator.vo.CommunityCollectionArticleVo;
import com.ruoyi.generator.vo.CommunityCollectionVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 社区文章管理
 *
 * @author fangzhen
 */
@Api(tags = "社区文章管理")
@RestController
@RequestMapping("/community/article")
public class CommunityArticleController extends BaseController {
    @Autowired
    private ICommunityArticleService communityArticleService;

    @Autowired
    private CommunityClassMapper communityClassMapper;

    @Autowired
    private CommunityArticleCommentMapper communityArticleCommentMapper;

    @Autowired
    private CommunityCommentLikeMapper communityCommentLikeMapper;

    @Autowired
    private CommunityUserCircleMapper communityUserCircleMapper;

    @Autowired
    private CommunityCircleMapper communityCircleMapper;

    @Autowired
    private CommunityClassCircleMapper communityClassCircleMapper;

    @Autowired
    private CommunityUserInfoMapper communityUserInfoMapper;

    @Autowired
    private ICommunityCollectionService communityCollectionService;

    @Autowired
    private ICommunityArticleRecommendService communityArticleRecommendService;

    @Autowired
    private ICommunityCommentReplyService commentReplyService;

    @Autowired
    private ICommunityPrivacyService communityPrivacyService;

    @Autowired
    private CommunityArticleMapper communityArticleMapper;
    /**
     * 获取文章列表信息
     */
    @ApiOperation("获取文章列表")
    @GetMapping("/list")
    //@Anonymous
    public TableDataInfo communityList(CommunityArticle communityArticle) {
        int pageNum = Convert.toInt(ServletUtils.getParameter("pageNum"), 1);
        int pageSize = Convert.toInt(ServletUtils.getParameter("pageSize"), 10);
        int searchType = Convert.toInt(ServletUtils.getParameter("searchType"), 0);
        TableDataInfo rspData = new TableDataInfo();
        List<CommunityArticleVo> list = communityArticleService.selectCommunityArticleList(rspData,communityArticle, pageNum, pageSize, searchType);
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        return rspData;
    }

    /**
     * 发布文章
     */
    @ApiOperation("发布文章")
    @PostMapping("/article")
    @Transactional
    //@Anonymous
    public AjaxResult article(@RequestBody CommunityArticle communityArticle) {
        if (communityArticle.getCircleIds().isEmpty()) {
            return AjaxResult.error("圈子不能为空");
        }

        if (communityArticle.getCircleIds().size() > 5) {
            return AjaxResult.error("只能绑定5个圈子!");
        }

        communityArticleService.insertCommunityArticle(communityArticle);
        return AjaxResult.success("文章发布成功!");
    }

    /**
     * 发布文章
     */
    @ApiOperation("删除文章")
    @DeleteMapping("/article")
    @Transactional
    //@Anonymous
    public AjaxResult article(String id) {
        if (Strings.isEmpty(id)) {
            return AjaxResult.error("参数异常!");
        }

        CommunityArticle communityArticle = new CommunityArticle();
        communityArticle.setIsDelete(true);
        boolean result = communityArticleService.update(communityArticle, new UpdateWrapper<CommunityArticle>().eq("id", id));
        if (result) {
            return success("删除成功!");
        }
        return error("删除失败!");
    }


    @GetMapping("/class")
    @ApiOperation("获取文章分类列表")
    //@Anonymous
    public AjaxResult getClassList() {
        List<CommunityClass> communityClasses = communityClassMapper.selectList(new QueryWrapper<CommunityClass>());
        return AjaxResult.success(communityClasses);
    }

    @GetMapping("/circleList")
    @ApiOperation("获取文章圈子列表")
    //@Anonymous
    public AjaxResult getCircleList() {
        List<CommunityCircle> communityClasses = communityCircleMapper.selectList(new QueryWrapper<CommunityCircle>());
        for (CommunityCircle communityCircle : communityClasses) {
            String className = communityClassCircleMapper.getClassNameByCircleId(communityCircle.getId());
            communityCircle.setCircleName(className + "·" + communityCircle.getCircleName());
        }
        return AjaxResult.success(communityClasses);
    }


    @ApiOperation("文章评论")
    @PostMapping("/comment")
    @Transactional
    public AjaxResult comment(@RequestBody CommunityArticleComment communityArticleComment) throws ParseException {
        if (null == communityArticleComment.getArticleId()) {
            return AjaxResult.error("文章不存在或异常!");
        }
        Long userId = SecurityUtils.getUserId();
        //调用方法去判断当前评论的用户 是不是文章作者的关注列表
        Boolean aBoolean = communityArticleService.checkCommentPermission(userId,null,communityArticleComment.getArticleId());
        communityArticleComment.setUserId(SecurityUtils.getUserId());
        if (!aBoolean) {  // 当 aBoolean 为 false 时，进入这个条件
            return AjaxResult.success("您没有权限评论此文章，因为只允许关注的人评论您!");
        }
        //新增评论
        communityArticleService.sendComment(communityArticleComment);
        return AjaxResult.success();
    }

    @ApiOperation("删除文章评价")
    @DeleteMapping("/comment")
    @Transactional
    public AjaxResult deleteComment(@RequestBody CommunityArticleComment communityArticleComment) {
        //获取评论信息
        CommunityArticleComment articleComment = communityArticleCommentMapper.selectById(communityArticleComment.getId());

        if (!articleComment.getCreateBy().equals(SecurityUtils.getUserId())) {
            return AjaxResult.error("不允许删除别人的评论!");
        }
        //删除评论
        communityArticleService.deleteComment(articleComment);
        return AjaxResult.success();
    }

    /**
     * 文章点赞
     */
    @ApiOperation("文章点赞")
    @PostMapping("/like")
    @Transactional
    //@Anonymous
    public AjaxResult like(@RequestBody CommunityLike communityLike) {
        if (Objects.isNull(communityLike.getArticleId()) || Objects.isNull(communityLike.getUserId())) {
            return AjaxResult.error("文章或用户信息异常!");
        }
        boolean isSuccess = true;
        String message = "";
        CommunityLike like = communityArticleService.selectCommunityLikeById(communityLike);
        if (Objects.isNull(like)) {
            //新增点赞
            communityLike.setCreateBy(String.valueOf(SecurityUtils.getLoginUser().getUserId()));
            communityLike.setUpdateBy(String.valueOf(SecurityUtils.getLoginUser().getUserId()));
            communityLike.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
            communityLike.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
            isSuccess = communityArticleService.insertCommunityLikeById(communityLike);
            message = "感谢点赞";
        } else {
            //删除点赞
            isSuccess = communityArticleService.deleteCommunityLikeById(like);
            message = "取消点赞";
        }

        if (!isSuccess) {
            message = "操作失败!";
            return AjaxResult.error(message);
        }
        return AjaxResult.success(message);
    }

    /**
     * 文章推荐值
     */
    @ApiOperation("新增/取消推荐值")
    @PostMapping("/recommend")
    @Transactional
    //@Anonymous
    public AjaxResult recommend(@RequestBody CommunityArticleRecommend articleRecommend) {
        if (Objects.isNull(articleRecommend.getArticleId())) {
            return AjaxResult.error("参数异常!");
        }
        boolean isSuccess = true;
        String message = "";
        Long userId = SecurityUtils.getUserId();
        CommunityArticleRecommend recommend = communityArticleRecommendService.getOne(new QueryWrapper<CommunityArticleRecommend>()
                .eq("article_id", articleRecommend.getArticleId())
                .eq("user_id", userId).and((wrapper) -> {
                    wrapper.ne("is_delete", true).or().isNull("is_delete");
                }));
        if (Objects.isNull(recommend)) {
            //新增推荐值
            recommend = new CommunityArticleRecommend();
            recommend.setArticleId(articleRecommend.getArticleId());
            recommend.setCreateBy(userId);
            recommend.setUserId(userId);
            recommend.setDelete(false);
            recommend.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
            isSuccess = communityArticleRecommendService.save(recommend);
            message = "感谢推荐";
        } else {
            //删除点赞
            recommend.setDelete(true);
            recommend.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
            recommend.setUpdateBy(userId);
            isSuccess = communityArticleRecommendService.updateById(recommend);
            message = "取消推荐";
        }

        if (!isSuccess) {
            message = "操作失败!";
            return AjaxResult.error(message);
        }
        return AjaxResult.success(message);
    }


    /**
     * 获取文章列表信息
     */
    @ApiOperation("文章收藏")
    @PostMapping("/collect")
    @Transactional
    //@Anonymous
    public AjaxResult collect(@RequestBody CommunityArticleCollect communityArticleCollect) {
        if (Objects.isNull(communityArticleCollect.getArticleId()) || Objects.isNull(communityArticleCollect.getUserId())) {
            return AjaxResult.error("文章或用户信息异常!");
        }
        boolean isSuccess = true;
        String message = "";
        CommunityArticleCollect collect = communityArticleService.selectCommunityCollectById(communityArticleCollect);
        if (Objects.isNull(collect) || Objects.isNull(collect.getId())) {
            //新增收藏
            isSuccess = communityArticleService.insertCommunityCollectById(communityArticleCollect);
            message = "收藏成功";
        } else {
            //删除收藏
            isSuccess = communityArticleService.deleteCommunityCollectById(collect);
            message = "取消收藏";
        }

        if (!isSuccess) {
            message = "操作失败!";
            return AjaxResult.error(message);
        }
        return AjaxResult.success(message);
    }


    /**
     * 评论点赞
     */
    @ApiOperation("评论点赞")
    @PostMapping("/commentLike")
    @Transactional
    //@Anonymous
    public AjaxResult commentLike(@RequestBody CommunityCommentLike commentLike) {
        if (Objects.isNull(commentLike.getCommentId())) {
            return AjaxResult.error("评论或用户信息异常!");
        }

        Long userId = SecurityUtils.getLoginUser().getUserId();
        String message = "";
        //评论点赞
        //查询该评论是否已点赞
        QueryWrapper<CommunityCommentLike> queryWrapper = null;
        if (commentLike.isReply()) {
            //回复的点赞
            queryWrapper = new QueryWrapper<CommunityCommentLike>()
                    .eq("reply_id", commentLike.getCommentId())
                    .eq("user_id", userId);
            commentLike.setReplyId(commentLike.getCommentId());
            commentLike.setCommentId(null);
        } else {
            //评论的点赞
            queryWrapper = new QueryWrapper<CommunityCommentLike>()
                    .eq("comment_id", commentLike.getCommentId())
                    .eq("user_id", userId);
        }

        CommunityCommentLike communityCommentLike = communityCommentLikeMapper.selectOne(queryWrapper);
        if (Objects.isNull(communityCommentLike) || Objects.isNull(communityCommentLike.getId())) {
            //新增点赞
            commentLike.setCreateBy(userId);
            commentLike.setUserId(userId);
            commentLike.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
            communityCommentLikeMapper.insert(commentLike);
            message = "感谢点赞";
        } else {
            //删除点赞
            communityCommentLikeMapper.deleteById(communityCommentLike);
            message = "取消点赞";
        }
        return AjaxResult.success(message);
    }


    @ApiOperation("获取圈子信息")
    @GetMapping("/circle")
    //@Anonymous
    public AjaxResult circle(@RequestParam("classId") String classId) {
        if (Strings.isBlank(classId)) {
            return AjaxResult.error("板块信息有误!");
        }
        List<CommunityCircleVo> communityCircles = communityArticleService.selectCommunityCircleList(classId);
        return AjaxResult.success(communityCircles);
    }

    @ApiOperation("我的圈子")
    @GetMapping("/myCircle")
    //@Anonymous
    public AjaxResult myCircle(@RequestParam(required = false) String circleName) {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        List<CommunityUserCircle> communityUserCircles = communityUserCircleMapper.selectList(new QueryWrapper<CommunityUserCircle>()
                .eq("user_id", userId)
                .and((wrapper) -> {
                    wrapper.ne("is_delete", 1).or().isNull("is_delete");
                }));

        List<Long> circleIds = new ArrayList<>();
        for (CommunityUserCircle communityUserCircle : communityUserCircles) {
            circleIds.add(communityUserCircle.getCircleId());
        }
        List<CommunityCircle> communityCircles = null;
        if (!circleIds.isEmpty()) {
            communityCircles = communityCircleMapper.selectList(new QueryWrapper<CommunityCircle>()
                    .in("id", circleIds)
                    .like("circle_name", circleName));
        }
        return AjaxResult.success("获取成功!", communityCircles);
    }


    @ApiOperation("收藏/取关圈子")
    @PostMapping("/circle")
    @Transactional
    //@Anonymous
    public AjaxResult circle(@RequestBody CommunityUserCircle communityUserCircle) {
        if (Objects.isNull(communityUserCircle.getCircleId())) {
            return AjaxResult.error("关注圈子异常,请刷新页面重试!");
        }
        Long userId = SecurityUtils.getLoginUser().getUserId();
        CommunityUserCircle userCircle = communityUserCircleMapper
                .selectOne(new QueryWrapper<CommunityUserCircle>()
                        .eq("circle_id", communityUserCircle.getCircleId())
                        .eq("user_id", userId)
                        .eq("is_delete", 0));
        String msg = "";
        if (Objects.isNull(userCircle) || Objects.isNull(userCircle.getId())) {
            //如果未找到数据,则进行关注
            userCircle = new CommunityUserCircle();
            userCircle.setCircleId(communityUserCircle.getCircleId());
            userCircle.setUserId(userId);
            userCircle.setCreateBy(userId);
            userCircle.setUpdateBy(userId);
            userCircle.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
            userCircle.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
            communityUserCircleMapper.insert(userCircle);
            msg = "已关注";
        } else {
            //更新删除标识
            userCircle.setDelete(true);
            userCircle.setCreateBy(userId);
            userCircle.setUpdateBy(userId);
            userCircle.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
            userCircle.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
            communityUserCircleMapper.updateById(userCircle);
            msg = "已取关";
        }
        return AjaxResult.success(msg);
    }

    /**
     * 关注用户
     *
     * @param likeUserId 被关注人id
     * @return 当前关注信息
     */

    @ApiOperation("关注/取关用户")
    @PostMapping("/likeUser")
    @Transactional
    public AjaxResult userLike(@RequestParam("likeUserId") Long likeUserId) {
        if (Objects.isNull(likeUserId)) {
            return AjaxResult.error("参数失效!");
        }
        String msg = "";
        CommunityUserLike communityUserLike = communityArticleService.addOrDeleteUserLike(likeUserId);
        if (Objects.isNull(communityUserLike) || Objects.isNull(communityUserLike.getId())) {
            msg = "取消关注";
        } else {
            msg = "已关注";
        }
        return AjaxResult.success(msg);
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/userInfo")
    public AjaxResult userInfo(Long userId) {
        if (Objects.isNull(userId)) {
            userId = SecurityUtils.getLoginUser().getUserId();
        }
        return AjaxResult.success(communityArticleService.selectCommunityUserInfoById(userId));
    }


    @ApiOperation("查询用户")
    @GetMapping("/userList")
    public AjaxResult userList(String SearchValue) {
        if (Objects.isNull(SearchValue)) {
            return AjaxResult.error();
        }
        return AjaxResult.success(communityArticleService.selectUserBySearchValue(SearchValue));
    }

    @ApiOperation("根据条件查询账户")
    @GetMapping("/selectUserList")
    public AjaxResult selectUserList(String SearchValue) {
        if (Objects.isNull(SearchValue)) {
            return AjaxResult.error();
        }
        return AjaxResult.success(communityArticleService.selectUsersByAccountOrName(SearchValue));
    }


    @ApiOperation("获取关注列表")
    @GetMapping("/likeUserList")
    public AjaxResult likeUserList() {
        return AjaxResult.success(communityArticleService.selectCommunityUserLikeList(SecurityUtils.getLoginUser().getUserId()));
    }

    @ApiOperation("获取粉丝列表")
    @GetMapping("/userFans")
    public AjaxResult userFans() {
        return AjaxResult.success(communityArticleService.selectUserFansList(SecurityUtils.getLoginUser().getUserId()));
    }

    @ApiOperation("互相关注列表")
    @GetMapping("/mutualAttention")
    public AjaxResult mutualAttention() {
        return AjaxResult.success(communityArticleService.selectMutualAttention(SecurityUtils.getLoginUser().getUserId()));
    }

    @ApiOperation("发送用户验证码")
    @GetMapping("/sendSms")
    //todo
    public AjaxResult sendSms() {
        return AjaxResult.success();
    }

    /**
     * 更新用户背景图片
     *
     * @param backImage 背景图url
     * @return 是否成功
     */
    @ApiOperation("更新用户背景图片")
    @PostMapping("/uploadBackImage")
    @Transactional
    public AjaxResult uploadBackImage(@RequestParam("backImage") String backImage) {
        if (backImage == null) {
            return AjaxResult.error("背景图不能为空");
        }

        Long userId = SecurityUtils.getLoginUser().getUserId();
        CommunityUserInfo communityUserInfo = communityUserInfoMapper.selectOne(new QueryWrapper<CommunityUserInfo>().eq("user_id", userId));
        if (Objects.isNull(communityUserInfo) || Objects.isNull(communityUserInfo.getId())) {
            return AjaxResult.error("系统出错");
        }
        communityUserInfo.setBackImage(backImage);
        communityUserInfoMapper.updateById(communityUserInfo);
        return AjaxResult.success("背景图片上传成功!");
    }

    /**
     * 用户合集
     *
     * @return 是否成功
     */
    @ApiOperation("用户合集")
    @GetMapping("/userCollection")
    public AjaxResult createCollection(Long userId) {
        if (Objects.isNull(userId)) {
            return AjaxResult.error("参数异常!");
        }

//        List<CommunityCollection> collections = communityCollectionService.list(new QueryWrapper<CommunityCollection>()
//                .eq("user_id", userId)
//                .ne("is_delete", true)
//                .or()
//                .isNull("is_delete"));

        List<CommunityCollectionVo> communityCollectionVos = communityCollectionService.selectUserCollection(userId);

        return AjaxResult.success(communityCollectionVos);
    }


    /**
     * 用户新增合集
     *
     * @param communityCollection 新增合集数据
     * @return 是否成功
     */
    @ApiOperation("用户新增合集")
    @PostMapping("/createCollection")
    @Transactional
    public AjaxResult createCollection(@RequestBody CommunityCollection communityCollection) {

        if (Objects.isNull(communityCollection.getCollectionName())) {
            return AjaxResult.error("合集名称不能为空");
        }

        if (Objects.isNull(communityCollection.getImages())) {
            return AjaxResult.error("合集图片不能为空");
        }

        CommunityCollection collection = communityCollectionService
                .getOne(new QueryWrapper<CommunityCollection>()
                        .eq("collection_name", communityCollection.getCollectionName())
                        .eq("user_id", SecurityUtils.getLoginUser().getUserId())
                        .and((wrapper) -> {
                            wrapper.ne("is_delete", true)
                                    .or()
                                    .isNull("is_delete");
                        }));

        if (!Objects.isNull(collection)) {
            return AjaxResult.error("合集名称不能重复!");
        }

        communityCollection.setUserId(SecurityUtils.getLoginUser().getUserId());
        communityCollection.setCreateBy(SecurityUtils.getLoginUser().getUserId());
        communityCollection.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
        communityCollection.setDelete(false);
        communityCollectionService.save(communityCollection);

        return AjaxResult.success(communityCollection);
    }

    /**
     * 用户删除合集
     *
     * @param collectionId 合集id
     * @return 是否成功
     */
    @ApiOperation("用户删除合集")
    @DeleteMapping("/deleteCollection")
    @Transactional
    public AjaxResult deleteCollection(Long collectionId) {
        if (Objects.isNull(collectionId)) {
            return AjaxResult.error("参数异常!");
        }

        communityCollectionService.deleteCollectionById(collectionId);
        return AjaxResult.success("删除成功!");
    }

    /**
     * 合集内新增文章
     *
     * @param collectionArticle 合集内新增文章
     * @return 是否成功
     */
    @ApiOperation("合集内新增文章")
    @PostMapping("/addArticleToCollection")
    @Transactional
    public AjaxResult addArticleToCollection(@RequestBody CommunityCollectionArticle collectionArticle) {
        if (Objects.isNull(collectionArticle.getArticleId())) {
            return AjaxResult.error("文章参数异常!");
        }

        if (Objects.isNull(collectionArticle.getCollectionId())) {
            return AjaxResult.error("合集参数异常!");
        }

        collectionArticle.setCreateBy(SecurityUtils.getLoginUser().getUserId());
        collectionArticle.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
        communityCollectionService.addArticleToCollection(collectionArticle);

        return AjaxResult.success("加入合集成功!");
    }

    /**
     * 合集内删除文章
     *
     * @param collectionId 合集id
     * @param articleId    文章id
     * @return 是否成功
     */
    @ApiOperation("合集内删除文章")
    @DeleteMapping("/deleteArticleInCollection")
    @Transactional
    public AjaxResult addArticleToCollection(Long collectionId, Long articleId) {
        if (Objects.isNull(collectionId) || Objects.isNull(articleId)) {
            return AjaxResult.error("参数异常!");
        }

        communityCollectionService.deleteArticleToCollection(collectionId, articleId);
        return AjaxResult.success("文章删除成功!");
    }

    /**
     * 查询合集下文章信息
     *
     * @param collectionId 合集id
     * @return 合集下文章信息
     */
    @ApiOperation("查询用户合集")
    @GetMapping("/getCollection")
    public AjaxResult getCollection(Long collectionId) {
        if (Objects.isNull(collectionId)) {
            return AjaxResult.error("合集不存在!");
        }
        List<CommunityCollectionArticleVo> collectionArticleVos = communityCollectionService.selectArticleInfoInCollection(collectionId);
        return AjaxResult.success(collectionArticleVos);
    }




}
