package com.xindazhou.business.service.community.collect;

import com.xindazhou.business.controller.app.community.collect.vo.CollectPageReqVO;
import com.xindazhou.business.controller.app.community.post.vo.PostRespVO;
import com.xindazhou.business.convert.community.post.PostConvert;
import com.xindazhou.business.dal.community.dataobject.collect.CollectDO;
import com.xindazhou.business.dal.community.dataobject.post.PostDO;
import com.xindazhou.business.dal.community.mysql.collect.CollectMapper;
import com.xindazhou.business.dal.community.mysql.post.CommunityPostMapper;
import com.xindazhou.framework.common.pojo.PageResult;
import com.xindazhou.framework.security.core.util.SecurityFrameworkUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.xindazhou.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.xindazhou.framework.common.exception.enums.GlobalErrorCodeConstants.NOT_FOUND;

/**
 * 收藏 Service 实现类
 *
 * @author xindazhou
 */
@Service("communityCollectServiceImpl")
@Slf4j
@Validated
public class CollectServiceImpl implements CollectService {

    @Resource
    private CollectMapper collectMapper;

    @Resource
    private CommunityPostMapper communityPostMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean toggleCollect(Long postId) {
        // 校验帖子存在
        PostDO post = communityPostMapper.selectById(postId);
        if (post == null) {
            throw exception(NOT_FOUND, "帖子不存在");
        }

        // 获取当前登录用户
        Long userId = SecurityFrameworkUtils.getLoginUserId();

        // 查询是否已收藏
        CollectDO existingCollect = collectMapper.selectByUserIdAndPostId(userId, postId);

        if (existingCollect != null) {
            // 已收藏，取消收藏
            collectMapper.deleteById(existingCollect.getId());
            decrementCollectCount(postId);
            return false;
        } else {
            // 未收藏，执行收藏
            CollectDO collect = new CollectDO();
            collect.setUserId(userId);
            collect.setPostId(postId);
            collect.setCreateTime(LocalDateTime.now());
            collectMapper.insert(collect);
            incrementCollectCount(postId);
            return true;
        }
    }

    @Override
    public Boolean isCollected(Long postId) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        if (userId == null) {
            return false;
        }
        CollectDO collect = collectMapper.selectByUserIdAndPostId(userId, postId);
        return collect != null;
    }

    @Override
    public PageResult<PostRespVO> getCollectPage(CollectPageReqVO reqVO) {
        // 设置当前用户ID
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        reqVO.setUserId(userId);

        // 查询收藏列表
        PageResult<CollectDO> pageResult = collectMapper.selectPage(reqVO);

        // 提取帖子ID列表
        List<Long> postIds = pageResult.getList().stream()
                .map(CollectDO::getPostId)
                .collect(Collectors.toList());

        if (postIds.isEmpty()) {
            return new PageResult<>(new ArrayList<>(), pageResult.getTotal());
        }

        // 查询帖子列表
        List<PostDO> posts = communityPostMapper.selectBatchIds(postIds);
        List<PostRespVO> postVOs = PostConvert.INSTANCE.convertList(posts);

        // 填充用户信息和状态
        // 注意：这里需要调用PostService的方法来填充完整信息
        // 为了简化，这里直接返回基本信息，实际使用时可以调用PostService.getPostPage

        return new PageResult<>(postVOs, pageResult.getTotal());
    }

    /**
     * 增加收藏数
     */
    private void incrementCollectCount(Long postId) {
        PostDO post = communityPostMapper.selectById(postId);
        if (post != null) {
            post.setCollectCount(post.getCollectCount() + 1);
            communityPostMapper.updateById(post);
        }
    }

    /**
     * 减少收藏数
     */
    private void decrementCollectCount(Long postId) {
        PostDO post = communityPostMapper.selectById(postId);
        if (post != null && post.getCollectCount() > 0) {
            post.setCollectCount(post.getCollectCount() - 1);
            communityPostMapper.updateById(post);
        }
    }

}

