package admin_order

import (
	"context"
	"fmt"
	"time"

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

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

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

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

func (l *AdminGetRefundStatisticsLogic) AdminGetRefundStatistics(req *types.AdminGetRefundStatisticsReq) (resp *types.AdminGetRefundStatisticsResp, err error) {
	// 获取今日的开始和结束时间
	today := time.Now()
	startOfDay := time.Date(today.Year(), today.Month(), today.Day(), 0, 0, 0, 0, today.Location())
	endOfDay := startOfDay.Add(24 * time.Hour)

	// 构建查询条件
	builder := l.svcCtx.OrderModel.SelectBuilder()

	// 查询总退款金额（status=refunded表示已退款）
	totalBuilder := builder.Where("status = ?", "refunded")
	totalRefundAmount, err := l.svcCtx.OrderModel.FindSum(l.ctx, totalBuilder, "amount")
	if err != nil {
		logx.Errorf("查询总退款金额失败: %v", err)
		return nil, fmt.Errorf("查询总退款金额失败: %w", err)
	}

	// 查询今日退款金额（status=refunded表示已退款，且退款时间为今日）
	todayBuilder := builder.Where("status = ? AND refund_time >= ? AND refund_time < ?", "refunded", startOfDay, endOfDay)
	todayRefundAmount, err := l.svcCtx.OrderModel.FindSum(l.ctx, todayBuilder, "amount")
	if err != nil {
		logx.Errorf("查询今日退款金额失败: %v", err)
		return nil, fmt.Errorf("查询今日退款金额失败: %w", err)
	}

	// 构建响应
	resp = &types.AdminGetRefundStatisticsResp{
		TotalRefundAmount: totalRefundAmount,
		TodayRefundAmount: todayRefundAmount,
	}

	return resp, nil
}
