package com.luojia_channel.modules.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.luojia_channel.common.domain.page.PageResponse;
import com.luojia_channel.modules.admin.dto.*;
import com.luojia_channel.modules.admin.service.AdminService;
import com.luojia_channel.modules.post.entity.Post;
import com.luojia_channel.modules.post.entity.Comment;
import com.luojia_channel.modules.post.mapper.PostMapper;
import com.luojia_channel.modules.post.mapper.CommentMapper;
import com.luojia_channel.modules.user.entity.User;
import com.luojia_channel.modules.user.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 管理员服务实现类
 */
@Service
@RequiredArgsConstructor
public class AdminServiceImpl implements AdminService {

    private final UserMapper userMapper;
    private final PostMapper postMapper;
    private final CommentMapper commentMapper;

    @Override
    public AdminOverviewDTO getOverview() {
        AdminOverviewDTO overview = new AdminOverviewDTO();
        
        // 获取用户总数
        overview.setTotalUsers(userMapper.selectCount(null));
        
        // 获取今日新增用户数
        LocalDateTime today = LocalDate.now().atStartOfDay();
        overview.setNewUsers(userMapper.selectCount(
                new LambdaQueryWrapper<User>()
                        .ge(User::getCreateTime, today)
        ));
        
        // 获取帖子总数
        overview.setTotalPosts(postMapper.selectCount(null));
        
        // 获取今日新增帖子数
        overview.setNewPosts(postMapper.selectCount(
                new LambdaQueryWrapper<Post>()
                        .ge(Post::getCreateTime, today)
        ));
        
        // 获取评论总数
        overview.setTotalComments(commentMapper.selectCount(null));
        
        // 获取今日新增评论数
        overview.setNewComments(commentMapper.selectCount(
                new LambdaQueryWrapper<Comment>()
                        .ge(Comment::getCreateTime, today)
        ));
        
        // 获取总浏览量和今日浏览量（假设有这样的字段或方法）
        overview.setTotalViews(0L); // 实际项目中应该从数据库获取
        overview.setTodayViews(0L); // 实际项目中应该从数据库获取
        
        // 获取活跃用户排行（假设通过发帖和评论数量判断）
        List<AdminUserDTO> activeUsers = new ArrayList<>(); // 实际项目中应该从数据库联表查询
        overview.setActiveUsers(activeUsers);
        
        // 获取热门帖子排行
        List<AdminPostDTO> hotPosts = new ArrayList<>(); // 实际项目中应该从数据库联表查询
        overview.setHotPosts(hotPosts);
        
        // 用户增长趋势（最近7天）
        Map<String, Long> userGrowth = new LinkedHashMap<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");
        LocalDate end = LocalDate.now();
        LocalDate start = end.minusDays(6);
        for (LocalDate date = start; !date.isAfter(end); date = date.plusDays(1)) {
            String dateStr = date.format(formatter);
            LocalDateTime dayStart = date.atStartOfDay();
            LocalDateTime dayEnd = date.plusDays(1).atStartOfDay();
            
            Long count = userMapper.selectCount(
                    new LambdaQueryWrapper<User>()
                            .ge(User::getCreateTime, dayStart)
                            .lt(User::getCreateTime, dayEnd)
            );
            userGrowth.put(dateStr, count);
        }
        overview.setUserGrowth(userGrowth);
        
        // 帖子增长趋势（最近7天）
        Map<String, Long> postGrowth = new LinkedHashMap<>();
        for (LocalDate date = start; !date.isAfter(end); date = date.plusDays(1)) {
            String dateStr = date.format(formatter);
            LocalDateTime dayStart = date.atStartOfDay();
            LocalDateTime dayEnd = date.plusDays(1).atStartOfDay();
            
            Long count = postMapper.selectCount(
                    new LambdaQueryWrapper<Post>()
                            .ge(Post::getCreateTime, dayStart)
                            .lt(Post::getCreateTime, dayEnd)
            );
            postGrowth.put(dateStr, count);
        }
        overview.setPostGrowth(postGrowth);
        
        // 用户类型分布（按角色）
        Map<String, Long> userRoleDistribution = new HashMap<>();
        userRoleDistribution.put("普通用户", userMapper.selectCount(
                new LambdaQueryWrapper<User>().eq(User::getRole, 1)
        ));
        userRoleDistribution.put("管理员", userMapper.selectCount(
                new LambdaQueryWrapper<User>().eq(User::getRole, 2)
        ));
        userRoleDistribution.put("超级管理员", userMapper.selectCount(
                new LambdaQueryWrapper<User>().eq(User::getRole, 3)
        ));
        overview.setUserRoleDistribution(userRoleDistribution);
        
        // 帖子分类分布（实际项目中应该从分类表联查）
        Map<String, Long> postCategoryDistribution = new HashMap<>();
        overview.setPostCategoryDistribution(postCategoryDistribution);
        
        return overview;
    }

    @Override
    public PageResponse<AdminUserDTO> getUserList(Integer page, Integer size, String keyword, Integer role, Integer status) {
        Page<User> pageParam = new Page<>(page, size);
        
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        
        // 按条件筛选
        if (StringUtils.hasText(keyword)) {
            queryWrapper.like(User::getUsername, keyword);
        }
        
        if (role != null) {
            queryWrapper.eq(User::getRole, role);
        }
        
        if (status != null) {
            queryWrapper.eq(User::getStatus, status);
        }
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc(User::getCreateTime);
        
        IPage<User> userPage = userMapper.selectPage(pageParam, queryWrapper);
        
        // 转换为DTO
        List<AdminUserDTO> userDTOs = userPage.getRecords().stream().map(user -> {
            AdminUserDTO dto = new AdminUserDTO();
            BeanUtils.copyProperties(user, dto);
            
            // 获取用户的发帖数、评论数、粉丝数、关注数（实际项目中应该通过关联查询获取）
            dto.setPostCount(0);
            dto.setCommentCount(0);
            dto.setFollowerCount(0);
            dto.setFollowingCount(0);
            
            return dto;
        }).collect(Collectors.toList());
        
        return PageResponse.<AdminUserDTO>builder()
                .current((long) page)
                .size((long) size)
                .total(userPage.getTotal())
                .records(userDTOs)
                .build();
    }

    @Override
    @Transactional
    public void changeUserStatus(Long id, Integer status) {
        if (id == null || status == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        
        // 检查状态值是否合法
        if (status != 1 && status != 2) {
            throw new IllegalArgumentException("用户状态值不合法");
        }
        
        // 检查用户是否存在
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        
        // 修改状态
        user.setStatus(status);
        userMapper.updateById(user);
    }

    @Override
    @Transactional
    public void changeUserRole(Long id, Integer role) {
        if (id == null || role == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        
        // 检查角色值是否合法
        if (role < 1 || role > 3) {
            throw new IllegalArgumentException("用户角色值不合法");
        }
        
        // 检查用户是否存在
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        
        // 修改角色
        user.setRole(role);
        userMapper.updateById(user);
    }

    @Override
    public PageResponse<AdminPostDTO> getPostList(Integer page, Integer size, String keyword, Long categoryId, Integer status) {
        Page<Post> pageParam = new Page<>(page, size);
        
        LambdaQueryWrapper<Post> queryWrapper = new LambdaQueryWrapper<>();
        
        // 按条件筛选
        if (StringUtils.hasText(keyword)) {
            queryWrapper.like(Post::getTitle, keyword)
                    .or().like(Post::getContent, keyword);
        }
        
        if (categoryId != null) {
            queryWrapper.eq(Post::getCategoryId, categoryId);
        }
        
        if (status != null) {
            queryWrapper.eq(Post::getStatus, status);
        }
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc(Post::getCreateTime);
        
        IPage<Post> postPage = postMapper.selectPage(pageParam, queryWrapper);
        
        // 转换为DTO
        List<AdminPostDTO> postDTOs = postPage.getRecords().stream().map(post -> {
            AdminPostDTO dto = new AdminPostDTO();
            BeanUtils.copyProperties(post, dto);
            
            // 获取发帖用户信息（实际项目中应该通过关联查询获取）
            User user = userMapper.selectById(post.getUserId());
            if (user != null) {
                dto.setUsername(user.getUsername());
                dto.setUserAvatar(user.getAvatar());
            }
            
            // 获取分类信息（实际项目中应该通过关联查询获取）
            dto.setCategoryName("默认分类"); // 示例值，实际应从数据库获取
            
            // 获取帖子的点赞数、评论数、收藏数、浏览量（实际项目中应该通过关联查询获取）
            dto.setLikeCount(0);
            dto.setCommentCount(0);
            dto.setFavoriteCount(0);
            dto.setViewCount(0);
            
            return dto;
        }).collect(Collectors.toList());
        
        return PageResponse.<AdminPostDTO>builder()
                .current((long) page)
                .size((long) size)
                .total(postPage.getTotal())
                .records(postDTOs)
                .build();
    }

    @Override
    @Transactional
    public void deletePost(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        
        // 检查帖子是否存在
        Post post = postMapper.selectById(id);
        if (post == null) {
            throw new IllegalArgumentException("帖子不存在或已被删除");
        }
        
        // 删除帖子
        postMapper.deleteById(id);
        
        // 删除关联的评论（实际项目中应该通过关联删除）
        commentMapper.delete(new LambdaQueryWrapper<Comment>()
                .eq(Comment::getPostId, id));
    }

    @Override
    @Transactional
    public void changePostStatus(Long id, Integer action) {
        if (id == null || action == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        
        // 检查帖子是否存在
        Post post = postMapper.selectById(id);
        if (post == null) {
            throw new IllegalArgumentException("帖子不存在或已被删除");
        }
        
        // 根据操作类型修改状态
        switch (action) {
            case 1: // 置顶
                post.setStatus(1);
                break;
            case 2: // 取消置顶
                post.setStatus(0);
                break;
            case 3: // 隐藏
                post.setStatus(2);
                break;
            case 4: // 显示
                post.setStatus(0);
                break;
            default:
                throw new IllegalArgumentException("操作类型不合法");
        }
        
        postMapper.updateById(post);
    }

    @Override
    public PageResponse<AdminCommentDTO> getCommentList(Integer page, Integer size, String keyword, Long postId) {
        Page<Comment> pageParam = new Page<>(page, size);
        
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        
        // 按条件筛选
        if (StringUtils.hasText(keyword)) {
            queryWrapper.like(Comment::getContent, keyword);
        }
        
        if (postId != null) {
            queryWrapper.eq(Comment::getPostId, postId);
        }
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc(Comment::getCreateTime);
        
        IPage<Comment> commentPage = commentMapper.selectPage(pageParam, queryWrapper);
        
        // 转换为DTO
        List<AdminCommentDTO> commentDTOs = commentPage.getRecords().stream().map(comment -> {
            AdminCommentDTO dto = new AdminCommentDTO();
            BeanUtils.copyProperties(comment, dto);
            
            // 获取评论用户信息（实际项目中应该通过关联查询获取）
            User user = userMapper.selectById(comment.getUserId());
            if (user != null) {
                dto.setUsername(user.getUsername());
                dto.setUserAvatar(user.getAvatar());
            }
            
            // 获取回复用户信息（实际项目中应该通过关联查询获取）
            if (comment.getParentCommentId() != null) {
                User replyUser = userMapper.selectById(comment.getParentCommentId());
                if (replyUser != null) {
                    dto.setReplyUsername(replyUser.getUsername());
                }
            }
            
            // 获取帖子信息（实际项目中应该通过关联查询获取）
            Post post = postMapper.selectById(comment.getPostId());
            if (post != null) {
                dto.setPostTitle(post.getTitle());
            }
            
            // 获取评论的点赞数（实际项目中应该通过关联查询获取）
            dto.setLikeCount(comment.getLikeCount() != null ? comment.getLikeCount().intValue() : 0);
            
            return dto;
        }).collect(Collectors.toList());
        
        return PageResponse.<AdminCommentDTO>builder()
                .current((long) page)
                .size((long) size)
                .total(commentPage.getTotal())
                .records(commentDTOs)
                .build();
    }

    @Override
    @Transactional
    public void deleteComment(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        
        // 检查评论是否存在
        Comment comment = commentMapper.selectById(id);
        if (comment == null) {
            throw new IllegalArgumentException("评论不存在或已被删除");
        }
        
        // 删除评论
        commentMapper.deleteById(id);
        
        // 删除子评论（实际项目中应该根据具体业务逻辑决定是否删除）
        commentMapper.delete(new LambdaQueryWrapper<Comment>()
                .eq(Comment::getParentCommentId, id));
    }

    @Override
    public Map<String, Object> getUserStatistics(String type, String startDate, String endDate) {
        Map<String, Object> result = new HashMap<>();
        
        // 日期格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        
        // 默认查询最近7天
        LocalDate end = endDate != null ? LocalDate.parse(endDate, formatter) : LocalDate.now();
        LocalDate start;
        
        if (startDate != null) {
            start = LocalDate.parse(startDate, formatter);
        } else {
            switch (type) {
                case "weekly":
                    start = end.minusDays(7);
                    break;
                case "monthly":
                    start = end.minusDays(30);
                    break;
                case "daily":
                default:
                    start = end.minusDays(7);
                    break;
            }
        }
        
        // 用户注册统计
        Map<String, Long> registrations = new LinkedHashMap<>();
        for (LocalDate date = start; !date.isAfter(end); date = date.plusDays(1)) {
            String dateStr = date.format(formatter);
            LocalDateTime dayStart = date.atStartOfDay();
            LocalDateTime dayEnd = date.plusDays(1).atStartOfDay();
            
            Long count = userMapper.selectCount(
                    new LambdaQueryWrapper<User>()
                            .ge(User::getCreateTime, dayStart)
                            .lt(User::getCreateTime, dayEnd)
            );
            registrations.put(dateStr, count);
        }
        result.put("registrations", registrations);
        
        // 用户活跃度统计（实际项目中应该根据登录记录或操作记录统计）
        Map<String, Long> activeUsers = new LinkedHashMap<>();
        for (LocalDate date = start; !date.isAfter(end); date = date.plusDays(1)) {
            String dateStr = date.format(formatter);
            activeUsers.put(dateStr, 0L); // 示例值，实际应从数据库获取
        }
        result.put("activeUsers", activeUsers);
        
        return result;
    }

    @Override
    public Map<String, Object> getPostStatistics(String type, String startDate, String endDate) {
        Map<String, Object> result = new HashMap<>();
        
        // 日期格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        
        // 默认查询最近7天
        LocalDate end = endDate != null ? LocalDate.parse(endDate, formatter) : LocalDate.now();
        LocalDate start;
        
        if (startDate != null) {
            start = LocalDate.parse(startDate, formatter);
        } else {
            switch (type) {
                case "weekly":
                    start = end.minusDays(7);
                    break;
                case "monthly":
                    start = end.minusDays(30);
                    break;
                case "daily":
                default:
                    start = end.minusDays(7);
                    break;
            }
        }
        
        // 帖子发布统计
        Map<String, Long> publications = new LinkedHashMap<>();
        for (LocalDate date = start; !date.isAfter(end); date = date.plusDays(1)) {
            String dateStr = date.format(formatter);
            LocalDateTime dayStart = date.atStartOfDay();
            LocalDateTime dayEnd = date.plusDays(1).atStartOfDay();
            
            Long count = postMapper.selectCount(
                    new LambdaQueryWrapper<Post>()
                            .ge(Post::getCreateTime, dayStart)
                            .lt(Post::getCreateTime, dayEnd)
            );
            publications.put(dateStr, count);
        }
        result.put("publications", publications);
        
        // 评论统计
        Map<String, Long> comments = new LinkedHashMap<>();
        for (LocalDate date = start; !date.isAfter(end); date = date.plusDays(1)) {
            String dateStr = date.format(formatter);
            LocalDateTime dayStart = date.atStartOfDay();
            LocalDateTime dayEnd = date.plusDays(1).atStartOfDay();
            
            Long count = commentMapper.selectCount(
                    new LambdaQueryWrapper<Comment>()
                            .ge(Comment::getCreateTime, dayStart)
                            .lt(Comment::getCreateTime, dayEnd)
            );
            comments.put(dateStr, count);
        }
        result.put("comments", comments);
        
        // 点赞统计（实际项目中应该从点赞表查询）
        Map<String, Long> likes = new LinkedHashMap<>();
        for (LocalDate date = start; !date.isAfter(end); date = date.plusDays(1)) {
            String dateStr = date.format(formatter);
            likes.put(dateStr, 0L); // 示例值，实际应从数据库获取
        }
        result.put("likes", likes);
        
        return result;
    }
} 