package com.tangguo.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tangguo.common.exception.ServiceException;
import com.tangguo.common.mauth.MobileTokenHelper;
import com.tangguo.domain.BbsMoment;
import com.tangguo.domain.BbsMomentAttachment;
import com.tangguo.domain.BbsMomentComment;
import com.tangguo.domain.BbsMomentVoteOption;
import com.tangguo.domain.bo.CommentMomentBO;
import com.tangguo.domain.bo.CreateMomentBO;
import com.tangguo.domain.bo.LikeMomentBO;
import com.tangguo.domain.bo.VoteMomentBO;
import com.tangguo.domain.vo.*;
import com.tangguo.enums.*;
import com.tangguo.mapper.BbsMomentMapper;
import com.tangguo.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StopWatch;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * 动态Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-01
 */
@Slf4j
@Service
public class BbsMomentServiceImpl extends ServiceImpl<BbsMomentMapper, BbsMoment> implements IBbsMomentService {

    @Resource
    private BbsMomentMapper bbsMomentMapper;

    @Resource
    private IBbsMomentAttachmentService attachmentsService;

    @Resource
    private IBbsMomentVoteOptionService voteOptionService;

    @Resource
    private IBbsMomentCommentService commentService;

    @Resource
    private IBbsMomentLikeService likeService;

    @Resource
    private IBbsMomentVoteService voteService;


    /**
     * 查询动态列表
     *
     * @param moment 动态
     * @return 动态
     */
    @Override
    public List<BbsMoment> selectBbsMomentList(BbsMoment moment) {
	    return this.baseMapper.selectBbsMomentList(moment);
    }


    /**
     * 删除动态
     *
     * @param id 动态Id
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteMoment(Long id) {
        this.removeById(id);
    }


    /**
     * 查询用户动态统计
     *
     * @return 动态统计
     */
    @Override
    public BbsUserMomentCountVO getUserMomentCount(String userName) {
        return this.baseMapper.selectUserMomentCount(userName);
    }


    /**
     * 查询动态列表
     *
     * @param userName 用户名
     * @param content  动态内容
     * @return 动态列表
     */
    @Override
    public List<BbsMomentListVO> getUserMoments(String userName, String content) {
        List<BbsMomentListVO> dbMoments = this.baseMapper.selectUserMoments(userName, content);
        this.fillMoment(dbMoments);
        return dbMoments;
    }


    /**
     * 查询动态列表
     *
     * @param userName 用户名
     * @param content  动态内容
     * @return 动态列表
     */
    @Override
    public List<BbsMomentListVO> getMoments(String userName, String content) {
        List<BbsMomentListVO> dbMoments = this.baseMapper.selectMoments(userName, content);
        this.fillMoment(dbMoments);
        return dbMoments;
    }


    /**
     * 查询动态详情
     *
     * @param momentId 动态Id
     * @param userName 用户名
     * @return 动态列表
     */
    @Override
    public BbsMomentListVO getMoment(Long momentId, String userName) {
        BbsMomentListVO dbMoment = this.baseMapper.selectMoment(momentId, userName);
        this.fillMoment(Collections.singletonList(dbMoment));
        dbMoment.setComments(null);
        return dbMoment;
    }


    /**
     * 创建动态
     *
     * @param bo 动态
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void userCreateMoment(CreateMomentBO bo) {
        // 添加动态
        String username = MobileTokenHelper.getUserName();
        BbsMoment newMoment = this.buildMoment(bo);
        newMoment.setUserName(username);
        this.save(newMoment);

        // 添加动态附件
        MomentType momentType = MomentType.getMomentType(bo.getType());
        if (MomentType.IMAGE == momentType || MomentType.VIDEO == momentType) {
            this.attachmentsService.addAttachments(newMoment, bo.getAttachments());
        }

        // 添加动态投票选项
        if (EnableStatus.QY.getStatus() == bo.getIsEnableVote()) {
            List<CreateMomentBO.VoteOption> voteOptions = bo.getVoteOptions();
            this.voteOptionService.addVoteOptions(newMoment, voteOptions);
        }
    }


    /**
     * 删除动态
     *
     * @param momentId 动态Id
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void userDeleteMoment(Long momentId) {
        String username = MobileTokenHelper.getUserName();
        BbsMoment dbMoment = this.getOne(
            Wrappers.lambdaQuery(BbsMoment.class)
                .select(BbsMoment::getId).eq(BbsMoment::getUserName, username).eq(BbsMoment::getId, momentId)
        );
        if (Objects.isNull(dbMoment)) {
            throw new ServiceException("删除失败，未查询到当前动态数据。");
        }

        this.removeById(dbMoment.getId());
    }


    /**
     * 点赞动态
     *
     * @param bo 动态
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void userLikeMoment(LikeMomentBO bo) {
        BbsMoment dbMoment = this.getById(bo.getMomentId());
        if (Objects.isNull(dbMoment)) {
            throw new ServiceException("点赞失败，未查询到当前动态数据。");
        }

        String userName = MobileTokenHelper.getUserName();
        long likeStatus = this.likeService.getUserMomentLikeCount(dbMoment.getId(), userName);
        int likeCount = dbMoment.getLikeCount();

        if (LikeStatus.LIKE.getStatus() == bo.getLikeStatus()) {
            if (likeStatus > 0) {
                throw new ServiceException("点赞失败，已对当前动态点赞。");
            } else {
                this.likeService.addMomentLike(dbMoment.getId(), userName);
                likeCount++;
            }
        } else {
            if (likeStatus < 1) {
                throw new ServiceException("取消失败，没有对当前动态点赞。");
            } else {
                this.likeService.deleteMomentLike(dbMoment.getId(), userName);
                likeCount--;
            }
        }

        // 更新动态点赞人数
        BbsMoment updMoment = new BbsMoment();
        updMoment.setId(dbMoment.getId());
        updMoment.setLikeCount(likeCount);
        this.updateById(updMoment);
    }


    /**
     * 投票动态
     *
     * @param bo 动态
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void userVoteMoment(VoteMomentBO bo) {
        BbsMoment dbMoment = this.getById(bo.getMomentId());
        if (Objects.isNull(dbMoment)) {
            throw new ServiceException("投票失败，未查询到当前动态数据。");
        }
        if (EnableStatus.QY.getStatus() != dbMoment.getIsEnableVote()) {
            throw new ServiceException("投票失败，当前动态未开启投票。");
        }

        String username = MobileTokenHelper.getUserName();
        long voteCount = this.voteService.getUserMomentVoteCount(dbMoment.getId(), username);
        if (voteCount > 0) {
            throw new ServiceException("投票失败，已对当前动态投票。");
        }

        String optionCode = bo.getOptionCode();
        BbsMomentVoteOption dbOption = this.voteOptionService.getVoteOption(dbMoment.getId(), optionCode);
        if (Objects.isNull(dbOption)) {
            throw new ServiceException("投票失败，未查询到当前投票选项数据。");
        }

        // 添加投票记录
        this.voteService.addMomentVoteCount(dbMoment.getId(), username, optionCode);

        // 更新投票选项投票人数
        BbsMomentVoteOption updOption = new BbsMomentVoteOption();
        updOption.setId(dbOption.getId());
        updOption.setVoteCount(dbOption.getVoteCount() + 1);
        this.voteOptionService.updateById(updOption);

        // 更新动态投票人数
        BbsMoment updMoment = new BbsMoment();
        updMoment.setId(dbMoment.getId());
        updMoment.setVoteCount(dbMoment.getVoteCount() + 1);
        this.updateById(updMoment);
    }


    /**
     * 评论动态
     *
     * @param bo 动态
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void userCommentMoment(CommentMomentBO bo) {
        BbsMoment dbMoment = this.getById(bo.getMomentId());
        if (Objects.isNull(dbMoment)) {
            throw new ServiceException("评论失败，未查询到当前动态数据。");
        }
        if (EnableStatus.QY.getStatus() != dbMoment.getIsEnableComment()) {
            throw new ServiceException("评论失败，当前动态未开启评论。");
        }

        BbsMomentComment dbParentComment = null;
        if (Objects.nonNull(bo.getParentId())) {
            dbParentComment = this.commentService.getById(bo.getParentId());
            if (Objects.isNull(dbParentComment)) {
                throw new ServiceException("回复失败，未查询到回复的评论数据");
            }
        }

        // 添加动态评论
        BbsMomentComment newComment = new BbsMomentComment();
        newComment.setMomentId(dbMoment.getId());
        newComment.setUserName(MobileTokenHelper.getUserName());
        newComment.setNikeName(MobileTokenHelper.getNikeName());
        newComment.setContent(bo.getContent());
        newComment.setStatus(CommentStatus.ZC.getStatus());
        newComment.setIsFeatured(1);
        this.commentService.save(newComment);

        // 更新动态评论
        BbsMomentComment updComment = new BbsMomentComment();
        updComment.setId(newComment.getId());
        if (Objects.nonNull(dbParentComment)) {
            updComment.setParentId(dbParentComment.getId());
            updComment.setReplyNikeName(dbParentComment.getNikeName());
            updComment.setAncestorPath(dbParentComment.getAncestorPath() + "," + newComment.getId());
        } else {
            updComment.setAncestorPath(String.valueOf(newComment.getId()));
        }
        this.commentService.updateById(updComment);

        // 更新动态评论人数
        BbsMoment updMoment = new BbsMoment();
        updMoment.setId(dbMoment.getId());
        updMoment.setCommentCount(dbMoment.getCommentCount() + 1);
        this.updateById(updMoment);
    }


    /**
     * 构建动态实体
     *
     * @param bo 动态
     * @return 动态实体
     */
    private BbsMoment buildMoment(CreateMomentBO bo) {
        // 动态类型
        MomentType momentType = MomentType.getMomentType(bo.getType());
        if (Objects.isNull(momentType)) {
            throw new ServiceException("发布失败，动态类型错误。");
        }

        // 动态附件
        BbsMoment newMoment = new BbsMoment();
        List<CreateMomentBO.Attachment> attachments = bo.getAttachments();
        String linkUrl = bo.getLinkUrl();
        if (MomentType.TEXT == momentType) {
            if (StrUtil.isBlank(bo.getContent())) {
                throw new ServiceException("发布失败，动态内容不能为空。");
            }
        }
        else if (MomentType.IMAGE == momentType || MomentType.VIDEO == momentType) {
            if (CollUtil.isEmpty(attachments)) {
                throw new ServiceException("发布失败，动态附件不能为空。");
            }
        }
        else if (MomentType.URL == momentType) {
            if (StrUtil.isBlank(linkUrl)) {
                throw new ServiceException("发布失败，动态链接不能为空。");
            }
        }

        newMoment.setType(momentType.name());
        newMoment.setContent(bo.getContent());
        newMoment.setLinkUrl(linkUrl);
        newMoment.setIsEnableComment(bo.getIsEnableComment());
        newMoment.setIsEnableFeaturedComment(bo.getIsEnableFeaturedComment());

        // 动态主题
        List<String> topicNames = bo.getTopicNames();
        List<String> topicIds = bo.getTopicIds();
        if (CollUtil.isNotEmpty(topicNames) && CollUtil.isNotEmpty(topicIds)) {
            newMoment.setTopicIds(String.join(",", topicIds));
            newMoment.setTopicNames(String.join(",", topicNames));
        }

        // 动态投票
        Integer isEnableVote = bo.getIsEnableVote();
        newMoment.setIsEnableVote(isEnableVote);
        if (EnableStatus.QY.getStatus() == isEnableVote) {
            newMoment.setVoteTitle(bo.getVoteTitle());
            VoteOptionType optionType = VoteOptionType.getVoteOptionType(bo.getVoteOptionType());
            if (Objects.isNull(optionType)) {
                throw new ServiceException("发布失败，动态投票选项类型错误。");
            }

            newMoment.setVoteOptionType(optionType.name());
            List<CreateMomentBO.VoteOption> options = bo.getVoteOptions();
            if (CollUtil.isEmpty(options)) {
                throw new ServiceException("发布失败，动态投票选项不能为空。");
            }

            for (CreateMomentBO.VoteOption option : options) {
                long optionCount = options.stream()
                    .filter(o -> o.getName().equals(option.getName())).count();
                if (optionCount > 1) {
                    throw new ServiceException("发布失败，动态投票选项重复。");
                }
            }
        }
        return newMoment;
    }


    /**
     * 填充动态附件、投票选项和评论
     *
     * @param moments 动态
     */
    private void fillMoment(List<BbsMomentListVO> moments) {
        log.info("=> 填充动态附件、投票选项和评论");
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        List<Long> momentIds = moments.stream().map(BbsMomentListVO::getId).collect(Collectors.toList());
        if (CollUtil.isEmpty(momentIds)) {
            return;
        }

        try {
            // 查询动态附件
            CompletableFuture<Map<Long, List<BbsMomentAttachment>>> af = CompletableFuture.supplyAsync(() -> {
                List<BbsMomentAttachment> atts = this.attachmentsService.getAttachments(momentIds);
                return atts.stream().collect(Collectors.groupingBy(BbsMomentAttachment::getMomentId));
            });

            // 查询动态投票选项
            CompletableFuture<Map<Long, List<BbsMomentVoteOption>>> of = CompletableFuture.supplyAsync(() -> {
                List<BbsMomentVoteOption> opts = this.voteOptionService.getVoteOptions(momentIds);
                return opts.stream().collect(Collectors.groupingBy(BbsMomentVoteOption::getMomentId));
            });

            // 查询动态评论
            CompletableFuture<Map<Long, List<BbsMomentComment>>> cf = CompletableFuture.supplyAsync(() -> {
                List<BbsMomentComment> opts = this.commentService.getComments(momentIds);
                return opts.stream().collect(Collectors.groupingBy(BbsMomentComment::getMomentId));
            });

            // 等待全部任务处理完毕
            CompletableFuture.allOf(af, of, cf).join();
            Map<Long, List<BbsMomentAttachment>> attsMap = af.join();
            Map<Long, List<BbsMomentVoteOption>> optsMap = of.join();
            Map<Long, List<BbsMomentComment>> comsMap = cf.join();

            for (BbsMomentListVO moment : moments) {
                // 填充动态附件
                List<BbsMomentAttachment> as = attsMap.get(moment.getId());
                if (CollUtil.isNotEmpty(as)) {
                    List<BbsAttachmentVO> avs = new ArrayList<>(as.size());
                    for (BbsMomentAttachment a : as) {
                        BbsAttachmentVO av = new BbsAttachmentVO();
                        av.setId(a.getId());
                        av.setName(a.getName());
                        av.setUrl(a.getUrl());
                        avs.add(av);
                    }
                    moment.setAttachments(avs);
                }

                // 填充动态投票选项
                List<BbsMomentVoteOption> os = optsMap.get(moment.getId());
                if (CollUtil.isNotEmpty(os)) {
                    List<BbsVoteOptionVO> ovs = new ArrayList<>(os.size());
                    for (BbsMomentVoteOption o : os) {
                        BbsVoteOptionVO ov = new BbsVoteOptionVO();
                        ov.setId(o.getId());
                        ov.setType(o.getType());
                        ov.setName(o.getName());
                        ov.setCode(o.getCode());
                        ov.setImageUrl(o.getImageUrl());
                        ov.setSort(o.getSort());
                        ov.setVoteCount(o.getVoteCount());
                        ovs.add(ov);
                    }
                    moment.setVoteOptions(ovs);
                }

                // 填充动态评论
                List<BbsMomentComment> cs = comsMap.get(moment.getId());
                if (CollUtil.isNotEmpty(cs)) {
                    List<BbsCommentVO> cvs = new ArrayList<>(cs.size());
                    for (BbsMomentComment c : cs) {
                        BbsCommentVO cv = new BbsCommentVO();
                        cv.setId(c.getId());
                        cv.setCreateTime(c.getCreateTime());
                        cv.setNikeName(c.getNikeName());
                        cv.setUserName(c.getUserName());
                        cv.setContent(c.getContent());
                        cvs.add(cv);
                    }
                    moment.setComments(cvs);
                }
            }

        } catch (Exception e) {
            log.error("=> 填充动态附件和投票选项失败：", e);
        }

        stopWatch.stop();
        long millis = stopWatch.getLastTaskTimeMillis();
        log.info("=> 填充动态附件、投票选项和评论完毕，耗时：{} 毫秒", millis);
    }

}
