package com.emotion.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.emotion.dto.request.AiConfigCallStatsRequest;
import com.emotion.dto.response.AiConfigCallStatsResponse;
import com.emotion.dto.response.AiConfigCallStatsItem;
import com.emotion.dto.response.DashboardStatsResponse;
import com.emotion.entity.*;
import com.emotion.mapper.AiConfigMapper;
import com.emotion.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.management.ManagementFactory;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 仪表盘服务实现类
 * 
 * @author system
 * @date 2025-10-31
 */
@Slf4j
@Service
public class DashboardServiceImpl implements DashboardService {

    @Autowired
    private UserService userService;

    @Autowired
    private GuestUserService guestUserService;

    @Autowired
    private ConversationService conversationService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private DiaryPostService diaryPostService;

    @Autowired
    private CommunityPostService communityPostService;

    @Autowired
    private EmotionRecordService emotionRecordService;

    @Autowired
    private CozeApiCallService cozeApiCallService;

    @Autowired
    private AiConfigService aiConfigService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private AiConfigMapper aiConfigMapper;

    @Autowired
    private AchievementService achievementService;

    @Autowired
    private RewardService rewardService;

    @Override
    public DashboardStatsResponse getDashboardStats() {
        log.info("获取仪表盘统计数据");

        try {
            return DashboardStatsResponse.builder()
                    .userStats(getUserStats())
                    .contentStats(getContentStats())
                    .aiServiceStats(getAiServiceStats())
                    .systemStats(getSystemStats())
                    .recentActivities(getRecentActivities())
                    .userGrowthTrends(getUserGrowthTrends(7))
                    .recentLogins(getRecentLogins(10))
                    .updateTime(LocalDateTime.now())
                    .build();
        } catch (Exception e) {
            log.error("获取仪表盘统计数据失败", e);
            // 返回默认数据，避免前端报错
            return getDefaultDashboardStats();
        }
    }

    @Override
    public DashboardStatsResponse.UserStats getUserStats() {
        try {
            // 获取用户统计数据
            Long totalUsers = userService.count(new LambdaQueryWrapper<User>()
                    .eq(User::getIsDeleted, 0));
            
            Long guestUsers = guestUserService.count(new LambdaQueryWrapper<GuestUser>()
                    .eq(GuestUser::getIsDeleted, 0));
            
            // 获取今日新增用户
            LocalDateTime todayStart = LocalDate.now().atStartOfDay();
            LocalDateTime todayEnd = todayStart.plusDays(1);
            Long todayNewUsers = userService.count(new LambdaQueryWrapper<User>()
                    .eq(User::getIsDeleted, 0)
                    .ge(User::getCreateTime, todayStart)
                    .lt(User::getCreateTime, todayEnd));
            
            // 活跃用户数（最近7天有活动的用户）
            LocalDateTime sevenDaysAgo = LocalDateTime.now().minusDays(7);
            Long activeUsers = userService.count(new LambdaQueryWrapper<User>()
                    .eq(User::getIsDeleted, 0)
                    .ge(User::getLastActiveTime, sevenDaysAgo));

            return DashboardStatsResponse.UserStats.builder()
                    .totalUsers(totalUsers)
                    .todayNewUsers(todayNewUsers)
                    .activeUsers(activeUsers)
                    .guestUsers(guestUsers)
                    .build();
        } catch (Exception e) {
            log.error("获取用户统计数据失败", e);
            return DashboardStatsResponse.UserStats.builder()
                    .totalUsers(0L)
                    .todayNewUsers(0L)
                    .activeUsers(0L)
                    .guestUsers(0L)
                    .build();
        }
    }

    @Override
    public DashboardStatsResponse.ContentStats getContentStats() {
        try {
            Long totalConversations = conversationService.count(new LambdaQueryWrapper<Conversation>()
                    .eq(Conversation::getIsDeleted, 0));
            
            Long totalMessages = messageService.count(new LambdaQueryWrapper<Message>()
                    .eq(Message::getIsDeleted, 0));
            
            Long diaryPosts = diaryPostService.count(new LambdaQueryWrapper<DiaryPost>()
                    .eq(DiaryPost::getIsDeleted, 0));
            
            Long communityPosts = communityPostService.count(new LambdaQueryWrapper<CommunityPost>()
                    .eq(CommunityPost::getIsDeleted, 0));
            
            Long emotionRecords = emotionRecordService.count(new LambdaQueryWrapper<EmotionRecord>()
                    .eq(EmotionRecord::getIsDeleted, 0));

            return DashboardStatsResponse.ContentStats.builder()
                    .totalConversations(totalConversations)
                    .totalMessages(totalMessages)
                    .diaryPosts(diaryPosts)
                    .communityPosts(communityPosts)
                    .emotionRecords(emotionRecords)
                    .build();
        } catch (Exception e) {
            log.error("获取内容统计数据失败", e);
            return DashboardStatsResponse.ContentStats.builder()
                    .totalConversations(0L)
                    .totalMessages(0L)
                    .diaryPosts(0L)
                    .communityPosts(0L)
                    .emotionRecords(0L)
                    .build();
        }
    }

    @Override
    public DashboardStatsResponse.AiServiceStats getAiServiceStats() {
        try {
            Long totalApiCalls = cozeApiCallService.count(new LambdaQueryWrapper<CozeApiCall>()
                    .eq(CozeApiCall::getIsDeleted, 0));
            
            Long aiConfigCount = aiConfigService.count(new LambdaQueryWrapper<AiConfig>()
                    .eq(AiConfig::getIsDeleted, 0));
            
            // 获取今日API调用次数
            LocalDateTime todayStart = LocalDate.now().atStartOfDay();
            LocalDateTime todayEnd = todayStart.plusDays(1);
            Long todayApiCalls = cozeApiCallService.count(new LambdaQueryWrapper<CozeApiCall>()
                    .eq(CozeApiCall::getIsDeleted, 0)
                    .ge(CozeApiCall::getCreateTime, todayStart)
                    .lt(CozeApiCall::getCreateTime, todayEnd));
            
            // 获取成功和失败的调用次数
            Long successfulCalls = cozeApiCallService.count(new LambdaQueryWrapper<CozeApiCall>()
                    .eq(CozeApiCall::getIsDeleted, 0)
                    .eq(CozeApiCall::getStatus, "success"));
            
            Long failedCalls = cozeApiCallService.count(new LambdaQueryWrapper<CozeApiCall>()
                    .eq(CozeApiCall::getIsDeleted, 0)
                    .eq(CozeApiCall::getStatus, "failed"));
            
            // 计算平均响应时间（从duration_ms字段）
            List<CozeApiCall> apiCalls = cozeApiCallService.list(new LambdaQueryWrapper<CozeApiCall>()
                    .eq(CozeApiCall::getIsDeleted, 0)
                    .isNotNull(CozeApiCall::getDurationMs)
                    .last("LIMIT 1000")); // 取最近1000条记录计算平均值
            
            Double avgResponseTime = apiCalls.stream()
                    .filter(call -> call.getDurationMs() != null)
                    .mapToInt(CozeApiCall::getDurationMs)
                    .average()
                    .orElse(0.0);

            return DashboardStatsResponse.AiServiceStats.builder()
                    .totalApiCalls(totalApiCalls)
                    .todayApiCalls(todayApiCalls)
                    .successfulCalls(successfulCalls)
                    .failedCalls(failedCalls)
                    .avgResponseTime(avgResponseTime)
                    .aiConfigCount(aiConfigCount)
                    .build();
        } catch (Exception e) {
            log.error("获取AI服务统计数据失败", e);
            return DashboardStatsResponse.AiServiceStats.builder()
                    .totalApiCalls(0L)
                    .todayApiCalls(0L)
                    .successfulCalls(0L)
                    .failedCalls(0L)
                    .avgResponseTime(0.0)
                    .aiConfigCount(0L)
                    .build();
        }
    }

    @Override
    public DashboardStatsResponse.SystemStats getSystemStats() {
        try {
            Long adminCount = adminService.count(new LambdaQueryWrapper<Admin>()
                    .eq(Admin::getIsDeleted, 0)
                    .eq(Admin::getStatus, 1)); // 只统计正常状态的管理员
            
            Long achievementCount = achievementService.count(new LambdaQueryWrapper<Achievement>()
                    .eq(Achievement::getIsDeleted, 0));
            
            Long rewardCount = rewardService.count(new LambdaQueryWrapper<Reward>()
                    .eq(Reward::getIsDeleted, 0));
            
            // 获取系统运行时间
            long uptimeMs = ManagementFactory.getRuntimeMXBean().getUptime();
            String uptime = formatUptime(uptimeMs);

            return DashboardStatsResponse.SystemStats.builder()
                    .adminCount(adminCount)
                    .achievementCount(achievementCount)
                    .rewardCount(rewardCount)
                    .uptime(uptime)
                    .build();
        } catch (Exception e) {
            log.error("获取系统统计数据失败", e);
            return DashboardStatsResponse.SystemStats.builder()
                    .adminCount(0L)
                    .achievementCount(0L)
                    .rewardCount(0L)
                    .uptime("未知")
                    .build();
        }
    }

    /**
     * 获取最近活动
     */
    private List<DashboardStatsResponse.RecentActivity> getRecentActivities() {
        List<DashboardStatsResponse.RecentActivity> activities = new ArrayList<>();
        
        try {
            // 获取最近注册的用户
            List<User> recentUsers = userService.list(new LambdaQueryWrapper<User>()
                    .eq(User::getIsDeleted, 0)
                    .orderByDesc(User::getCreateTime)
                    .last("LIMIT 3"));
            
            for (User user : recentUsers) {
                activities.add(DashboardStatsResponse.RecentActivity.builder()
                        .type("user_register")
                        .description("新用户注册: " + (user.getNickname() != null ? user.getNickname() : user.getUsername()))
                        .userId(user.getId())
                        .username(user.getNickname() != null ? user.getNickname() : user.getUsername())
                        .activityTime(user.getCreateTime())
                        .extraData(new HashMap<>())
                        .build());
            }
            
            // 获取最近的对话
            List<Conversation> recentConversations = conversationService.list(new LambdaQueryWrapper<Conversation>()
                    .eq(Conversation::getIsDeleted, 0)
                    .orderByDesc(Conversation::getCreateTime)
                    .last("LIMIT 3"));
            
            for (Conversation conversation : recentConversations) {
                Map<String, Object> extraData = new HashMap<>();
                extraData.put("conversationId", conversation.getId());
                extraData.put("title", conversation.getTitle());
                
                activities.add(DashboardStatsResponse.RecentActivity.builder()
                        .type("ai_chat")
                        .description("新的AI对话: " + (conversation.getTitle() != null ? conversation.getTitle() : "未命名对话"))
                        .userId(conversation.getUserId())
                        .username("用户")
                        .activityTime(conversation.getCreateTime())
                        .extraData(extraData)
                        .build());
            }
            
            // 获取最近的日记帖子
            List<DiaryPost> recentDiaryPosts = diaryPostService.list(new LambdaQueryWrapper<DiaryPost>()
                    .eq(DiaryPost::getIsDeleted, 0)
                    .orderByDesc(DiaryPost::getCreateTime)
                    .last("LIMIT 2"));
            
            for (DiaryPost post : recentDiaryPosts) {
                Map<String, Object> extraData = new HashMap<>();
                extraData.put("postId", post.getId());
                extraData.put("title", post.getTitle());
                
                activities.add(DashboardStatsResponse.RecentActivity.builder()
                        .type("diary_post")
                        .description("新的日记: " + (post.getTitle() != null ? post.getTitle() : "无标题"))
                        .userId(post.getUserId())
                        .username("用户")
                        .activityTime(post.getCreateTime())
                        .extraData(extraData)
                        .build());
            }
            
            // 按时间排序，取最新的10条
            activities.sort((a, b) -> b.getActivityTime().compareTo(a.getActivityTime()));
            if (activities.size() > 10) {
                activities = activities.subList(0, 10);
            }
                    
        } catch (Exception e) {
            log.error("获取最近活动失败", e);
        }
        
        return activities;
    }

    /**
     * 格式化运行时间
     */
    private String formatUptime(long uptimeMs) {
        long seconds = uptimeMs / 1000;
        long minutes = seconds / 60;
        long hours = minutes / 60;
        long days = hours / 24;

        if (days > 0) {
            return String.format("%d天%d小时%d分钟", days, hours % 24, minutes % 60);
        } else if (hours > 0) {
            return String.format("%d小时%d分钟", hours, minutes % 60);
        } else if (minutes > 0) {
            return String.format("%d分钟", minutes);
        } else {
            return String.format("%d秒", seconds);
        }
    }

    /**
     * 获取默认仪表盘统计数据（用于异常情况）
     */
    private DashboardStatsResponse getDefaultDashboardStats() {
        return DashboardStatsResponse.builder()
                .userStats(DashboardStatsResponse.UserStats.builder()
                        .totalUsers(0L)
                        .todayNewUsers(0L)
                        .activeUsers(0L)
                        .guestUsers(0L)
                        .build())
                .contentStats(DashboardStatsResponse.ContentStats.builder()
                        .totalConversations(0L)
                        .totalMessages(0L)
                        .diaryPosts(0L)
                        .communityPosts(0L)
                        .emotionRecords(0L)
                        .build())
                .aiServiceStats(DashboardStatsResponse.AiServiceStats.builder()
                        .totalApiCalls(0L)
                        .todayApiCalls(0L)
                        .successfulCalls(0L)
                        .failedCalls(0L)
                        .avgResponseTime(0.0)
                        .aiConfigCount(0L)
                        .build())
                .systemStats(DashboardStatsResponse.SystemStats.builder()
                        .adminCount(0L)
                        .achievementCount(0L)
                        .rewardCount(0L)
                        .uptime("未知")
                        .build())
                .recentActivities(new ArrayList<>())
                .userGrowthTrends(new ArrayList<>())
                .recentLogins(new ArrayList<>())
                .updateTime(LocalDateTime.now())
                .build();
    }

    @Override
    public List<DashboardStatsResponse.UserGrowthTrend> getUserGrowthTrends(int days) {
        List<DashboardStatsResponse.UserGrowthTrend> trends = new ArrayList<>();
        
        try {
            LocalDate endDate = LocalDate.now();
            LocalDate startDate = endDate.minusDays(days - 1);
            
            // 获取指定日期范围内每天的用户注册数据
            for (int i = 0; i < days; i++) {
                LocalDate currentDate = startDate.plusDays(i);
                LocalDateTime dayStart = currentDate.atStartOfDay();
                LocalDateTime dayEnd = dayStart.plusDays(1);
                
                // 统计当天新增用户数
                Long newUsers = userService.count(new LambdaQueryWrapper<User>()
                        .eq(User::getIsDeleted, 0)
                        .ge(User::getCreateTime, dayStart)
                        .lt(User::getCreateTime, dayEnd));
                
                // 统计截止到当天的总用户数
                Long totalUsers = userService.count(new LambdaQueryWrapper<User>()
                        .eq(User::getIsDeleted, 0)
                        .lt(User::getCreateTime, dayEnd));
                
                trends.add(DashboardStatsResponse.UserGrowthTrend.builder()
                        .date(currentDate.toString())
                        .newUsers(newUsers)
                        .totalUsers(totalUsers)
                        .build());
            }
            
        } catch (Exception e) {
            log.error("获取用户增长趋势数据失败", e);
        }
        
        return trends;
    }

    @Override
    public List<DashboardStatsResponse.RecentLogin> getRecentLogins(int limit) {
        List<DashboardStatsResponse.RecentLogin> recentLogins = new ArrayList<>();
        
        try {
            // 获取最近活跃的用户（按最后活跃时间排序）
            List<User> recentUsers = userService.list(new LambdaQueryWrapper<User>()
                    .eq(User::getIsDeleted, 0)
                    .isNotNull(User::getLastActiveTime)
                    .orderByDesc(User::getLastActiveTime)
                    .last("LIMIT " + limit));
            
            for (User user : recentUsers) {
                String timeDescription = formatTimeDescription(user.getLastActiveTime());
                
                recentLogins.add(DashboardStatsResponse.RecentLogin.builder()
                        .userId(user.getId())
                        .username(user.getUsername())
                        .nickname(user.getNickname())
                        .avatar(user.getAvatar())
                        .loginTime(user.getLastActiveTime())
                        .timeDescription(timeDescription)
                        .build());
            }
            
        } catch (Exception e) {
            log.error("获取最近登录用户失败", e);
        }
        
        return recentLogins;
    }

    @Override
    public AiConfigCallStatsResponse getAiConfigCallStats(AiConfigCallStatsRequest request) {
        Integer limit = request != null ? request.getLimit() : null;
        if (limit == null) {
            limit = 20;
        }
        // 防御性限制，避免过大查询
        if (limit > 200) {
            limit = 200;
        }
        if (limit < 1) {
            limit = 1;
        }

        List<AiConfigCallStatsItem> items = aiConfigMapper.selectAiConfigCallStats(limit);
        return AiConfigCallStatsResponse.builder()
                .items(items)
                .build();
    }

    /**
     * 格式化时间描述
     */
    private String formatTimeDescription(LocalDateTime dateTime) {
        if (dateTime == null) {
            return "未知";
        }
        
        LocalDateTime now = LocalDateTime.now();
        long minutes = java.time.Duration.between(dateTime, now).toMinutes();
        
        if (minutes < 1) {
            return "刚刚";
        } else if (minutes < 60) {
            return minutes + "分钟前";
        } else if (minutes < 1440) { // 24小时
            long hours = minutes / 60;
            return hours + "小时前";
        } else {
            long days = minutes / 1440;
            if (days == 1) {
                return "昨天";
            } else if (days < 7) {
                return days + "天前";
            } else {
                return dateTime.toLocalDate().toString();
            }
        }
    }
}