package com.example.demo.controller;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.model.Order;
import com.example.demo.repository.MembershipLevelRepository;
import com.example.demo.repository.OrderRepository;
import com.example.demo.repository.PaymentRepository;
import com.example.demo.repository.UserMembershipRepository;
import com.example.demo.repository.UserRepository;
import com.example.demo.service.DashboardService;

@RestController
@RequestMapping("/api/dashboard")
@CrossOrigin(origins = "*")
public class DashboardApiController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private PaymentRepository paymentRepository;

    @Autowired
    private UserMembershipRepository userMembershipRepository;

    @Autowired
    private MembershipLevelRepository membershipLevelRepository;

    @Autowired
    private com.example.demo.service.UserService userService;
    
    @Autowired
    private DashboardService dashboardService;

    // 获取仪表盘概览数据
    @GetMapping("/overview")
    public ResponseEntity<Map<String, Object>> getDashboardOverview() {
        try {
            // 使用 DashboardService 获取包含同比变化的完整数据
            Map<String, Object> overview = dashboardService.getDashboardOverview();
            return ResponseEntity.ok(overview);
            
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "获取仪表盘数据失败");
            error.put("message", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }

    // 获取月度收入趋势数据
    @GetMapping("/monthly-revenue")
    public ResponseEntity<Map<String, Object>> getMonthlyRevenue(@RequestParam(defaultValue = "2024") String year) {
        try {
            Map<String, Object> response = new HashMap<>();
            
            // 获取指定年份的月度收入数据
            List<Map<String, Object>> monthlyData = paymentRepository.findMonthlyRevenueByYear(Integer.parseInt(year));
            
            // 确保12个月都有数据
            List<Map<String, Object>> completeData = new ArrayList<>();
            for (int month = 1; month <= 12; month++) {
                final int currentMonth = month;
                Optional<Map<String, Object>> monthData = monthlyData.stream()
                    .filter(data -> {
                        Object monthObj = data.get("month");
                        if (monthObj instanceof Number) {
                            return ((Number) monthObj).intValue() == currentMonth;
                        }
                        return false;
                    })
                    .findFirst();
                
                if (monthData.isPresent()) {
                    completeData.add(monthData.get());
                } else {
                    Map<String, Object> emptyMonth = new HashMap<>();
                    emptyMonth.put("month", currentMonth);
                    emptyMonth.put("revenue", 0.0);
                    emptyMonth.put("orderCount", 0);
                    completeData.add(emptyMonth);
                }
            }
            
            response.put("monthlyData", completeData);
            response.put("year", year);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "获取月度收入数据失败");
            error.put("message", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }

    // 获取用户转化率数据
    @GetMapping("/conversion-rate")
    public ResponseEntity<Map<String, Object>> getConversionRate(@RequestParam(required = false) String year) {
        try {
            Map<String, Object> response = new HashMap<>();
            
            // 当月新增用户数
            LocalDate today = LocalDate.now();
            LocalDateTime currentMonthStart = LocalDateTime.of(today.getYear(), today.getMonthValue(), 1, 0, 0, 0);
            LocalDateTime currentMonthEnd = currentMonthStart.plusMonths(1).minusSeconds(1);
            
            long newUsers = userRepository.countByCreatedAtBetween(currentMonthStart, currentMonthEnd);
            
            // 当月付费用户数（当月内产生成功支付的去重用户）
            long paidUsers = paymentRepository.countDistinctUsersByStatusAndPaidAtBetween(
                    com.example.demo.model.PaymentStatus.SUCCESS, currentMonthStart, currentMonthEnd);
            
            // 当月付费转化率 = 当月付费用户数 / 当月新增用户数
            double conversionRate = newUsers > 0 ? (double) paidUsers / newUsers * 100 : 0.0;
            
            response.put("totalUsers", newUsers);
            response.put("paidUsers", paidUsers);
            response.put("conversionRate", Math.round(conversionRate * 100.0) / 100.0);
            
            // 如果指定了年份，返回按月转化率数据
            if (year != null && !year.isEmpty()) {
                List<Map<String, Object>> monthlyConversion = getMonthlyConversionRate(Integer.parseInt(year));
                response.put("monthlyData", monthlyConversion);
            }
            
            // 按会员等级统计
            List<Map<String, Object>> membershipStats = membershipLevelRepository.findMembershipStats();
            response.put("membershipStats", membershipStats);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "获取转化率数据失败");
            error.put("message", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }
    
    // 获取按月转化率数据（当月转化率：当月付费用户数 / 当月新增用户数）
    // 只计算到当前月份，未来月份不显示
    private List<Map<String, Object>> getMonthlyConversionRate(int year) {
        List<Map<String, Object>> monthlyData = new ArrayList<>();
        
        // 获取当前年月
        LocalDate now = LocalDate.now();
        int currentYear = now.getYear();
        int currentMonth = now.getMonthValue();
        
        // 确定要计算到哪个月份
        int maxMonth;
        if (year < currentYear) {
            maxMonth = 12;
        } else if (year == currentYear) {
            maxMonth = currentMonth;
        } else {
            return monthlyData;
        }
        
        for (int month = 1; month <= maxMonth; month++) {
            Map<String, Object> monthData = new HashMap<>();
            monthData.put("month", month);
            
            LocalDateTime monthStart = LocalDateTime.of(year, month, 1, 0, 0, 0);
            LocalDateTime monthEnd = monthStart.plusMonths(1).minusSeconds(1);
            
            // 当月新增用户数
            long monthNewUsers = userRepository.countByCreatedAtBetween(monthStart, monthEnd);
            
            // 当月付费用户数（当月内产生成功支付的去重用户）
            long monthPaidUsers = paymentRepository.countDistinctUsersByStatusAndPaidAtBetween(
                    com.example.demo.model.PaymentStatus.SUCCESS, monthStart, monthEnd);
            
            // 当月转化率
            double monthConversionRate = monthNewUsers > 0 ? (double) monthPaidUsers / monthNewUsers * 100 : 0.0;
            
            monthData.put("totalUsers", monthNewUsers);
            monthData.put("paidUsers", monthPaidUsers);
            monthData.put("conversionRate", Math.round(monthConversionRate * 100.0) / 100.0);
            
            monthlyData.add(monthData);
        }
        
        return monthlyData;
    }

    // 获取最近订单数据
    @GetMapping("/recent-orders")
    public ResponseEntity<Map<String, Object>> getRecentOrders(@RequestParam(defaultValue = "10") int limit) {
        try {
            Map<String, Object> response = new HashMap<>();
            
            // 获取最近的订单
            List<Order> recentOrdersList = orderRepository.findRecentOrders(PageRequest.of(0, limit));
            List<Map<String, Object>> recentOrders = recentOrdersList.stream()
                .map(order -> {
                    Map<String, Object> orderMap = new HashMap<>();
                    orderMap.put("id", order.getId());
                    orderMap.put("orderNumber", order.getOrderNumber());
                    orderMap.put("totalAmount", order.getTotalAmount());
                    orderMap.put("status", order.getStatus());
                    orderMap.put("orderType", order.getOrderType());
                    orderMap.put("description", order.getDescription());
                    orderMap.put("createdAt", order.getCreatedAt());
                    orderMap.put("username", order.getUser() != null ? order.getUser().getUsername() : "未知用户");
                    return orderMap;
                })
                .collect(Collectors.toList());
            response.put("recentOrders", recentOrders);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "获取最近订单失败");
            error.put("message", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }

    // 获取系统状态
    @GetMapping("/system-status")
    public ResponseEntity<Map<String, Object>> getSystemStatus() {
        try {
            Map<String, Object> response = new HashMap<>();
            Map<String, Object> data = new HashMap<>();
            
            // 当前在线用户（基于最近10分钟内有活动的用户）
            long onlineUsers = userService.countOnlineUsers();
            data.put("onlineUsers", onlineUsers);
            data.put("maxUsers", 500);
            
            // 系统运行时间（从JVM启动时间计算）
            long uptimeMillis = java.lang.management.ManagementFactory.getRuntimeMXBean().getUptime();
            long uptimeSeconds = uptimeMillis / 1000;
            data.put("uptime", uptimeSeconds);
            
            // 格式化的运行时间
            long hours = uptimeSeconds / 3600;
            long minutes = (uptimeSeconds % 3600) / 60;
            data.put("uptimeFormatted", hours + "小时" + minutes + "分");
            
            // 数据库连接状态
            data.put("databaseStatus", "正常");
            
            // 服务状态
            data.put("serviceStatus", "运行中");
            
            response.put("success", true);
            response.put("data", data);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("error", "获取系统状态失败");
            error.put("message", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }
}