package com.dora.service.impl;

import com.dora.dto.AdminPaymentUserDto;
import com.dora.dto.ApiResponse;
import com.dora.mapper.AdminPaymentUserMapper;
import com.dora.service.AdminPaymentUserService;
import com.dora.util.AdminSecurityUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * 管理端支付用户统计服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdminPaymentUserServiceImpl implements AdminPaymentUserService {

    private static final String DATE_FORMAT = "yyyy-MM-dd";
    private final AdminPaymentUserMapper adminPaymentUserMapper;

    @Override
    public ApiResponse<AdminPaymentUserDto.PaymentUserStatisticsResponse> getPaymentUserStatistics(
            AdminPaymentUserDto.PaymentUserStatisticsRequest request) {
        try {
            // 验证管理员权限
            Long adminId = AdminSecurityUtil.getCurrentAdminId();
            log.info("管理员 {} 查询支付用户统计数据", adminId);

            // 处理时间参数
            LocalDateTime startDate = null;
            LocalDateTime endDate = null;

            if (StringUtils.hasText(request.getStartDate())) {
                startDate = LocalDate.parse(request.getStartDate(), DateTimeFormatter.ofPattern(DATE_FORMAT))
                        .atStartOfDay();
            }

            if (StringUtils.hasText(request.getEndDate())) {
                endDate = LocalDate.parse(request.getEndDate(), DateTimeFormatter.ofPattern(DATE_FORMAT))
                        .plusDays(1).atStartOfDay(); // 结束日期包含当天，所以加1天
            }

            // 构建响应对象
            AdminPaymentUserDto.PaymentUserStatisticsResponse response = 
                    new AdminPaymentUserDto.PaymentUserStatisticsResponse();

            // 1. 获取支付概览统计
            AdminPaymentUserDto.PaymentOverview overview = adminPaymentUserMapper.selectPaymentOverview(startDate, endDate);
            response.setOverview(overview);

            // 2. 获取支付用户列表（默认显示前20个，按最近支付时间排序）
            List<AdminPaymentUserDto.PaymentUserInfo> paymentUsers = adminPaymentUserMapper.selectPaymentUserList(
                    startDate, endDate, null, null, null, null, "lastPaidAt", "DESC", 0, 20);
            response.setPaymentUsers(paymentUsers);

            // 3. 获取支付金额分布统计
            List<Map<String, Object>> amountRanges = adminPaymentUserMapper.selectAmountDistribution(startDate, endDate);
            AdminPaymentUserDto.AmountDistributionStats amountDistribution = buildAmountDistributionStats(amountRanges);
            response.setAmountDistribution(amountDistribution);

            // 4. 获取每日支付统计
            List<AdminPaymentUserDto.DailyPaymentStats> dailyStats = 
                    adminPaymentUserMapper.selectDailyPaymentStats(startDate, endDate);
            response.setDailyStats(dailyStats);

            log.info("支付用户统计查询成功，支付用户数: {}, 订单数: {}", 
                    overview.getTotalPaymentUsers(), overview.getTotalPaymentOrders());

            return ApiResponse.success(response);
        } catch (Exception e) {
            log.error("查询支付用户统计数据失败", e);
            return ApiResponse.error(500, "查询支付用户统计数据失败: " + e.getMessage());
        }
    }

    @Override
    public ApiResponse<AdminPaymentUserDto.PaymentUserListResponse> getPaymentUserList(
            AdminPaymentUserDto.PaymentUserListRequest request) {
        try {
            // 验证管理员权限
            Long adminId = AdminSecurityUtil.getCurrentAdminId();
            log.info("管理员 {} 查询支付用户列表", adminId);

            // 处理时间参数
            LocalDateTime startDate = null;
            LocalDateTime endDate = null;

            if (StringUtils.hasText(request.getStartDate())) {
                startDate = LocalDate.parse(request.getStartDate(), DateTimeFormatter.ofPattern(DATE_FORMAT))
                        .atStartOfDay();
            }

            if (StringUtils.hasText(request.getEndDate())) {
                endDate = LocalDate.parse(request.getEndDate(), DateTimeFormatter.ofPattern(DATE_FORMAT))
                        .plusDays(1).atStartOfDay();
            }

            // 处理分页参数
            int page = request.getPage() != null ? request.getPage() : 1;
            int size = request.getSize() != null ? request.getSize() : 10;
            int offset = (page - 1) * size;

            // 处理排序参数
            String sortField = StringUtils.hasText(request.getSortField()) ? request.getSortField() : "lastPaidAt";
            String sortOrder = StringUtils.hasText(request.getSortOrder()) ? request.getSortOrder() : "DESC";

            // 查询支付用户列表
            List<AdminPaymentUserDto.PaymentUserInfo> users = adminPaymentUserMapper.selectPaymentUserList(
                    startDate, endDate, request.getRole(), request.getOnlyRepeatUsers(),
                    request.getMinAmount(), request.getMaxAmount(), sortField, sortOrder, offset, size);

            // 查询总数
            Long total = adminPaymentUserMapper.countPaymentUserList(
                    startDate, endDate, request.getRole(), request.getOnlyRepeatUsers(),
                    request.getMinAmount(), request.getMaxAmount());

            // 构建响应
            AdminPaymentUserDto.PaymentUserListResponse response = new AdminPaymentUserDto.PaymentUserListResponse();
            response.setUsers(users);
            response.setTotal(total);
            response.setCurrentPage(page);
            response.setPageSize(size);
            response.setTotalPages((int) Math.ceil((double) total / size));

            log.info("支付用户列表查询成功，总数: {}, 当前页: {}", total, page);

            return ApiResponse.success(response);
        } catch (Exception e) {
            log.error("查询支付用户列表失败", e);
            return ApiResponse.error(500, "查询支付用户列表失败: " + e.getMessage());
        }
    }

    /**
     * 构建支付金额分布统计
     */
    private AdminPaymentUserDto.AmountDistributionStats buildAmountDistributionStats(List<Map<String, Object>> amountRanges) {
        AdminPaymentUserDto.AmountDistributionStats amountDistributionStats = 
                new AdminPaymentUserDto.AmountDistributionStats();

        // 初始化为0
        amountDistributionStats.setUsers0To50(0L);
        amountDistributionStats.setUsers50To100(0L);
        amountDistributionStats.setUsers100To200(0L);
        amountDistributionStats.setUsers200To500(0L);
        amountDistributionStats.setUsersAbove500(0L);

        // 填充数据
        for (Map<String, Object> item : amountRanges) {
            String rangeName = (String) item.get("rangeName");
            Long userCount = ((Number) item.get("userCount")).longValue();

            switch (rangeName) {
                case "0-50元":
                    amountDistributionStats.setUsers0To50(userCount);
                    break;
                case "50-100元":
                    amountDistributionStats.setUsers50To100(userCount);
                    break;
                case "100-200元":
                    amountDistributionStats.setUsers100To200(userCount);
                    break;
                case "200-500元":
                    amountDistributionStats.setUsers200To500(userCount);
                    break;
                case "500元以上":
                    amountDistributionStats.setUsersAbove500(userCount);
                    break;
                default:
                    log.warn("未知的金额区间: {}", rangeName);
                    break;
            }
        }

        return amountDistributionStats;
    }
}
