package com.dora.service.impl;

import com.dora.dto.CourseLikeFavoriteDto;
import com.dora.entity.CourseLike;
import com.dora.entity.CourseFavorite;
import com.dora.mapper.CourseLikeMapper;
import com.dora.mapper.CourseFavoriteMapper;
import com.dora.service.CourseLikeFavoriteService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 课程点赞和收藏服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CourseLikeFavoriteServiceImpl implements CourseLikeFavoriteService {

    private final CourseLikeMapper courseLikeMapper;
    private final CourseFavoriteMapper courseFavoriteMapper;

    @Override
    @Transactional
    public CourseLikeFavoriteDto.LikeResponse toggleLike(Long userId, Long courseId) {
        CourseLikeFavoriteDto.LikeResponse response = new CourseLikeFavoriteDto.LikeResponse();
        
        try {
            // 检查是否存在重复的点赞记录
            int duplicateCount = courseLikeMapper.countDuplicateLikes(userId, courseId);
            if (duplicateCount > 1) {
                // 删除重复记录，保留最早的一条
                courseLikeMapper.deleteDuplicateLikes(userId, courseId);
                log.warn("发现重复的课程点赞记录，已清理 - userId: {}, courseId: {}, 重复数量: {}", 
                        userId, courseId, duplicateCount);
            }
            
            // 查询当前点赞状态（只查有效记录）
            CourseLike activeLike = courseLikeMapper.selectByUserAndCourse(userId, courseId);
            boolean isLiked = activeLike != null;
            int likeCount = 0;
            
            if (isLiked) {
                // 取消点赞
                courseLikeMapper.deleteByUserAndCourse(userId, courseId);
                response.setMessage("取消点赞成功");
                response.setIsLiked(false);
            } else {
                // 检查是否存在已删除的记录
                CourseLike existingLike = courseLikeMapper.selectByUserAndCourseIncludeDeleted(userId, courseId);
                
                if (existingLike != null) {
                    // 恢复已删除的记录
                    courseLikeMapper.restoreByUserAndCourse(userId, courseId);
                    response.setMessage("点赞成功");
                } else {
                    // 插入新记录
                    CourseLike courseLike = new CourseLike();
                    courseLike.setUserId(userId);
                    courseLike.setCourseId(courseId);
                    int insertCount = courseLikeMapper.insertIgnore(courseLike);
                    
                    if (insertCount > 0) {
                        response.setMessage("点赞成功");
                    } else {
                        // 记录已存在，可能是并发操作
                        log.warn("课程点赞记录已存在（并发操作） - userId: {}, courseId: {}", userId, courseId);
                        response.setMessage("已点赞");
                    }
                }
                response.setIsLiked(true);
            }
            
            likeCount = courseLikeMapper.countByCourseId(courseId);
            
            response.setSuccess(true);
            response.setLikeCount(likeCount);
            
            log.info("课程点赞操作 - userId: {}, courseId: {}, isLiked: {}", 
                    userId, courseId, response.getIsLiked());
                    
        } catch (Exception e) {
            log.error("课程点赞操作失败 - userId: {}, courseId: {}", 
                    userId, courseId, e);
            response.setSuccess(false);
            response.setMessage("操作失败：" + e.getMessage());
        }
        
        return response;
    }

    @Override
    @Transactional
    public CourseLikeFavoriteDto.FavoriteResponse toggleFavorite(Long userId, Long courseId) {
        CourseLikeFavoriteDto.FavoriteResponse response = new CourseLikeFavoriteDto.FavoriteResponse();
        
        try {
            // 检查是否存在重复的收藏记录
            int duplicateCount = courseFavoriteMapper.countDuplicateFavorites(userId, courseId);
            if (duplicateCount > 1) {
                // 删除重复记录，保留最早的一条
                courseFavoriteMapper.deleteDuplicateFavorites(userId, courseId);
                log.warn("发现重复的课程收藏记录，已清理 - userId: {}, courseId: {}, 重复数量: {}", 
                        userId, courseId, duplicateCount);
            }
            
            // 查询当前收藏状态（只查有效记录）
            CourseFavorite activeFavorite = courseFavoriteMapper.selectByUserAndCourse(userId, courseId);
            boolean isFavorited = activeFavorite != null;
            int favoriteCount = 0;
            
            if (isFavorited) {
                // 取消收藏
                courseFavoriteMapper.deleteByUserAndCourse(userId, courseId);
                response.setMessage("取消收藏成功");
                response.setIsFavorited(false);
            } else {
                // 检查是否存在已删除的记录
                CourseFavorite existingFavorite = courseFavoriteMapper.selectByUserAndCourseIncludeDeleted(userId, courseId);
                
                if (existingFavorite != null) {
                    // 恢复已删除的记录
                    courseFavoriteMapper.restoreByUserAndCourse(userId, courseId);
                    response.setMessage("收藏成功");
                } else {
                    // 插入新记录
                    CourseFavorite courseFavorite = new CourseFavorite();
                    courseFavorite.setUserId(userId);
                    courseFavorite.setCourseId(courseId);
                    int insertCount = courseFavoriteMapper.insertIgnore(courseFavorite);
                    
                    if (insertCount > 0) {
                        response.setMessage("收藏成功");
                    } else {
                        // 记录已存在，可能是并发操作
                        log.warn("课程收藏记录已存在（并发操作） - userId: {}, courseId: {}", userId, courseId);
                        response.setMessage("已收藏");
                    }
                }
                response.setIsFavorited(true);
            }
            
            favoriteCount = courseFavoriteMapper.countByCourseId(courseId);
            
            response.setSuccess(true);
            response.setFavoriteCount(favoriteCount);
            
            log.info("课程收藏操作 - userId: {}, courseId: {}, isFavorited: {}", 
                    userId, courseId, response.getIsFavorited());
                    
        } catch (Exception e) {
            log.error("课程收藏操作失败 - userId: {}, courseId: {}", 
                    userId, courseId, e);
            response.setSuccess(false);
            response.setMessage("操作失败：" + e.getMessage());
        }
        
        return response;
    }

    @Override
    public Boolean isLiked(Long userId, Long courseId) {
        try {
            return courseLikeMapper.selectByUserAndCourse(userId, courseId) != null;
        } catch (Exception e) {
            log.error("检查课程点赞状态失败 - userId: {}, courseId: {}", 
                    userId, courseId, e);
            return false;
        }
    }

    @Override
    public Boolean isFavorited(Long userId, Long courseId) {
        try {
            return courseFavoriteMapper.selectByUserAndCourse(userId, courseId) != null;
        } catch (Exception e) {
            log.error("检查课程收藏状态失败 - userId: {}, courseId: {}", 
                    userId, courseId, e);
            return false;
        }
    }

    @Override
    public Integer getLikeCount(Long courseId) {
        try {
            return courseLikeMapper.countByCourseId(courseId);
        } catch (Exception e) {
            log.error("获取课程点赞数量失败 - courseId: {}", courseId, e);
            return 0;
        }
    }

    @Override
    public Integer getFavoriteCount(Long courseId) {
        try {
            return courseFavoriteMapper.countByCourseId(courseId);
        } catch (Exception e) {
            log.error("获取课程收藏数量失败 - courseId: {}", courseId, e);
            return 0;
        }
    }

    @Override
    public CourseLikeFavoriteDto.CourseStatusResponse getCourseStatus(Long userId, Long courseId) {
        CourseLikeFavoriteDto.CourseStatusResponse response = new CourseLikeFavoriteDto.CourseStatusResponse();
        
        try {
            boolean isLiked = userId != null ? isLiked(userId, courseId) : false;
            boolean isFavorited = userId != null ? isFavorited(userId, courseId) : false;
            int likeCount = getLikeCount(courseId);
            int favoriteCount = getFavoriteCount(courseId);
            
            response.setSuccess(true);
            response.setMessage("查询成功");
            response.setIsLiked(isLiked);
            response.setIsFavorited(isFavorited);
            response.setLikeCount(likeCount);
            response.setFavoriteCount(favoriteCount);
            
        } catch (Exception e) {
            log.error("获取课程状态失败 - userId: {}, courseId: {}", userId, courseId, e);
            response.setSuccess(false);
            response.setMessage("查询失败：" + e.getMessage());
        }
        
        return response;
    }

    @Override
    public CourseLikeFavoriteDto.CourseListResponse getUserLikedCourses(Long userId, Integer page, Integer size) {
        CourseLikeFavoriteDto.CourseListResponse response = new CourseLikeFavoriteDto.CourseListResponse();
        
        try {
            int offset = (page - 1) * size;
            List<CourseLikeFavoriteDto.CourseRecord> records = new ArrayList<>();
            
            // 获取用户点赞的课程列表
            List<CourseLikeMapper.CourseLikeWithInfo> courseLikesWithInfo = 
                courseLikeMapper.selectByUserIdWithCourseInfo(userId, offset, size);
            
            for (CourseLikeMapper.CourseLikeWithInfo likeWithInfo : courseLikesWithInfo) {
                CourseLikeFavoriteDto.CourseRecord record = new CourseLikeFavoriteDto.CourseRecord();
                record.setId(likeWithInfo.getId());
                record.setCourseId(likeWithInfo.getCourseId());
                record.setCourseTitle(likeWithInfo.getCourseTitle());
                record.setCourseDescription(likeWithInfo.getCourseDescription());
                record.setCoverUrl(likeWithInfo.getCoverUrl());
                record.setPrice(likeWithInfo.getPrice());
                record.setIsFree(likeWithInfo.getIsFree() != null && likeWithInfo.getIsFree() == 1);
                record.setLevel(likeWithInfo.getLevel());
                record.setLevelName(getRoleNameByLevel(likeWithInfo.getLevel()));
                record.setCategory(likeWithInfo.getCategory());
                record.setCreatorUsername(likeWithInfo.getCreatorUsername());
                record.setCreateTime(likeWithInfo.getCreateTime());
                records.add(record);
            }
            
            int total = courseLikeMapper.countByUserId(userId);
            
            response.setSuccess(true);
            response.setMessage("获取成功");
            response.setRecords(records);
            response.setTotal(total);
            response.setPage(page);
            response.setSize(size);
            
            log.info("获取用户点赞课程列表成功 - userId: {}, 记录数: {}, 总数: {}", 
                    userId, records.size(), total);
            
        } catch (Exception e) {
            log.error("获取用户点赞课程列表失败 - userId: {}", userId, e);
            response.setSuccess(false);
            response.setMessage("获取失败：" + e.getMessage());
        }
        
        return response;
    }

    @Override
    public CourseLikeFavoriteDto.CourseListResponse getUserFavoritedCourses(Long userId, Integer page, Integer size) {
        CourseLikeFavoriteDto.CourseListResponse response = new CourseLikeFavoriteDto.CourseListResponse();
        
        try {
            int offset = (page - 1) * size;
            List<CourseLikeFavoriteDto.CourseRecord> records = new ArrayList<>();
            
            // 获取用户收藏的课程列表
            List<CourseFavoriteMapper.CourseFavoriteWithInfo> courseFavoritesWithInfo = 
                courseFavoriteMapper.selectByUserIdWithCourseInfo(userId, offset, size);
            
            for (CourseFavoriteMapper.CourseFavoriteWithInfo favoriteWithInfo : courseFavoritesWithInfo) {
                CourseLikeFavoriteDto.CourseRecord record = new CourseLikeFavoriteDto.CourseRecord();
                record.setId(favoriteWithInfo.getId());
                record.setCourseId(favoriteWithInfo.getCourseId());
                record.setCourseTitle(favoriteWithInfo.getCourseTitle());
                record.setCourseDescription(favoriteWithInfo.getCourseDescription());
                record.setCoverUrl(favoriteWithInfo.getCoverUrl());
                record.setPrice(favoriteWithInfo.getPrice());
                record.setIsFree(favoriteWithInfo.getIsFree() != null && favoriteWithInfo.getIsFree() == 1);
                record.setLevel(favoriteWithInfo.getLevel());
                record.setLevelName(getRoleNameByLevel(favoriteWithInfo.getLevel()));
                record.setCategory(favoriteWithInfo.getCategory());
                record.setCreatorUsername(favoriteWithInfo.getCreatorUsername());
                record.setCreateTime(favoriteWithInfo.getCreateTime());
                records.add(record);
            }
            
            int total = courseFavoriteMapper.countByUserId(userId);
            
            response.setSuccess(true);
            response.setMessage("获取成功");
            response.setRecords(records);
            response.setTotal(total);
            response.setPage(page);
            response.setSize(size);
            
            log.info("获取用户收藏课程列表成功 - userId: {}, 记录数: {}, 总数: {}", 
                    userId, records.size(), total);
            
        } catch (Exception e) {
            log.error("获取用户收藏课程列表失败 - userId: {}", userId, e);
            response.setSuccess(false);
            response.setMessage("获取失败：" + e.getMessage());
        }
        
        return response;
    }

    @Override
    public CourseLikeFavoriteDto.CourseStatsResponse getUserStats(Long userId) {
        CourseLikeFavoriteDto.CourseStatsResponse response = new CourseLikeFavoriteDto.CourseStatsResponse();
        
        try {
            int likedCourseCount = courseLikeMapper.countByUserId(userId);
            int favoritedCourseCount = courseFavoriteMapper.countByUserId(userId);
            
            response.setSuccess(true);
            response.setMessage("获取成功");
            response.setLikedCourseCount(likedCourseCount);
            response.setFavoritedCourseCount(favoritedCourseCount);
            
        } catch (Exception e) {
            log.error("获取用户课程统计失败 - userId: {}", userId, e);
            response.setSuccess(false);
            response.setMessage("获取失败：" + e.getMessage());
        }
        
        return response;
    }

    /**
     * 根据级别获取角色名称
     */
    private String getRoleNameByLevel(Integer level) {
        if (level == null || level <= 0) {
            return "游客";
        } else if (level == 1) {
            return "普通用户";
        } else if (level == 2) {
            return "VIP用户";
        } else {
            return "SVIP用户";
        }
    }
}