package com.competition.modules.pub.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.competition.common.result.PageResult;
import com.competition.modules.ugc.entity.UgcWork;
import com.competition.modules.ugc.entity.UgcWorkFavorite;
import com.competition.modules.ugc.entity.UgcWorkLike;
import com.competition.modules.ugc.mapper.UgcWorkFavoriteMapper;
import com.competition.modules.ugc.mapper.UgcWorkLikeMapper;
import com.competition.modules.ugc.mapper.UgcWorkMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class PublicInteractionService {

    private final UgcWorkLikeMapper ugcWorkLikeMapper;
    private final UgcWorkFavoriteMapper ugcWorkFavoriteMapper;
    private final UgcWorkMapper ugcWorkMapper;

    /**
     * 切换点赞状态
     */
    @Transactional
    public Map<String, Object> toggleLike(Long workId, Long userId) {
        UgcWorkLike existing = ugcWorkLikeMapper.selectOne(
                new LambdaQueryWrapper<UgcWorkLike>()
                        .eq(UgcWorkLike::getWorkId, workId)
                        .eq(UgcWorkLike::getUserId, userId));

        boolean liked;
        if (existing != null) {
            ugcWorkLikeMapper.deleteById(existing.getId());
            ugcWorkMapper.update(null, new LambdaUpdateWrapper<UgcWork>()
                    .eq(UgcWork::getId, workId)
                    .setSql("like_count = GREATEST(like_count - 1, 0)"));
            liked = false;
        } else {
            UgcWorkLike like = new UgcWorkLike();
            like.setWorkId(workId);
            like.setUserId(userId);
            like.setCreateTime(LocalDateTime.now());
            ugcWorkLikeMapper.insert(like);
            ugcWorkMapper.update(null, new LambdaUpdateWrapper<UgcWork>()
                    .eq(UgcWork::getId, workId)
                    .setSql("like_count = like_count + 1"));
            liked = true;
        }

        UgcWork work = ugcWorkMapper.selectById(workId);
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("liked", liked);
        result.put("likeCount", work != null ? work.getLikeCount() : 0);
        return result;
    }

    /**
     * 切换收藏状态
     */
    @Transactional
    public Map<String, Object> toggleFavorite(Long workId, Long userId) {
        UgcWorkFavorite existing = ugcWorkFavoriteMapper.selectOne(
                new LambdaQueryWrapper<UgcWorkFavorite>()
                        .eq(UgcWorkFavorite::getWorkId, workId)
                        .eq(UgcWorkFavorite::getUserId, userId));

        boolean favorited;
        if (existing != null) {
            ugcWorkFavoriteMapper.deleteById(existing.getId());
            ugcWorkMapper.update(null, new LambdaUpdateWrapper<UgcWork>()
                    .eq(UgcWork::getId, workId)
                    .setSql("favorite_count = GREATEST(favorite_count - 1, 0)"));
            favorited = false;
        } else {
            UgcWorkFavorite fav = new UgcWorkFavorite();
            fav.setWorkId(workId);
            fav.setUserId(userId);
            fav.setCreateTime(LocalDateTime.now());
            ugcWorkFavoriteMapper.insert(fav);
            ugcWorkMapper.update(null, new LambdaUpdateWrapper<UgcWork>()
                    .eq(UgcWork::getId, workId)
                    .setSql("favorite_count = favorite_count + 1"));
            favorited = true;
        }

        UgcWork work = ugcWorkMapper.selectById(workId);
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("favorited", favorited);
        result.put("favoriteCount", work != null ? work.getFavoriteCount() : 0);
        return result;
    }

    /**
     * 获取互动状态
     */
    public Map<String, Object> getInteractionStatus(Long workId, Long userId) {
        boolean liked = ugcWorkLikeMapper.selectCount(
                new LambdaQueryWrapper<UgcWorkLike>()
                        .eq(UgcWorkLike::getWorkId, workId)
                        .eq(UgcWorkLike::getUserId, userId)) > 0;

        boolean favorited = ugcWorkFavoriteMapper.selectCount(
                new LambdaQueryWrapper<UgcWorkFavorite>()
                        .eq(UgcWorkFavorite::getWorkId, workId)
                        .eq(UgcWorkFavorite::getUserId, userId)) > 0;

        Map<String, Object> result = new LinkedHashMap<>();
        result.put("liked", liked);
        result.put("favorited", favorited);
        return result;
    }

    /**
     * 批量获取互动状态
     */
    public Map<Long, Map<String, Object>> batchGetInteractionStatus(List<Long> workIds, Long userId) {
        if (workIds == null || workIds.isEmpty()) {
            return Collections.emptyMap();
        }

        // 查询点赞
        Set<Long> likedIds = ugcWorkLikeMapper.selectList(
                new LambdaQueryWrapper<UgcWorkLike>()
                        .in(UgcWorkLike::getWorkId, workIds)
                        .eq(UgcWorkLike::getUserId, userId))
                .stream().map(UgcWorkLike::getWorkId).collect(Collectors.toSet());

        // 查询收藏
        Set<Long> favoritedIds = ugcWorkFavoriteMapper.selectList(
                new LambdaQueryWrapper<UgcWorkFavorite>()
                        .in(UgcWorkFavorite::getWorkId, workIds)
                        .eq(UgcWorkFavorite::getUserId, userId))
                .stream().map(UgcWorkFavorite::getWorkId).collect(Collectors.toSet());

        Map<Long, Map<String, Object>> result = new LinkedHashMap<>();
        for (Long workId : workIds) {
            Map<String, Object> status = new LinkedHashMap<>();
            status.put("liked", likedIds.contains(workId));
            status.put("favorited", favoritedIds.contains(workId));
            result.put(workId, status);
        }
        return result;
    }

    /**
     * 获取我的收藏（分页）
     */
    public PageResult<Map<String, Object>> getMyFavorites(Long userId, int page, int pageSize) {
        IPage<UgcWorkFavorite> favPage = ugcWorkFavoriteMapper.selectPage(
                new Page<>(page, pageSize),
                new LambdaQueryWrapper<UgcWorkFavorite>()
                        .eq(UgcWorkFavorite::getUserId, userId)
                        .orderByDesc(UgcWorkFavorite::getCreateTime));

        List<Map<String, Object>> voList = new ArrayList<>();
        for (UgcWorkFavorite fav : favPage.getRecords()) {
            UgcWork work = ugcWorkMapper.selectById(fav.getWorkId());
            if (work != null && work.getIsDeleted() == 0) {
                Map<String, Object> vo = new LinkedHashMap<>();
                vo.put("favoriteId", fav.getId());
                vo.put("favoriteTime", fav.getCreateTime());
                vo.put("workId", work.getId());
                vo.put("title", work.getTitle());
                vo.put("coverUrl", work.getCoverUrl());
                vo.put("status", work.getStatus());
                vo.put("likeCount", work.getLikeCount());
                vo.put("viewCount", work.getViewCount());
                voList.add(vo);
            }
        }
        return PageResult.from(favPage, voList);
    }
}
