package admin_order

import (
	"context"
	"fmt"
	"time"

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

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

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

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

func (l *AdminGetOrderStatisticsLogic) AdminGetOrderStatistics(req *types.AdminGetOrderStatisticsReq) (resp *types.AdminGetOrderStatisticsResp, err error) {
	// 获取当前时间
	now := time.Now()
	var startTime, endTime time.Time

	// 根据时间维度设置时间范围和格式
	switch req.Dimension {
	case "day":
		// 日：当月1号到今天
		startTime = time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
		endTime = time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 999999999, now.Location())
	case "month":
		// 月：今年1月到当月
		startTime = time.Date(now.Year(), 1, 1, 0, 0, 0, 0, now.Location())
		endTime = time.Date(now.Year(), now.Month(), 1, 23, 59, 59, 999999999, now.Location()).AddDate(0, 1, -1)
	case "year":
		// 年：过去5年
		startTime = time.Date(now.Year()-5, 1, 1, 0, 0, 0, 0, now.Location())
		endTime = time.Date(now.Year(), 12, 31, 23, 59, 59, 999999999, now.Location())
	case "all":
		// 全部：所有时间，但按日统计
		startTime = time.Date(2020, 1, 1, 0, 0, 0, 0, now.Location()) // 假设从2020年开始
		endTime = now
	default:
		// 默认为日
		startTime = time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
		endTime = time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 999999999, now.Location())
	}

	// 构建查询条件
	builder := l.svcCtx.OrderModel.SelectBuilder().
		Where("create_time >= ? AND create_time <= ?", startTime, endTime).
		Where("status = ?", "paid") // 只统计已支付的订单

	// 查询所有符合条件的订单
	orders, err := l.svcCtx.OrderModel.FindAll(l.ctx, builder, "create_time ASC")
	if err != nil {
		logx.Errorf("查询订单统计数据失败: %v", err)
		return nil, fmt.Errorf("查询订单统计数据失败: %w", err)
	}

	// 按日期分组统计
	dateMap := make(map[string]*types.OrderStatisticsItem)

	for _, order := range orders {
		var dateKey string
		if req.Dimension == "year" {
			dateKey = order.CreateTime.Format("2006")
		} else if req.Dimension == "month" {
			dateKey = order.CreateTime.Format("2006-01")
		} else {
			dateKey = order.CreateTime.Format("2006-01-02")
		}

		if item, exists := dateMap[dateKey]; exists {
			item.Count++
			item.Amount += order.Amount
		} else {
			dateMap[dateKey] = &types.OrderStatisticsItem{
				Date:   dateKey,
				Count:  1,
				Amount: order.Amount,
			}
		}
	}

	// 转换为切片
	items := make([]types.OrderStatisticsItem, 0, len(dateMap))
	for date := range dateMap {
		items = append(items, *dateMap[date])
	}

	// 构建响应
	resp = &types.AdminGetOrderStatisticsResp{
		Items: items,
	}

	return resp, nil
}
