package service

import (
	"encoding/json"
	"fmt"
	"gadmin/config"
	"gadmin/internal/admin/consts"
	"gadmin/internal/admin/forms"
	"gadmin/internal/elastic/docs"
	"gadmin/internal/elastic/eapi"
	"gadmin/internal/gorm/model"
	"gadmin/internal/gorm/query"
	"gadmin/utility/player"
	"gadmin/utility/serializer"
	"os"
	"time"

	"github.com/gin-gonic/gin"
)

var Signin = new(sSignin)

type sSignin struct{}

func (s *sSignin) Count(ctx *gin.Context, req forms.SigninCountReq) serializer.Response {
	type Signin struct {
		Time  int64 `json:"time"`
		Count int64 `json:"count"`
	}

	DB, err := player.GetDBByUserId(req.Playerid)
	if err != nil {
		return serializer.Err(consts.CodeParamErr, "GetDBByUserId err", err)
	}

	var (
		q      = query.Use(config.GDBGroup[DB]).Signin
		m      = q.WithContext(ctx).Where(q.Playerid.Eq(req.Playerid))
		models *model.Signin
		signin Signin
	)

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

	if models != nil {
		if err = json.Unmarshal([]byte(models.Sign), &signin); err != nil {
			return serializer.Err(
				consts.CodeParamErr,
				"json.Unmarshal err",
				err,
			)
		}
	}

	must := []eapi.M{
		{
			"term": eapi.M{
				"event_id": consts.LoginEventEntryPack,
			},
		},
		{
			"term": eapi.M{
				"user_id": req.Playerid,
			},
		},
		{
			"range": eapi.M{
				"event_at": eapi.M{
					"gte": time.Now().Unix() - 86400*90,
					"lte": time.Now().Unix(),
				},
			},
		},
	}

	where := eapi.M{
		"query": eapi.M{
			"bool": eapi.M{
				"must": must,
			},
		},
	}
	var loginCount int64
	if eapi.ExistElastic() {
		index := fmt.Sprintf("%s%s_%s", os.Getenv("ELASTIC_TOPIC"), docs.LoginLog.GetIndex(), time.Now().Format("200601"))
		loginCount, err = eapi.Count(ctx, index, where)
		if err != nil {
			return serializer.Err(consts.CodeParamErr, "查询出错 Count", err)
		}
	}

	return serializer.Suc(map[string]interface{}{
		"signinCount": signin.Count, // 签到次数
		"loginCount":  loginCount,   // 累计登录次数
	})
}
