package pay

import (
	"common/connection"
	"fmt"
	"paycenter/internal/mesqueue"
	"sync"
)

var (
	// 用户缓存对象
	orderMap = make(map[int64]*Order)
	rwmu     sync.RWMutex
)

// GetUserByID 根据用户id获取用户信息
func GetUserByID(orderID int64) (*Order, error) {

	//判断缓存是否存在
	var order *Order

	func() *Order {
		rwmu.RLock()
		defer rwmu.RUnlock()
		ok := true
		if order, ok = orderMap[orderID]; ok {
			return order
		}
		return nil
	}()

	if order != nil {
		return order, nil
	}

	result := connection.GetPayDB().First(&order, orderID)
	if result.Error != nil {
		return nil, result.Error
	}

	//添加缓存
	func() {
		rwmu.Lock()
		defer rwmu.Unlock()
		orderMap[order.OrderID] = order
	}()

	return order, nil
}

// AddOrderCache 添加用户缓存
func AddOrderCache(order *Order) {
	rwmu.Lock()
	defer rwmu.Unlock()
	orderMap[order.OrderID] = order
}

// AddOrder 添加订单
func AddOrder(order *Order) (int64, error) {

	//处理一些验证

	// 异步 写入到数据库
	connection.AsyncCreate(connection.GetPayDB(), &order)

	//添加缓存
	AddOrderCache(order)

	return order.OrderID, nil
}

// ChangeOrderStatus 改变订单状态
func ChangeOrderStatus(orderID int64, status int32) error {

	//根据订单id获取订单
	order, err := GetUserByID(orderID)
	if err != nil {
		return err
	}

	//判断订单是否存在
	if order == nil {
		return fmt.Errorf("订单不存在,订单id %d", orderID)
	}

	if status == 1 {
		mesqueue.AddQueue(mesqueue.GameMsg{
			GameId:  "",
			OrderID: orderID,
		})
	}

	//更新订单状态
	order.OrderStatus = status
	order.IsNotifyGameServer = 1

	//异步更新数据库
	connection.AsyncSave(connection.GetPayDB(), &order)
	return nil
}
