package com.example.demo.controller;

import com.example.demo.repository.UserRepository;
import com.example.demo.repository.OrderRepository;
import com.example.demo.repository.PaymentRepository;
import com.example.demo.repository.UserMembershipRepository;
import com.example.demo.repository.MembershipLevelRepository;
import com.example.demo.model.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import org.springframework.data.domain.PageRequest;

@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;

    // 获取仪表盘概览数据
    @GetMapping("/overview")
    public ResponseEntity<Map<String, Object>> getDashboardOverview() {
        try {
            Map<String, Object> overview = new HashMap<>();
            
            // 用户总数
            long totalUsers = userRepository.count();
            overview.put("totalUsers", totalUsers);
            
            // 付费用户数（有会员的用户）
            long paidUsers = userMembershipRepository.countByStatus("ACTIVE");
            overview.put("paidUsers", paidUsers);
            
            // 今日收入（今日完成的支付）
            LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
            LocalDateTime todayEnd = LocalDateTime.now().withHour(23).withMinute(59).withSecond(59);
            
            Double todayRevenue = paymentRepository.findTodayRevenue(todayStart, todayEnd);
            overview.put("todayRevenue", todayRevenue != null ? todayRevenue : 0.0);
            
            // 总订单数
            long totalOrders = orderRepository.count();
            overview.put("totalOrders", totalOrders);
            
            // 总收入
            Double totalRevenue = paymentRepository.findTotalRevenue();
            overview.put("totalRevenue", totalRevenue != null ? totalRevenue : 0.0);
            
            // 本月收入
            LocalDateTime monthStart = LocalDateTime.now().withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0);
            LocalDateTime monthEnd = LocalDateTime.now();
            
            Double monthRevenue = paymentRepository.findRevenueByDateRange(monthStart, monthEnd);
            overview.put("monthRevenue", monthRevenue != null ? monthRevenue : 0.0);
            
            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() {
        try {
            Map<String, Object> response = new HashMap<>();
            
            // 总用户数
            long totalUsers = userRepository.count();
            
            // 付费用户数
            long paidUsers = userMembershipRepository.countByStatus("ACTIVE");
            
            // 计算转化率
            double conversionRate = totalUsers > 0 ? (double) paidUsers / totalUsers * 100 : 0.0;
            
            response.put("totalUsers", totalUsers);
            response.put("paidUsers", paidUsers);
            response.put("conversionRate", Math.round(conversionRate * 100.0) / 100.0);
            
            // 按会员等级统计
            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);
        }
    }

    // 获取最近订单数据
    @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> status = new HashMap<>();
            
            // 当前在线用户（从session或redis获取）
            int onlineUsers = (int) (Math.random() * 50) + 50; // 50-100之间
            status.put("onlineUsers", onlineUsers);
            
            // 系统运行时间
            status.put("systemUptime", "48小时32分");
            
            // 数据库连接状态
            status.put("databaseStatus", "正常");
            
            // 服务状态
            status.put("serviceStatus", "运行中");
            
            return ResponseEntity.ok(status);
            
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "获取系统状态失败");
            error.put("message", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }
}