package card_t_mall_order

import (
	"context"
	"kami/internal/consts"
	"kami/internal/dao"
	"kami/internal/model/do"
	"kami/internal/model/entity"
	"kami/utility/config"
	"time"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/os/gtime"
)

// GetRecentOrdersByStatus 获取已经支付过的支付宝订单
func (h *sRechargeTMallGameOrder) GetRecentOrdersByStatus(ctx context.Context, status consts.RechargeTMallGameOrder, duration time.Duration, tx gdb.TX) (data []entity.V1RechargeTMallShop, err error) {
	//	处理30分钟内没有处理的订单
	data = make([]entity.V1RechargeTMallShop, 0)
	m := dao.V1RechargeTMallShop.Ctx(ctx).DB(config.GetDatabaseV1())
	if tx != nil {
		m = m.TX(tx)
	}
	err = m.Where(dao.V1RechargeTMallShop.Columns().Status, status).
		WhereGTE(dao.V1RechargeTMallShop.Columns().CreatedAt, gtime.Now().Add(-duration)).
		Scan(&data)
	return
}

// GetShopOrderByOrderNo 通过淘宝订单号获取淘宝订单信息
func (h *sRechargeTMallGameOrder) GetShopOrderByOrderNo(ctx context.Context, orderNo string, tx gdb.TX) (data *entity.V1RechargeTMallShop, err error) {
	data = &entity.V1RechargeTMallShop{}
	m := dao.V1RechargeTMallShop.Ctx(ctx).DB(config.GetDatabaseV1())
	if tx != nil {
		m = m.TX(tx)
	}
	err = m.Where(dao.V1RechargeTMallShop.Columns().OrderNo, orderNo).Scan(&data)
	return
}

// UpdateShopOrderStatusById 修改shop订单状态
func (h *sRechargeTMallGameOrder) UpdateShopOrderStatusById(ctx context.Context, id int, status consts.EnumShopStatus, tx gdb.TX) (err error) {
	m := dao.V1RechargeTMallShop.Ctx(ctx).DB(config.GetDatabaseV1())
	if tx != nil {
		m = m.TX(tx)
	}
	_, err = m.Where(dao.V1RechargeTMallShop.Columns().Id, id).Update(do.V1RechargeTMallShop{
		Status: status,
	})
	return
}

// ModifyCallBackStatus 修改回调状态
func (h *sRechargeTMallGameOrder) ModifyCallBackStatus(ctx context.Context, orderNo string, callbackStatus bool, tx gdb.TX) (err error) {
	m := dao.V1RechargeTMallOrder.Ctx(ctx).DB(config.GetDatabaseV1())
	if tx != nil {
		m = m.TX(tx)
	}
	status := consts.TMallGameCallbackStatusFail
	if callbackStatus {
		status = consts.TMallGameCallbackStatusSuccess
	}
	_, err = m.Where(dao.V1RechargeTMallOrder.Columns().OrderNo, orderNo).Update(do.V1RechargeTMallOrder{NotifyStatus: status})
	return
}
