package card_info_t_mall_game

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

	"github.com/duke-git/lancet/v2/slice"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/os/gtime"

	v1 "kami/api/card_info_t_mall_game/v1"
)

func (c *ControllerV1) TMallGameDataSync(ctx context.Context, req *v1.TMallGameDataSyncReq) (res *v1.TMallGameDataSyncRes, err error) {
	//	获取近5s的所有数据
	//	获取账户数据
	res = &v1.TMallGameDataSyncRes{}
	orderInfo := make([]*entity.V1RechargeTMallOrder, 0)
	if err2 := dao.V1RechargeTMallOrder.Ctx(ctx).DB(config.GetDatabaseV1()).Unscoped().
		Where(dao.V1RechargeTMallOrder.Columns().ChannelName, req.ChannelName).
		WhereGTE(dao.V1RechargeTMallOrder.Columns().UpdatedAt, gtime.Now().Add(-gtime.S*time.Duration(req.Duration))).
		Scan(&orderInfo); err2 != nil {
		glog.Error(ctx, err2)
	}
	res.OrderData = orderInfo

	orderNos := g.SliceStr{}
	accountIds := g.SliceStr{}
	for _, order := range orderInfo {
		accountIds = append(accountIds, order.AccountId)
		orderNos = append(orderNos, order.OrderNo)
	}
	accountInfo := make([]*entity.V1RechargeTMallAccount, 0)
	if err2 := dao.V1RechargeTMallAccount.Ctx(ctx).DB(config.GetDatabaseV1()).Unscoped().
		WhereIn(dao.V1RechargeTMallAccount.Columns().Id, accountIds).
		Scan(&accountInfo); err2 != nil {
		glog.Error(ctx, err2)
	}
	res.AccountData = accountInfo

	shopInfo := make([]*entity.V1RechargeTMallShop, 0)
	if err2 := dao.V1RechargeTMallShop.Ctx(ctx).DB(config.GetDatabaseV1()).Unscoped().
		WhereIn(dao.V1RechargeTMallOrderHistory.Columns().OrderNo, orderNos).
		WhereGT(dao.V1RechargeTMallShop.Columns().UpdatedAt, gtime.Now().Add(-gtime.S*time.Duration(req.Duration))).
		Scan(&shopInfo); err2 != nil {
		glog.Error(ctx, err2)
	}
	res.ShopData = shopInfo

	orderHistoryInfo := make([]*entity.V1RechargeTMallOrderHistory, 0)
	if err2 := dao.V1RechargeTMallOrderHistory.Ctx(ctx).DB(config.GetDatabaseV1()).Unscoped().
		WhereIn(dao.V1RechargeTMallOrderHistory.Columns().OrderNo, orderNos).
		WhereGT(dao.V1RechargeTMallOrderHistory.Columns().UpdatedAt, gtime.Now().Add(-gtime.S*time.Duration(req.Duration))).
		Scan(&orderHistoryInfo); err2 != nil {
		glog.Error(ctx, err2)
	}
	res.OrderHistory = orderHistoryInfo

	shopIds := g.SliceInt{}
	slice.ForEach(orderHistoryInfo, func(index int, item *entity.V1RechargeTMallOrderHistory) {
		shopIds = append(shopIds, int(item.Id))
	})
	shopHistoryInfo := make([]*entity.V1RechargeTMallShopHistory, 0)
	if err2 := dao.V1RechargeTMallShopHistory.Ctx(ctx).DB(config.GetDatabaseV1()).Unscoped().
		WhereIn(dao.V1RechargeTMallShopHistory.Columns().ShopId, shopIds).
		WhereGT(dao.V1RechargeTMallShopHistory.Columns().UpdatedAt, gtime.Now().Add(-gtime.S*time.Duration(req.Duration))).
		Scan(&shopHistoryInfo); err2 != nil {
		glog.Error(ctx, err2)
	}
	res.ShopHistory = shopHistoryInfo
	return
}
