package service

import (
	"context"
	"gadmin/config"
	"gadmin/internal/admin/consts"
	"gadmin/internal/admin/data"
	"gadmin/internal/admin/forms"
	"gadmin/internal/gorm/query"
	"gadmin/utility/serializer"
)

var AdvertisementLog = new(sAdvertisementLog)

type sAdvertisementLog struct{}

func (s *sAdvertisementLog) AdvRanking(ctx context.Context, req forms.AdvRankingReq) serializer.Response {
	type mods struct {
		ID       int64  `json:"id"`
		NickName string `json:"nickName"`
		UserId   int64  `json:"user_id"`
		Count    int64  `json:"count"`
		LastTime int64  `json:"lastTime"`
	}

	var (
		q      = query.Use(config.DB).AdvertisementLog
		m      = q.WithContext(ctx).Where(q.EventID.Eq(4))
		models forms.ListRes
		lists  []mods
	)

	req.Page, req.PerPage, _ = forms.CalculatePage(req.Page, req.PerPage)

	if req.ServerId > 0 {
		m = m.Where(q.ServerID.Eq(int32(req.ServerId)))
	}

	if len(req.Createtime) == 2 {
		m = m.Where(q.EventAt.Between(int32(req.Createtime[0]), int32(req.Createtime[1])))
	}

	m = m.Select(q.UserID, q.ID.Count().As("count")).Group(q.UserID).Order(q.ID.Count().Desc())

	if err := m.Limit(100).Scan(&lists); err != nil {
		return serializer.Err(consts.CodeParamErr, "查询出错 lists", err)
	}

	for i := 0; i < len(lists); i++ {
		lists[i].ID = int64(i + 1)
		user := data.GetUser(lists[i].UserId)
		if user != nil {
			lists[i].NickName = user.NickName
		}

		first, _ := q.WithContext(ctx).Select(q.EventAt).Where(q.EventID.Eq(4)).Where(q.UserID.Eq(lists[i].UserId)).Order(q.ID.Desc()).First()
		if first != nil {
			lists[i].LastTime = int64(first.EventAt)
		}
	}

	models.List = lists
	models.Page = req.Page
	models.PerPage = req.PerPage
	models.PageCount = 0

	return serializer.Suc(models)
}
