package service

import (
	"gadmin/config"
	"gadmin/internal/admin/consts"
	"gadmin/internal/admin/forms"
	"gadmin/internal/gorm/model"
	"gadmin/internal/gorm/query"
	"gadmin/utility/serializer"
	"github.com/gin-gonic/gin"
)

// BanLog 拉黑记录
var BanLog = new(sBanLog)

type sBanLog struct{}

func (s *sBanLog) List(ctx *gin.Context, req forms.UserAccountBanListReq) serializer.Response {
	type Result struct {
		model.PlayerBanLog
		OpenID     string `gorm:"column:openId" json:"openId"`
		NickName   string `gorm:"column:nickName" json:"nickName"`
		ImgURL     string `gorm:"column:imgUrl" json:"imgUrl"`
		CurBan     int32  `json:"curBan"`
		ServerName string `json:"serverName"`
	}

	var (
		q            = query.Use(config.DB).PlayerBanLog
		m            = q.WithContext(ctx)
		offset int64 = 0
		models forms.UserAccountListRes
		lists  []*Result
	)

	if req.ID > 0 {
		m = m.Where(q.Playerid.Eq(req.ID))
	}
	if req.AccId > 0 {
		m = m.Where(q.AccID.Eq(req.AccId))
	}

	m = m.Order(q.ID.Desc())

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

	count, err := m.Count()
	if err != nil {
		return serializer.Err(consts.CodeParamErr, "查询出错 count", err)
	}

	if count > 0 {
		if err = m.Limit(int(req.PerPage)).Offset(int(offset)).Scan(&lists); err != nil {
			return serializer.Err(consts.CodeParamErr, "查询出错 lists", err)
		}
	}

	for _, v := range lists {
		v.ServerName, _ = ServerOption.GetName(ctx, v.ServerID)

		u := query.Use(config.GDBGroup[int(v.ServerID)]).PlayerAttr
		user, _ := u.Where(u.Playerid.Eq(v.Playerid)).First()
		if user != nil {
			v.NickName = user.NickName
			v.ImgURL = user.ImgURL
			v.OpenID = user.OpenID
			v.CurBan = user.Ban
		}
	}

	models.List = lists
	models.Page = req.Page
	models.PerPage = req.PerPage
	models.PageCount = (count + req.PerPage - 1) / req.PerPage
	return serializer.Suc(models)
}
