package com.erp.tenant.service.tenant.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.tenant.dto.tenant.DashboardResponse;
import com.erp.tenant.dto.tenant.DashboardResponse.OrderListItem;
import com.erp.tenant.entity.order.Order;
import com.erp.tenant.dto.report.AlertDTO;
import com.erp.tenant.entity.report.ReportSummary;
import com.erp.tenant.repository.order.OrderRepository;
import com.erp.tenant.repository.stock.StockRepository;
import com.erp.tenant.service.tenant.TenantDashboardService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 租户Dashboard服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TenantDashboardServiceImpl implements TenantDashboardService {

    private final OrderRepository orderRepository;
    private final StockRepository stockRepository;

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @Override
    public DashboardResponse getDashboard(Long tenantId, Integer recentDays) {
        int days = recentDays != null ? recentDays : 7;
        LocalDate today = LocalDate.now();
        String monthStart = today.withDayOfMonth(1).format(DATE_FORMATTER) + " 00:00:00";
        String monthEnd = today.format(DATE_FORMATTER) + " 23:59:59";
        String recentStart = today.minusDays(days).format(DATE_FORMATTER) + " 00:00:00";
        String recentEnd = today.format(DATE_FORMATTER) + " 23:59:59";

        // 本月订单统计
        OrderRepository.OrderStats monthOrderStats = orderRepository.getMonthOrderStats(tenantId, monthStart, monthEnd);

        // 构建摘要
        ReportSummary summary = ReportSummary.builder()
                .monthOrdersTotal(monthOrderStats.totalOrders != null ? monthOrderStats.totalOrders : 0L)
                .monthOrdersCompleted(monthOrderStats.completedOrders != null ? monthOrderStats.completedOrders : 0L)
                .monthOrdersCancelled(monthOrderStats.cancelledOrders != null ? monthOrderStats.cancelledOrders : 0L)
                .monthOrdersAmount(monthOrderStats.totalAmount != null ? new BigDecimal(monthOrderStats.totalAmount.doubleValue()) : BigDecimal.ZERO)
                .apiSuccessRate(BigDecimal.valueOf(calcRate(100L, 95L))) // TODO: pull record stats
                .build();

        // 近期订单
        List<Order> recentOrders = orderRepository.findRecentOrders(tenantId, recentStart, recentEnd, 20);
        List<OrderListItem> recentOrderItems = recentOrders.stream()
                .map(this::toOrderListItem)
                .collect(Collectors.toList());

        // 预警列表
        List<AlertDTO> alerts = buildAlerts(tenantId);

        return DashboardResponse.builder()
                .summary(summary)
                .alerts(alerts)
                .recentOrders(recentOrderItems)
                .build();
    }

    @Override
    public List<AlertDTO> buildAlerts(Long tenantId) {
        List<AlertDTO> alerts = new ArrayList<>();

        // 库存预警
        Long lowStockCount = stockRepository.countLowStock(tenantId, null);
        Long outOfStockCount = stockRepository.countOutOfStock(tenantId, null);
        int globalThreshold = 10;

        if (outOfStockCount != null && outOfStockCount > 0) {
            alerts.add(AlertDTO.builder()
                    .type("stock_critical")
                    .level("critical")
                    .title("库存严重不足")
                    .message("有 " + outOfStockCount + " 个商品库存为0")
                    .count(outOfStockCount.intValue())
                    .build());
        }

        if (lowStockCount != null && lowStockCount > 0) {
            alerts.add(AlertDTO.builder()
                    .type("stock_warning")
                    .level("warning")
                    .title("库存预警")
                    .message("有 " + lowStockCount + " 个商品库存低于预警阈值")
                    .count(lowStockCount.intValue())
                    .build());
        }

        return alerts;
    }

    @Override
    public Double calcRate(Long total, Long success) {
        if (total == null || total <= 0 || success == null) {
            return null;
        }
        return BigDecimal.valueOf(success)
                .divide(BigDecimal.valueOf(total), 4, RoundingMode.HALF_UP)
                .multiply(BigDecimal.valueOf(100))
                .setScale(2, RoundingMode.HALF_UP)
                .doubleValue();
    }

    private OrderListItem toOrderListItem(Order order) {
        return OrderListItem.builder()
                .id(order.getId())
                .orderSn(order.getOrderSn())
                .platform(order.getPlatform())
                .shopName(order.getShopName())
                .erpStatus(order.getErpStatus())
                .erpStatusText(order.getErpStatusText())
                .receiverName(order.getReceiverName())
                .receiverPhone(maskPhone(order.getReceiverPhone()))
                .totalAmount(order.getTotalAmount())
                .itemCount(order.getItems() != null ? order.getItems().size() : 0)
                .paymentTime(order.getPaymentTime() != null ? order.getPaymentTime().format(DATE_TIME_FORMATTER) : null)
                .warehouseName(order.getWarehouseName())
                .logisticsCompany(order.getLogisticsCompany())
                .logisticsNo(order.getLogisticsNo())
                .build();
    }

    private String maskPhone(String phone) {
        if (phone == null || phone.length() != 11) {
            return phone;
        }
        return phone.substring(0, 3) + "****" + phone.substring(7);
    }
}
