package admin_promotion

import (
	"context"
	"time"

	"xingfucha-server/app/main/api/internal/svc"
	"xingfucha-server/app/main/api/internal/types"
	"xingfucha-server/common/ctxdata"
	"xingfucha-server/common/xerr"

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

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

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

func (l *GetPromotionStatsHistoryLogic) GetPromotionStatsHistory(req *types.GetPromotionStatsHistoryReq) (resp []types.PromotionStatsHistoryItem, err error) {
	// 获取当前用户ID
	adminUserId, getUidErr := ctxdata.GetUidFromCtx(l.ctx)
	if getUidErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取当前用户ID失败, %+v", getUidErr)
	}
	// 构建查询条件
	builder := l.svcCtx.AdminPromotionLinkStatsHistoryModel.SelectBuilder()

	// 如果有日期范围，添加日期过滤
	if req.StartDate != "" && req.EndDate != "" {
		startDate, err := time.Parse("2006-01-02", req.StartDate)
		if err != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "开始日期格式错误")
		}
		endDate, err := time.Parse("2006-01-02", req.EndDate)
		if err != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "结束日期格式错误")
		}
		// 将结束日期设置为当天的最后一刻
		endDate = endDate.Add(24*time.Hour - time.Second)
		builder = builder.Where("stats_date BETWEEN ? AND ?", startDate, endDate)
	}

	// 获取历史统计数据
	historyStats, err := l.svcCtx.AdminPromotionLinkStatsHistoryModel.FindAll(l.ctx, builder, "stats_date DESC")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取历史统计数据失败")
	}

	// 转换为响应格式
	resp = make([]types.PromotionStatsHistoryItem, 0, len(historyStats))
	for _, stat := range historyStats {
		// 验证链接是否属于当前用户
		link, err := l.svcCtx.AdminPromotionLinkModel.FindOne(l.ctx, stat.LinkId)
		if err != nil {
			continue // 如果链接不存在，跳过该记录
		}
		if link.AdminUserId != adminUserId {
			continue // 如果链接不属于当前用户，跳过该记录
		}

		resp = append(resp, types.PromotionStatsHistoryItem{
			Id:         stat.Id,
			LinkId:     stat.LinkId,
			PayAmount:  stat.PayAmount,
			ClickCount: stat.ClickCount,
			PayCount:   stat.PayCount,
			StatsDate:  stat.StatsDate.Format("2006-01-02"),
		})
	}

	return resp, nil
}
