package com.example.demo.service;

import com.example.demo.model.Order;
import com.example.demo.model.OrderStatus;
import com.example.demo.model.Payment;
import com.example.demo.model.PaymentStatus;
import com.example.demo.repository.OrderRepository;
import com.example.demo.repository.PaymentRepository;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class DashboardService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private PaymentRepository paymentRepository;

    /**
     * 获取仪表盘概览数据
     */
    public Map<String, Object> getDashboardOverview() {
        Map<String, Object> overview = new HashMap<>();

        // 用户总数
        long totalUsers = userRepository.count();
        overview.put("totalUsers", totalUsers);

        // 付费用户数（有成功支付记录的不同用户数）
        long payingUsers = paymentRepository.findAll().stream()
                .filter(payment -> payment.getStatus() == PaymentStatus.SUCCESS)
                .map(payment -> payment.getUser().getId())
                .distinct()
                .count();
        overview.put("payingUsers", payingUsers);

        // 今日收入（今日成功支付的金额）
        LocalDateTime todayStart = LocalDate.now().atStartOfDay();
        LocalDateTime todayEnd = LocalDate.now().atTime(23, 59, 59);
        
        List<Payment> todayPayments = paymentRepository.findAll().stream()
                .filter(payment -> payment.getStatus() == PaymentStatus.SUCCESS)
                .filter(payment -> payment.getPaidAt() != null && 
                        payment.getPaidAt().isAfter(todayStart) && 
                        payment.getPaidAt().isBefore(todayEnd))
                .toList();
        
        BigDecimal todayRevenue = todayPayments.stream()
                .map(Payment::getAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        overview.put("todayRevenue", todayRevenue);

        // 转化率（付费用户数 / 总用户数）
        double conversionRate = totalUsers > 0 ? (double) payingUsers / totalUsers * 100 : 0;
        overview.put("conversionRate", Math.round(conversionRate * 100.0) / 100.0);

        // 今日新增用户
        long todayNewUsers = userRepository.findAll().stream()
                .filter(user -> user.getCreatedAt() != null && 
                        user.getCreatedAt().isAfter(todayStart) && 
                        user.getCreatedAt().isBefore(todayEnd))
                .count();
        overview.put("todayNewUsers", todayNewUsers);

        return overview;
    }

    /**
     * 获取日活数据（最近30天）
     */
    public Map<String, Object> getDailyActiveUsers() {
        Map<String, Object> result = new HashMap<>();
        
        List<Map<String, Object>> dailyData = new ArrayList<>();
        LocalDate endDate = LocalDate.now();
        
        for (int i = 29; i >= 0; i--) {
            LocalDate date = endDate.minusDays(i);
            LocalDateTime startOfDay = date.atStartOfDay();
            LocalDateTime endOfDay = date.atTime(23, 59, 59);
            
            // 统计当天有订单的用户数作为日活
            long dailyActiveUsers = orderRepository.findAll().stream()
                    .filter(order -> order.getCreatedAt() != null &&
                            order.getCreatedAt().isAfter(startOfDay) &&
                            order.getCreatedAt().isBefore(endOfDay))
                    .map(Order::getUser)
                    .distinct()
                    .count();
            
            Map<String, Object> dayData = new HashMap<>();
            dayData.put("date", date.format(DateTimeFormatter.ofPattern("MM-dd")));
            dayData.put("activeUsers", dailyActiveUsers);
            dailyData.add(dayData);
        }
        
        result.put("dailyData", dailyData);
        return result;
    }

    /**
     * 获取收入趋势数据（最近30天）
     */
    public Map<String, Object> getRevenueTrend() {
        Map<String, Object> result = new HashMap<>();
        
        List<Map<String, Object>> revenueData = new ArrayList<>();
        LocalDate endDate = LocalDate.now();
        
        for (int i = 29; i >= 0; i--) {
            LocalDate date = endDate.minusDays(i);
            LocalDateTime startOfDay = date.atStartOfDay();
            LocalDateTime endOfDay = date.atTime(23, 59, 59);
            
            // 统计当天成功支付的金额
            BigDecimal dailyRevenue = paymentRepository.findAll().stream()
                    .filter(payment -> payment.getStatus() == PaymentStatus.SUCCESS)
                    .filter(payment -> payment.getPaidAt() != null &&
                            payment.getPaidAt().isAfter(startOfDay) &&
                            payment.getPaidAt().isBefore(endOfDay))
                    .map(Payment::getAmount)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            
            Map<String, Object> dayData = new HashMap<>();
            dayData.put("date", date.format(DateTimeFormatter.ofPattern("MM-dd")));
            dayData.put("revenue", dailyRevenue);
            revenueData.add(dayData);
        }
        
        result.put("revenueData", revenueData);
        return result;
    }

    /**
     * 获取订单状态分布
     */
    public Map<String, Object> getOrderStatusDistribution() {
        Map<String, Object> result = new HashMap<>();
        
        List<Map<String, Object>> statusData = new ArrayList<>();
        for (OrderStatus status : OrderStatus.values()) {
            long count = orderRepository.countByStatus(status);
            Map<String, Object> statusInfo = new HashMap<>();
            statusInfo.put("status", status.name());
            statusInfo.put("count", count);
            statusData.add(statusInfo);
        }
        
        result.put("statusData", statusData);
        return result;
    }

    /**
     * 获取支付方式分布
     */
    public Map<String, Object> getPaymentMethodDistribution() {
        Map<String, Object> result = new HashMap<>();
        
        List<Map<String, Object>> methodData = new ArrayList<>();
        // 这里需要根据PaymentMethod枚举来统计，暂时简化处理
        Map<String, Long> methodCounts = new HashMap<>();
        
        paymentRepository.findAll().forEach(payment -> {
            String method = payment.getPaymentMethod().name();
            methodCounts.put(method, methodCounts.getOrDefault(method, 0L) + 1);
        });
        
        methodCounts.forEach((method, count) -> {
            Map<String, Object> methodInfo = new HashMap<>();
            methodInfo.put("method", method);
            methodInfo.put("count", count);
            methodData.add(methodInfo);
        });
        
        result.put("methodData", methodData);
        return result;
    }

    /**
     * 获取最近订单列表
     */
    public Map<String, Object> getRecentOrders() {
        Map<String, Object> result = new HashMap<>();
        
        List<Order> recentOrders = orderRepository.findAll().stream()
                .sorted((o1, o2) -> o2.getCreatedAt().compareTo(o1.getCreatedAt()))
                .limit(10)
                .toList();
        
        List<Map<String, Object>> orderList = new ArrayList<>();
        recentOrders.forEach(order -> {
            Map<String, Object> orderInfo = new HashMap<>();
            orderInfo.put("id", order.getId());
            orderInfo.put("orderNumber", order.getOrderNumber());
            orderInfo.put("totalAmount", order.getTotalAmount());
            orderInfo.put("status", order.getStatus().name());
            orderInfo.put("createdAt", order.getCreatedAt());
            orderInfo.put("username", order.getUser().getUsername());
            orderList.add(orderInfo);
        });
        
        result.put("orders", orderList);
        return result;
    }
}
