package shop

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"server/console"
	mysqlmgr "server/db/mysql"
	redismgr "server/db/redis"
	"server/msg"
	"server/user"
	"time"

	"github.com/name5566/leaf/gate"
)

func init() {
}

func OnBuy(args []interface{}) {
	m := args[0].(*msg.BuyShopItem)
	a := args[1].(gate.Agent)
	user_id := a.UserData().(*msg.UserInfo).UserId
	console.Log("玩家购买了商品id为：", m.Id)
	item := getShopItemById(m.Id)
	if item != nil {
		user.AddUserCoin(item.Num, user_id)
	} else {
		console.Log("OnBuy error:", m.String())
	}

}

type ShopItem struct {
	ID         int       `db:"id"`
	ShopType   int       `db:"shop_type"`
	Name       string    `db:"name"`
	Price      int       `db:"price"`
	Num        int       `db:"num"`
	CreateTime time.Time `db:"create_time"` // 添加了create_time字段
}

func GetShopList(shop_type int) ([]*msg.ShopItem, error) {
	str, err := redismgr.Get("ShopList")
	var list []*msg.ShopItem = nil
	if err == nil {
		json.Unmarshal([]byte(str), &list)
	}
	if list != nil {
		return list, nil
	}
	rows, err := mysqlmgr.Query("SELECT * FROM shop_config WHERE shop_type = ? LIMIT 100 ", shop_type)
	if err != nil {
		return nil, fmt.Errorf("query failed: %v", err)
	}
	defer rows.Close()

	var nullTime sql.NullTime // 用于处理可能的NULL时间值
	for rows.Next() {
		var shop_item ShopItem
		if err := rows.Scan(
			&shop_item.ID,
			&nullTime,
			&shop_item.Name,
			&shop_item.Price,
			&shop_item.Num,
			&shop_item.ShopType,
		); err != nil {
			return nil, fmt.Errorf("failed to scan row: %v", err)
		}
		list = append(list, &msg.ShopItem{
			Id:    fmt.Sprint(shop_item.ID),
			Name:  shop_item.Name,
			Price: int32(shop_item.Price),
			Num:   int32(shop_item.Num),
		})
	}

	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("rows error: %v", err)
	}

	shopDataJson, err := json.Marshal(list)
	if err != nil {
		console.Log("Error marshalling user data: %v", err)
		return nil, fmt.Errorf("failed to scan row: %v", err)
	}
	redismgr.Set("ShopList", shopDataJson)
	return list, nil
}

func getShopItemById(id string) *msg.ShopItem {
	list, err := GetShopList(1)
	if err != nil {
		console.Log("getShopItemById err:", err)
	}
	for _, v := range list {
		if v.Id == id {
			return v
		}
	}
	return nil
}
