/*
 * @Descripttion:
 * @version:
 * @Author: Neo,Huang
 * @Date: 2023-11-18 22:52:59
 * @LastEditors: Neo,Huang
 * @LastEditTime: 2023-11-21 23:39:58
 */
package models

import (
	"encoding/json"

	"github.com/astaxie/beego"

	"box-gm/utils"
)

type ItemConfig struct {
	Id    int    `json:"id"`    // 道具ID
	Name  string `json:"name"`  // 道具名称
	Type  int    `json:"ty"`    // 道具类型
	Price int    `json:"price"` // 道具价格
}
type ItemConfigs []*ItemConfig

type RES_CONF_ITEMS struct {
	Code  int         `json:"code"`  // 道具ID
	Items ItemConfigs `json:"items"` // 道具配置列表
}

var itemConfigMap map[int]*ItemConfig
var itemConfigs ItemConfigs

func init() {
	itemConfigMap = make(map[int]*ItemConfig)

	itemConfigMap[101] = &ItemConfig{
		Id:   101,
		Name: "金币",
		Type: 1,
	}
	itemConfigMap[102] = &ItemConfig{
		Id:   102,
		Name: "绑金",
		Type: 1,
	}
	itemConfigMap[103] = &ItemConfig{
		Id:   103,
		Name: "N1",
		Type: 1,
	}
	itemConfigs = append(itemConfigs, itemConfigMap[101])
	itemConfigs = append(itemConfigs, itemConfigMap[102])
	itemConfigs = append(itemConfigs, itemConfigMap[103])
}

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

	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))
	// log.Printf("UpdateItemConfig url[%s] body[%s] buff[%s] err[%v]", url, string(body), string(buff), err)
	if err != nil {
		return 0, 0
	}

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

	oldCount := len(itemConfigs)
	itemConfigMap = make(map[int]*ItemConfig)
	itemConfigs = ItemConfigs{}
	for _, v := range res.Items {
		itemConfigMap[v.Id] = v
		itemConfigs = append(itemConfigs, v)
	}

	beego.Info("load item config, oldCount: ", oldCount, "newCount", len(itemConfigs))
	return oldCount, len(itemConfigs)
}

func GetItemName(id int) string {
	item, ok := itemConfigMap[id]
	if !ok {
		return ""
	}
	return item.Name
}

// 获取物品列表
func GetItemInfoList() ItemConfigs {
	// InitItemConfig()
	return itemConfigs
}
