package com.ruoyi.generator.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.generator.domain.Community.*;
import com.ruoyi.generator.mapper.community.*;
import com.ruoyi.generator.vo.*;
import com.ruoyi.system.mapper.SysUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 业务 服务层实现
 *
 * @author ruoyi
 */
@Service
public class CommunityArticleServiceImpl extends ServiceImpl<CommunityArticleMapper, CommunityArticle> implements ICommunityArticleService {
    private static final Logger log = LoggerFactory.getLogger(CommunityArticleServiceImpl.class);

    @Autowired
    private CommunityArticleMapper communityArticleMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private CommunityLikeMapper communityLikeMapper;

    @Autowired
    private CommunityCollectMapper communityCollectMapper;

    @Autowired
    private CommunityArticleCommentMapper communityArticleCommentMapper;

    @Autowired
    private CommunityCommentLikeMapper communityCommentLikeMapper;

    @Autowired
    private CommunityArticleTagMapper articleTagMapper;

    @Autowired
    private CommunityArticleTagMapper communityArticleTagMapper;

    @Autowired
    private CommunityTagMapper communityTagMapper;

    @Autowired
    private CommunityArticleImagesMapper communityArticleImagesMapper;

    @Autowired
    private CommunityClassCircleMapper communityClassCircleMapper;

    @Autowired
    private CommunityCircleMapper communityCircleMapper;

    @Autowired
    private CommunityUserCircleMapper communityUserCircleMapper;

    @Autowired
    private CommunityUserLikeMapper communityUserLikeMapper;

    @Autowired
    private CommunityUserInfoMapper communityUserInfoMapper;

    @Autowired
    private ICommunityArticleCircleService communityArticleCircleService;

    @Autowired
    private CommunityCollectionArticleMapper communityCollectionArticleMapper;

    @Autowired
    private ICommunityCollectionArticleService collectionArticleService;

    @Autowired
    private CommunityTagBlockMapper communityTagBlockMapper;

    @Autowired
    private CommunityArticleRecommendMapper recommendMapper;

    @Autowired
    private ICommunityArticleService communityArticleService;

    @Autowired
    private ICommunityPrivacyService communityPrivacyService;

    /**
     * 查询文章列表
     *
     * @param communityArticle 文章信息
     * @return 文章信息集合
     */
    @Override
    public List<CommunityArticleVo> selectCommunityArticleList(TableDataInfo rspData, CommunityArticle communityArticle, int pageNum, int pageSize, int searchType) {
        //找出板块下的分类
        Long classId = communityArticle.getClassId();
        Long id = communityArticle.getId();
        Long circleId = communityArticle.getCircleId();
        Long userId = SecurityUtils.getUserId();
        List<CommunityArticleVo> communityArticleVos = null;
        if (Objects.nonNull(id)) {
            //获取指定文章详细内容,文章浏览量+1
            CommunityArticle article = communityArticleMapper.selectById(id);
            article.setPageViews(article.getPageViews() + 1);
            communityArticleMapper.updateById(article);
        }

        List<Long> circleIds = null;
        if (Objects.nonNull(classId)) {
            List<CommunityClassCircle> classCircles = communityClassCircleMapper.selectList(new QueryWrapper<CommunityClassCircle>().eq("class_id", classId));
            circleIds = new ArrayList<>();
            for (CommunityClassCircle classCircle : classCircles) {
                circleIds.add(classCircle.getCircleId());
            }
        }

        //如果有圈子id,则按照传递的圈子id取文章数据
        if (Objects.nonNull(circleId)) {
            circleIds = new ArrayList<>();
            circleIds.add(circleId);
        }

        //如果没有圈子,则返回null数据
        if (Objects.isNull(circleIds) || circleIds.isEmpty()) {
            communityArticleVos = new ArrayList<>();
        }

        //根据分类查找文章
        int offset = (pageNum - 1) * pageSize;
        communityArticleVos = communityArticleMapper.selectCommunityArticleList(communityArticle, circleIds, offset, pageSize, searchType);
        rspData.setTotal(communityArticleMapper.selectCommunityArticleCount(communityArticle, circleIds, searchType));
        List<CommunityArticleVo> communityArticleVos_copy = new ArrayList<>(communityArticleVos);
        for (CommunityArticleVo articleVo : communityArticleVos_copy) {
            List<Map<String, Object>> imageList = articleVo.getImageList();
            articleVo.setCircleIds(circleIds);
            List<CommunityArticleImages> videoList = new ArrayList<>();
            CommunityArticleImages videos = null;
            for (Map<String, Object> image : imageList) {
                videos = new CommunityArticleImages();
                String imageUrl = image.get("imageUrl").toString();
                //判断是否是视频
                boolean isVideo = isVideoFile(imageUrl);
                if (isVideo) {
                    imageList.remove(image);
                    BeanUtils.copyProperties(image, videos);
                    videoList.add(videos);
                }
            }
            articleVo.setVideoList(videoList);

            //设置评论回复数量
            articleVo.setCommentCount(communityArticleCommentMapper.queryCommentCount(articleVo.getId()));
            //设置文章的点赞数量
            articleVo.setLikeCount(communityLikeMapper.selectList(new QueryWrapper<CommunityLike>().eq("article_id", articleVo.getId())).size());
            //设置文章的收藏数量
            articleVo.setCollectCount(communityCollectMapper.selectList(new QueryWrapper<CommunityArticleCollect>().eq("article_id", articleVo.getId())).size());
            //设置文章推荐数量
            articleVo.setRecommendCount(recommendMapper.selectList(new QueryWrapper<CommunityArticleRecommend>()
                    .eq("article_id", articleVo.getId())
                    .and((wrapper) -> {
                        wrapper.ne("is_delete", true).or().isNull("is_delete");
                    })).size());

            //文章下的评论
//            List<Map<String, Object>> comments = articleVo.getComments();
//            for (Map<String, Object> communityArticleCommentVo : comments) {
//                String commentUserId = communityArticleCommentVo.get("userId").toString();
//                if (Objects.isNull(commentUserId)) {
//                    break;
//                }
//                //获取评论的用户信息
//                SysUser sysUser = sysUserMapper.selectUserById(Long.parseLong(commentUserId));
//                communityArticleCommentVo.put("username", sysUser.getUserName());
//                communityArticleCommentVo.put("avatar", sysUser.getAvatar());
//                //当前登录用户是否已点赞
//                List<CommunityCommentLike> commentLikes = communityCommentLikeMapper.selectList(new QueryWrapper<CommunityCommentLike>().eq("comment_id", communityArticleCommentVo.get("id")).eq("user_id", userId));
//                communityArticleCommentVo.put("commentLike", !commentLikes.isEmpty());
//
//                //该评论的点赞数量
//                communityArticleCommentVo.put("commentLikeCount", communityCommentLikeMapper.selectList(new QueryWrapper<CommunityCommentLike>().eq("comment_id", communityArticleCommentVo.get("id"))).size());
//            }

            //判断是否已收藏
            CommunityArticleCollect collect = communityCollectMapper.selectOne(new QueryWrapper<CommunityArticleCollect>().eq("user_id", userId).eq("article_id", articleVo.getId()));
            articleVo.setCollect(!Objects.isNull(collect));

            //判断是否已点赞
            CommunityLike like = communityLikeMapper.selectOne(new QueryWrapper<CommunityLike>().eq("user_id", userId).eq("article_id", articleVo.getId()));
            articleVo.setLike(!Objects.isNull(like));

            //判断是否已推荐
            CommunityArticleRecommend recommend = recommendMapper.selectOne(new QueryWrapper<CommunityArticleRecommend>()
                    .eq("user_id", userId)
                    .eq("article_id", articleVo.getId()).and((wrapper) -> {
                        wrapper.ne("is_delete", true).or().isNull("is_delete");
                    }));
            articleVo.setRecommend(!Objects.isNull(recommend));

            //获取文章标签
            List<CommunityArticleTag> articleTags = communityArticleTagMapper.selectList(new QueryWrapper<CommunityArticleTag>().eq("article_id", articleVo.getId()));
            List<Long> tagList = articleTags.stream().map(CommunityArticleTag::getTagId).collect(Collectors.toList());
            List<Long> tagIds = new ArrayList<>();

            if (!tagList.isEmpty()) {
                //判断当前标签是否被当前登录用户拉黑
                List<CommunityTagBlock> communityTagBlocks = communityTagBlockMapper.selectList(new QueryWrapper<CommunityTagBlock>()
                        .in("tag_id", tagList)
                        .eq("user_id", userId));

                for (CommunityTagBlock tagBlock : communityTagBlocks) {
                    if (tagBlock.isBlock()) {
                        communityArticleVos.remove(articleVo);
                        break;
                    }
                    tagIds.add(tagBlock.getTagId());
                }

                if (communityTagBlocks.isEmpty()) {
                    tagIds.addAll(tagList);
                }

                if (!tagIds.isEmpty()) {
                    List<CommunityTag> communityTags = communityTagMapper.selectBatchIds(tagIds);
                    articleVo.setTags(communityTags);
                }
            }
        }
        return communityArticleVos;
    }

    /**
     * 发布文章
     *
     * @param communityArticle 文章信息
     */
    @Override
    public void insertCommunityArticle(CommunityArticle communityArticle) {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        //插入文章信息
        communityArticle.setUserId(userId);
        communityArticle.setCreateBy(userId);
        communityArticle.setUpdateBy(userId);
        communityArticle.setIsDelete(false);
        communityArticle.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
        communityArticle.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
        communityArticleMapper.insert(communityArticle);
        //插入标签日志
        List<String> tags = communityArticle.getTags();
        CommunityArticleTag tagLog = null;
        for (String tag : tags) {
            tagLog = new CommunityArticleTag();
            tagLog.setArticleId(communityArticle.getId());
            tagLog.setTagId(Long.parseLong(tag));
            tagLog.setUpdateBy(userId);
            tagLog.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
            tagLog.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
            tagLog.setCreateBy(userId);
            articleTagMapper.insert(tagLog);

            //标签热度自增
            CommunityTag communityTag = communityTagMapper.selectById(Long.parseLong(tag));
            communityTag.setTagHot(Objects.isNull(communityTag.getTagHot()) ? 1 : communityTag.getTagHot() + 1);
            communityTag.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
            communityTag.setUpdateBy(userId);
            communityTagMapper.updateById(communityTag);
        }

        //插入图片日志
        List<String> images = communityArticle.getImages();
        CommunityArticleImages articleImages = null;
        for (String image : images) {
            articleImages = new CommunityArticleImages();
            articleImages.setArticleId(communityArticle.getId());
            articleImages.setImageUrl(image);
            articleImages.setUpdateBy(userId);
            articleImages.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
            articleImages.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
            articleImages.setCreateBy(userId);
            communityArticleImagesMapper.insert(articleImages);
        }

        //插入圈子
        List<String> circleIds = communityArticle.getCircleIds();
        List<CommunityArticleCircle> articleCircles = new ArrayList<>();
        CommunityArticleCircle articleCircle = null;
        for (String circleId : circleIds) {
            articleCircle = new CommunityArticleCircle();
            articleCircle.setCircleId(Long.parseLong(circleId));
            articleCircle.setArticleId(communityArticle.getId());
            articleCircle.setCreateBy(userId);
            articleCircle.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
            articleCircles.add(articleCircle);
        }
        communityArticleCircleService.saveBatch(articleCircles);

        //插入合集
        List<String> collectionIds = communityArticle.getCollectionIds();
        List<CommunityCollectionArticle> collectionArticles = new ArrayList<>();
        CommunityCollectionArticle collectionArticle = null;
        for (String collectionId : collectionIds) {
            collectionArticle = new CommunityCollectionArticle();
            collectionArticle.setCollectionId(Long.parseLong(collectionId));
            collectionArticle.setArticleId(communityArticle.getId());
            collectionArticle.setCreateBy(userId);
            collectionArticle.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
            collectionArticles.add(collectionArticle);
        }
        collectionArticleService.saveBatch(collectionArticles);
    }


    /**
     * 发送评论
     *
     * @param communityArticleComment 评论信息
     */
    @Override
    public void sendComment(CommunityArticleComment communityArticleComment) throws ParseException {
        communityArticleComment.setId(null);
        communityArticleComment.setCreateBy(SecurityUtils.getLoginUser().getUserId());
        communityArticleComment.setUpdateBy(SecurityUtils.getLoginUser().getUserId());
        communityArticleComment.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
        communityArticleComment.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
        communityArticleComment.setDelete(false);
        communityArticleCommentMapper.insert(communityArticleComment);
    }

    /**
     * 删除评论
     *
     * @param communityArticleComment 评论信息
     */
    @Override
    public void deleteComment(CommunityArticleComment communityArticleComment) {
        communityArticleComment.setDelete(true);
        communityArticleComment.setUpdateBy(SecurityUtils.getUserId());
        communityArticleComment.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
        communityArticleCommentMapper.updateById(communityArticleComment);
    }


    /**
     * 查询该文章对应的用户是否已经点赞
     *
     * @param communityLike 点赞信息
     * @return 点赞信息
     */
    @Override
    public CommunityLike selectCommunityLikeById(CommunityLike communityLike) {
        QueryWrapper<CommunityLike> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id", communityLike.getArticleId()).eq("user_id", communityLike.getUserId());
        return communityLikeMapper.selectOne(queryWrapper);
    }


    /**
     * 新增点赞
     *
     * @param communityLike 点赞信息
     * @return 点赞是否成功
     */
    @Override
    public boolean insertCommunityLikeById(CommunityLike communityLike) {
        return communityLikeMapper.insert(communityLike) > 0;
    }


    /**
     * 删除点赞
     *
     * @param communityLike 点赞信息
     * @return 删除是否成功
     */
    @Override
    public boolean deleteCommunityLikeById(CommunityLike communityLike) {
        return communityLikeMapper.deleteById(communityLike.getId()) > 0;
    }


    /**
     * 查询该文章对应的用户是否已经收藏
     *
     * @param collect 收藏信息
     * @return 收藏信息
     */
    @Override
    public CommunityArticleCollect selectCommunityCollectById(CommunityArticleCollect collect) {
        return communityCollectMapper.selectOne(new QueryWrapper<CommunityArticleCollect>().eq("article_id", collect.getArticleId()).eq("user_id", SecurityUtils.getUserId()));
    }

    /**
     * 新增收藏
     *
     * @param collect 收藏信息
     * @return 收藏是否成功
     */
    @Override
    public boolean insertCommunityCollectById(CommunityArticleCollect collect) {
        return communityCollectMapper.insert(collect) > 0;
    }

    /**
     * 删除收藏
     *
     * @param collect 收藏信息
     * @return 删除是否成功
     */
    @Override
    public boolean deleteCommunityCollectById(CommunityArticleCollect collect) {
        return communityCollectMapper.deleteById(collect) > 0;
    }


    /**
     * 根据板块获取圈子列表
     *
     * @param classId 板块id
     * @return 圈子列表信息
     */
    @Override
    public List<CommunityCircleVo> selectCommunityCircleList(String classId) {
        List<CommunityClassCircle> classes = communityClassCircleMapper.selectList(new QueryWrapper<CommunityClassCircle>().eq("class_id", classId));
        List<Long> circleIds = new ArrayList<>();
        for (CommunityClassCircle aClass : classes) {
            circleIds.add(aClass.getCircleId());
        }

        List<CommunityCircleVo> communityCircleVos = null;
        if (!circleIds.isEmpty()) {
            List<CommunityCircle> communityCircles = communityCircleMapper.selectBatchIds(circleIds);
            //复制到Vo对象中
            communityCircleVos = new ArrayList<>();
            CommunityCircleVo communityCircleVo = null;
            for (CommunityCircle communityCircle : communityCircles) {
                communityCircleVo = new CommunityCircleVo();
                BeanUtils.copyProperties(communityCircle, communityCircleVo);

                //获取当前用户是否有关注这些圈子
                CommunityUserCircle communityUserCircles = communityUserCircleMapper.selectOne(new QueryWrapper<CommunityUserCircle>().eq("circle_id", communityCircle.getId()).eq("user_id", SecurityUtils.getLoginUser().getUserId()).eq("is_delete", 0));
                if (Objects.isNull(communityUserCircles) || Objects.isNull(communityUserCircles.getId())) {
                    //没找到关注数据,则设为false,反之则true
                    communityCircleVo.setLike(false);
                } else {
                    communityCircleVo.setLike(true);
                }
                communityCircleVos.add(communityCircleVo);
            }
        }
        return communityCircleVos;
    }

    /**
     * 关注或取消关注用户粉丝/关注
     *
     * @param likeUserId 被关注人id
     * @return 登录用户关注信息
     */
    @Override
    public CommunityUserLike addOrDeleteUserLike(Long likeUserId) {
        Long userId = SecurityUtils.getLoginUser().getUserId();  // 当前登录用户id
        //1.检查是否已被当前用户关注
        CommunityUserLike communityUserLike = communityUserLikeMapper.selectOne(new QueryWrapper<CommunityUserLike>().eq("user_id", userId).eq("like_user_id", likeUserId));
        //2.1 没有则进行关注,返回关注列表信息
        if (Objects.isNull(communityUserLike) || Objects.isNull(communityUserLike.getId())) {
            communityUserLike = new CommunityUserLike();
            communityUserLike.setUserId(userId);
            communityUserLike.setLikeUserId(likeUserId);
            communityUserLike.setCreateBy(userId);
            communityUserLike.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
            communityUserLikeMapper.insert(communityUserLike);

            communityUserLike = communityUserLikeMapper.selectOne(new QueryWrapper<CommunityUserLike>().eq("user_id", userId).eq("like_user_id", likeUserId));
            return communityUserLike;
        }

        //2.2 已关注则取消关注
        communityUserLikeMapper.deleteById(communityUserLike);
        return null;
    }

    /**
     * 获取当前登录用户信息
     *
     * @param userId 用户id
     * @return 用户信息
     */
    @Override
    public CommunityUserInfoVo selectCommunityUserInfoById(Long userId) {
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        CommunityUserInfo communityUserInfo = communityUserInfoMapper.selectOne(new QueryWrapper<CommunityUserInfo>().eq("user_id", userId));
        CommunityUserInfoVo communityUserInfoVo = new CommunityUserInfoVo();
        BeanUtils.copyProperties(communityUserInfo, communityUserInfoVo);
        communityUserInfoVo.setAvatar(sysUser.getAvatar());
        communityUserInfoVo.setNickName(sysUser.getNickName());
        communityUserInfoVo.setSex(sysUser.getSex());
        communityUserInfoVo.setUserId(userId);

        //设置关注,粉丝,陪伴数量
        communityUserInfoVo.setLikeCount(communityUserLikeMapper.selectList(new QueryWrapper<CommunityUserLike>().eq("user_id", userId)).size());
        communityUserInfoVo.setFansCount(communityUserLikeMapper.selectList(new QueryWrapper<CommunityUserLike>().eq("like_user_id", userId)).size());
        communityUserInfoVo.setCompanionCount(0);

        //设置是否被当前登录的用户关注
        communityUserInfoVo.setLike(false);
        Long loginUserId = SecurityUtils.getLoginUser().getUserId();
        if (!Objects.equals(userId, loginUserId)) {
            CommunityUserLike communityUserLike = communityUserLikeMapper.selectOne(new QueryWrapper<CommunityUserLike>().eq("user_id", loginUserId).eq("like_user_id", userId));
            if (!Objects.isNull(communityUserLike) && !Objects.isNull(communityUserLike.getId())) {
                communityUserInfoVo.setLike(true);
            }
        }

        return communityUserInfoVo;
    }

    /**
     * 根据搜索值,搜索用户
     *
     * @param SearchValue 搜索值
     * @return 用户
     */
    @Override
    public List<CommunityUserInfoVo> selectUserBySearchValue(String SearchValue) {
        return communityUserInfoMapper.selectUserBySearchValue(SearchValue);
    }

    /**
     * 根据账户或者用户名称,搜索用户
     *
     * @param SearchValue
     * @return 用户
     */
    @Override
    public List<CommunityUserInfoVo> selectUsersByAccountOrName(String SearchValue) {
        return communityUserInfoMapper.selectUsersByAccountOrName(SearchValue);
    }


    /**
     * 获取关注列表
     *
     * @param userId 登录用户id
     * @return 当前用户关注列表
     */
    @Override
    public List<CommunityUserLikeVo> selectCommunityUserLikeList(Long userId) {
        List<CommunityUserLike> communityUserLikes = communityUserLikeMapper.selectList(new QueryWrapper<CommunityUserLike>().eq("user_id", userId));
        List<CommunityUserLikeVo> communityUserLikeVos = new ArrayList<>();
        CommunityUserLikeVo communityUserLikeVo = null;
        for (CommunityUserLike communityUserLike : communityUserLikes) {
            communityUserLikeVo = new CommunityUserLikeVo();
            SysUser sysUser = sysUserMapper.selectUserById(communityUserLike.getLikeUserId());
            BeanUtils.copyProperties(communityUserLike, communityUserLikeVo);
            communityUserLikeVo.setLikeUsername(sysUser.getUserName());
            communityUserLikeVos.add(communityUserLikeVo);
        }
        return communityUserLikeVos;
    }


    /**
     * 获取粉丝列表
     *
     * @param userId 登录用户id
     * @return 当前用户粉丝列表
     */
    @Override
    public List<CommunityUserLikeVo> selectUserFansList(Long userId) {
        List<CommunityUserLike> communityUserLikes = communityUserLikeMapper.selectList(new QueryWrapper<CommunityUserLike>().eq("like_user_id", userId));
        List<CommunityUserLikeVo> communityUserLikeVos = new ArrayList<>();
        CommunityUserLikeVo communityUserLikeVo = null;
        for (CommunityUserLike communityUserLike : communityUserLikes) {
            communityUserLikeVo = new CommunityUserLikeVo();
            BeanUtils.copyProperties(communityUserLike, communityUserLikeVo);
            SysUser sysUser = sysUserMapper.selectUserById(communityUserLike.getUserId());
            communityUserLikeVo.setUsername(sysUser.getUserName());
            communityUserLikeVos.add(communityUserLikeVo);
        }
        return communityUserLikeVos;
    }

    /**
     * 获取互相关注列表
     *
     * @param userId 登录用户id
     * @return 获取互相关注列表
     */
    @Override
    public List<CommunityUserLikeVo> selectMutualAttention(Long userId) {
        //先查询自己关注的人
        List<CommunityUserLikeVo> communityUserLikeVos = selectCommunityUserLikeList(userId);
        //再查询被关注的人是否关注自己
        List<Long> likeUserIds = new ArrayList<>();
        for (CommunityUserLikeVo communityUserLikeVo : communityUserLikeVos) {
            likeUserIds.add(communityUserLikeVo.getLikeUserId());
        }

        if (!likeUserIds.isEmpty()) {
            List<CommunityUserLike> communityUserLikes = communityUserLikeMapper.selectList(new QueryWrapper<CommunityUserLike>().in("user_id", likeUserIds).eq("like_user_id", userId));
            CommunityUserLikeVo communityUserLikeVo = null;
            communityUserLikeVos = new ArrayList<>();
            for (CommunityUserLike communityUserLike : communityUserLikes) {
                communityUserLikeVo = new CommunityUserLikeVo();
                BeanUtils.copyProperties(communityUserLike, communityUserLikeVo);
                SysUser sysUser = sysUserMapper.selectUserById(communityUserLike.getUserId());
                communityUserLikeVo.setUsername(sysUser.getUserName());
                communityUserLikeVos.add(communityUserLikeVo);
            }
        }
        return communityUserLikeVos;
    }

    /**
     * 判断评论的人 是否在文章作者的关注列表中
     *
     * @param userId    必填
     * @param commentId 可选  评论的评论接口
     * @param articleId 可选  文章评论接口
     * @return true or false
     * @throws ParseException
     */
    @Override
    public Boolean checkCommentPermission(Long userId, Long commentId, Long articleId) throws ParseException {
        /**
         * 1.传commentId 说明是 评论的评论接口
         * 2.传articleId 说明是文章评论接口
         * 3.询隐私设置表 communityPrivacyService.selectUserPrivacy 权限有没有开启
         * 4.没有开启 直接结束
         * 5.开启 查询作者关注列表
         * 6。是否是关注的人评论我 有则评论成功，没有则返回失败
         */
        //假设传的评论ID 根据 评论ID要找到文章ID
        if (articleId == null) {
            List<CommunityArticleComment> communityArticleComments
                    = communityArticleCommentMapper
                    .selectList(new QueryWrapper<CommunityArticleComment>().eq("id", commentId));
            CommunityArticleComment communityArticleComment = communityArticleComments.get(0);
            articleId = communityArticleComment.getArticleId();
        }
        ;

        //获取文章信息 找到文章创建人
        List<CommunityArticle> communityArticles
                = communityArticleMapper
                .selectList(new QueryWrapper<CommunityArticle>().eq("id", articleId));

        // 提取用户ID
        Long articleUserId = null; // 初始化用户ID

        if (!communityArticles.isEmpty()) { // 检查列表是否为空
            CommunityArticle article = communityArticles.get(0); // 获取第一个文章
            articleUserId = article.getUserId(); // 假设CommunityArticle有getUserId()方法
        } else {
            // 处理未找到文章的情况
            // 例如，可以抛出异常或记录日志
            return false;
        }

        // 直接允许作者评论
        if (articleUserId.equals(userId)) {
           /* // 如果评论者是文章作者，直接进行评论
            communityArticleService.sendComment(communityArticleComment);*/
            return true;
        }

        // 查询隐私设置
        List<CommunityUserPrivacyVo> communityUserPrivacyVos = communityPrivacyService.selectUserPrivacy(articleUserId);
        // 检查隐私设置 只允许我关注的人评论我
        boolean IsComment = false;
        for (CommunityUserPrivacyVo privacyVo : communityUserPrivacyVos) {
            if (privacyVo.getIsComment() != null && privacyVo.getIsComment()) {
                IsComment = true; // 只允许特定用户评论
                break;
            }
        }
        // 如果评论受限，则查询用户关注列表
        if (IsComment) {
            List<CommunityUserLikeVo> communityUserLikeVos = communityArticleService.selectCommunityUserLikeList(articleUserId);
            // 3. 检查评论者是否在关注列表中
            boolean isFollower = communityUserLikeVos.stream()
                    .anyMatch(like -> like.getLikeUserId().equals(userId));
            System.out.println(userId);
            // 如果不是关注者，返回失败
            if (!isFollower) {
                //return AjaxResult.error("您没有权限评论此文章，因为只允许关注的人评论您!");
                return false;
            }
        }
        return true;
    }

    /**
     *
     */


    /**
     * 判断是否是视频文件
     *
     * @param fileUrl 文件地址
     * @return 结果
     */
    public static boolean isVideoFile(String fileUrl) {
        try {
            // 打开 HTTP 连接
            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            // 获取文件类型
            String mimeType = connection.getContentType();

            // 判断是否为视频类型
            return mimeType != null && mimeType.startsWith("video");
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
