package service

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

var PlayerMaterial = new(sPlayerMaterial)

type sPlayerMaterial struct{}

func (s *sPlayerMaterial) Equipments(ctx *gin.Context, req forms.PlayerEquipmentsReq) serializer.Response {
	DB, err := player.GetDBByUserId(req.PlayerId)
	if err != nil {
		return serializer.Err(consts.CodeParamErr, "GetDBByUserId err", err)
	}

	var (
		q                 = query.Use(config.GDBGroup[DB]).PlayerMaterial
		m                 = q.WithContext(ctx).Select(q.Equipments).Where(q.Playerid.Eq(req.PlayerId))
		equipments        string
		dropEquipmentMap  map[string]*forms.DropEquipment
		dropEquipmentList forms.DropEquipmentList
		models            forms.PlayerEquipmentsRes
	)

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

	if equipments == "" {
		models.List = nil
		return serializer.Suc(models)
	}

	err = json.Unmarshal([]byte(equipments), &dropEquipmentMap)
	if err != nil {
		return serializer.Err(
			consts.CodeParamErr,
			"转换出错",
			err,
		)
	}

	for _, v := range dropEquipmentMap {
		dropEquipmentList = append(dropEquipmentList, *v)
	}

	sort.Sort(dropEquipmentList)

	models.List = dropEquipmentList
	return serializer.Suc(models)
}
