package service

import (
	"context"
	"gadmin/config"
	"gadmin/internal/admin/consts"
	"gadmin/internal/admin/forms"
	"gadmin/internal/gorm/query"
	"gadmin/package/gmdata"
	"gadmin/utility"
	"github.com/sirupsen/logrus"
)

var LimitGift = new(sLimitGift)

type sLimitGift struct{}

func (s *sLimitGift) List(ctx context.Context, params forms.LimitGiftListReq) (resp forms.LimitGiftListRespData, err error) {
	var (
		rdb              = query.Use(config.DB).ReportDayLimitgift
		days             = 0
		offset           = (params.Page - 1) * params.PerPage
		startIndex       = int(offset + 1)
		endIndex         = int(params.PerPage + offset)
		startTID   int32 = 0
		endTID     int32 = 0
		tempLst    []*forms.LimitGiftListItem
	)

	// 获取总触发次数
	type Stat struct {
		Total int64
	}

	var stat Stat
	mt := rdb.Select(rdb.ShowCount.Sum().As("total")).Where(rdb.Date.Between(params.Day, params.EndDay))

	switch params.ChannelId {
	case consts.ChannelIdNone:
		// 不选择渠道
	case consts.ChannelIdAllAdv, consts.ChannelIdAllWx, consts.ChannelIdAllTT:
		// 所有的广告渠道
		mt = mt.Where(rdb.ChannelID.In(Channel.GetIdsByType(params.ChannelId)...))
	default:
		// 指定渠道
		mt = mt.Where(rdb.ChannelID.Eq(params.ChannelId))
	}

	if params.ServerId > 0 {
		mt = mt.Where(rdb.ServerID.Eq(int64(params.ServerId)))
	}

	if err = mt.Scan(&stat); err != nil {
		return forms.LimitGiftListRespData{}, err
	}

	for k, v := range gmdata.LimitGiftList {
		if k >= startIndex && k <= endIndex {
			if startTID == 0 {
				startTID = v.Id
			}
			endTID = v.Id
			tempLst = append(tempLst, &forms.LimitGiftListItem{
				ID:              v.Id,
				GoodsType:       v.TypeName,
				GoodsValue:      v.ValueStr,
				AllTriggerCount: stat.Total,
				ShowCount:       0,
				PayCount:        0,
			})
		}
	}

	days, err = utility.GetDaysBetween2Date("2006-01-02", params.Day, params.EndDay)
	if err != nil {
		return resp, err
	}
	days += 1

	ml := rdb.
		Where(rdb.Date.Between(params.Day, params.EndDay)).
		Order(rdb.Date, rdb.GoodsID).
		Where(rdb.GoodsID.Between(int64(startTID), int64(endTID)))
	if params.ChannelId != "" {
		ml = ml.Where(rdb.ChannelID.Eq(params.ChannelId))
	}
	results, err := ml.Find()
	if err != nil {
		return resp, err
	}

	findResult := func(goodsID int32) *forms.LimitGiftListItem {
		for _, v := range tempLst {
			if v.ID == goodsID {
				return v
			}
		}
		return nil
	}

	for _, result := range results {
		goods := gmdata.GetLimitGift(int32(result.GoodsID))
		if goods == nil {
			continue
		}

		item := findResult(goods.Id)
		if item == nil {
			logrus.Warnf("获取限时礼包失败:%+v", goods)
			continue
		} else {
			item.ShowCount += result.ShowCount
			item.PayCount += result.PayCount
		}
	}

	resp.Data = tempLst
	resp.Total = int64(len(gmdata.LimitGiftList))

	return
}
