package admin_order

import (
	"context"
	"fmt"

	"xingfucha-server/app/main/api/internal/svc"
	"xingfucha-server/app/main/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AdminGetOrderSourceStatisticsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAdminGetOrderSourceStatisticsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetOrderSourceStatisticsLogic {
	return &AdminGetOrderSourceStatisticsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AdminGetOrderSourceStatisticsLogic) AdminGetOrderSourceStatistics(req *types.AdminGetOrderSourceStatisticsReq) (resp *types.AdminGetOrderSourceStatisticsResp, err error) {
	// 查询所有有产品ID的订单
	builder := l.svcCtx.OrderModel.SelectBuilder()
	builder = builder.Where("product_id IS NOT NULL")

	// 获取所有符合条件的订单
	orders, err := l.svcCtx.OrderModel.FindAll(l.ctx, builder, "id DESC")
	if err != nil {
		logx.Errorf("查询订单列表失败: %v", err)
		return nil, fmt.Errorf("查询订单列表失败: %w", err)
	}

	logx.Infof("获取到订单数量: %d", len(orders))

	// 统计每个产品的订单数量
	productCountMap := make(map[int64]int64)
	for _, order := range orders {
		productCountMap[order.ProductId]++
	}

	// 构建返回结果
	items := make([]types.OrderSourceStatisticsItem, 0, len(productCountMap))
	for productId, count := range productCountMap {
		// 获取产品信息
		product, err := l.svcCtx.ProductModel.FindOne(l.ctx, productId)
		if err != nil {
			logx.Errorf("查询产品信息失败 productId=%d, err=%v", productId, err)
			// 如果查询失败，使用默认值
			items = append(items, types.OrderSourceStatisticsItem{
				ProductName: "未知产品",
				OrderCount:  count,
			})
			continue
		}

		items = append(items, types.OrderSourceStatisticsItem{
			ProductName: product.ProductName,
			OrderCount:  count,
		})
	}

	// 按订单数量降序排序
	for i := 0; i < len(items)-1; i++ {
		for j := i + 1; j < len(items); j++ {
			if items[i].OrderCount < items[j].OrderCount {
				items[i], items[j] = items[j], items[i]
			}
		}
	}

	logx.Infof("查询到订单来源统计数据: %d 个产品，订单总数: %d", len(items), len(orders))
	return &types.AdminGetOrderSourceStatisticsResp{
		Items: items,
	}, nil
}

// 定义结果结构体
type OrderSourceResult struct {
	ProductName string `db:"product_name"`
	OrderCount  int64  `db:"order_count"`
}
