/*
 * @Descripttion:
 * @version:
 * @Author: Neo,Huang
 * @Date: 2023-11-18 22:52:59
 * @LastEditors: Neo,Huang
 * @LastEditTime: 2023-11-19 16:04:30
 */
package models

import (
	"encoding/json"

	"github.com/astaxie/beego"

	"box-gm/utils"
)

type GoodsConfig struct {
	Id    int    `json:"id"`   // 商品ID
	Name  string `json:"name"` // 商品名称
	Price int    `json:"rmb"`  // 商品价格
}
type GoodsConfigs []*GoodsConfig

type RES_CONF_GOODS struct {
	Code      int          `json:"code"`      // 错误码
	GoodsList GoodsConfigs `json:"goodsList"` // 商品配置列表
}

var goodsConfigMap map[int]*GoodsConfig
var goodsConfigs GoodsConfigs

func init() {
	goodsConfigMap = make(map[int]*GoodsConfig)
}

func UpdateGoodsConfig() (int, int) {
	params := make(map[string]interface{})
	params["name"] = "gm_get_conf_goods"

	body, _ := json.Marshal(params)
	host := utils.GetKeyConf("gameservers", "web")
	sign := utils.Strtomd5(string(body) + utils.GetKeyConf("app", "gameKey"))
	url := "http://" + host + "/json?sign=" + sign
	buff, err := utils.SendAndRecvHTTP("POST", url, string(body))
	if err != nil {
		return 0, 0
	}

	var res RES_CONF_GOODS
	err = json.Unmarshal(buff, &res)
	if err != nil {
		return 0, 0
	}
	if res.Code != 200 {
		return 0, 0
	}

	oldCount := len(goodsConfigs)
	goodsConfigMap = make(map[int]*GoodsConfig)
	goodsConfigs = GoodsConfigs{}
	for _, v := range res.GoodsList {
		goodsConfigMap[v.Id] = v
		goodsConfigs = append(goodsConfigs, v)
	}

	beego.Info("load goods config, oldCount: ", oldCount, "newCount", len(goodsConfigs))
	return oldCount, len(goodsConfigs)
}

func GetGoodsName(id int) string {
	item, ok := goodsConfigMap[id]
	if !ok {
		return ""
	}
	return item.Name
}
func GetGoodsPrice(id int) int {
	item, ok := goodsConfigMap[id]
	if !ok {
		return 0
	}
	return item.Price
}

// 获取物品列表
func GetGoodsInfoList() GoodsConfigs {
	// InitItemConfig()
	return goodsConfigs
}
