package card_t_mall_order

import (
	"context"
	"fmt"
	"kami/internal/consts"
	"kami/internal/dao"
	"kami/internal/model"
	"kami/internal/model/do"
	"kami/internal/model/entity"
	"kami/internal/service"
	"kami/utility/config"
	"kami/utility/utils"

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

func init() {
	service.RegisterRechargeTMallGameOrder(New())
}

func New() *sRechargeTMallGameOrder {
	return &sRechargeTMallGameOrder{}
}

type sRechargeTMallGameOrder struct{}

func (h *sRechargeTMallGameOrder) List(ctx context.Context, input *model.RechargeTMallGameOrderListInput) (total int, data []model.RechargeTMallGameOrderListOutput, err error) {
	total = 0
	data = make([]model.RechargeTMallGameOrderListOutput, 0)
	m := dao.V1RechargeTMallOrder.Ctx(ctx).DB(config.GetDatabaseV1()).Page(input.Current, input.PageSize)
	if input.Status != "" {
		m = m.Where(dao.V1RechargeTMallOrder.Columns().Status, input.Status)
	}
	if input.OrderNo != "" {
		m = m.Where(dao.V1RechargeTMallOrder.Columns().OrderNo, input.OrderNo)
	}
	if input.AccountNumber != "" {
		m = m.Where(dao.V1RechargeTMallOrder.Columns().AccountNumber, input.AccountNumber)
	}
	if input.MerchantOrder != "" {
		m = m.Where(dao.V1RechargeTMallOrder.Columns().MerchantOrder, input.MerchantOrder)
	}
	if input.CallBackType != "" {
		m = m.Where(dao.V1RechargeTMallOrder.Columns().CallbackType, input.CallBackType)
	}
	if input.ThirdMerchantOrder != "" {
		m = m.Where(dao.V1RechargeTMallOrder.Columns().ThirdMerhantOrder, input.ThirdMerchantOrder)
	}
	if len(input.DateRange) == 2 {
		m = m.WhereBetween(dao.V1RechargeTMallOrder.Columns().CreatedAt, input.DateRange[0], input.DateRange[1])
	}
	if input.TMallShopOrder != "" {
		shopOrder, _ := h.GetShopOneByTid(ctx, input.TMallShopOrder, nil)
		m = m.Where(dao.V1RechargeTMallOrder.Columns().OrderNo, shopOrder.OrderNo)
	}
	err = m.WithAll().OrderDesc(dao.V1RechargeTMallOrder.Columns().CreatedAt).ScanAndCount(&data, &total, false)
	return
}

// Create 创建订单
func (h *sRechargeTMallGameOrder) Create(ctx context.Context, input *model.RechargeTMallGameOrderCreateInput) (orderNo string, err error) {
	orderNo = utils.GenerateRandomUUID()
	_, err = dao.V1RechargeTMallOrder.Ctx(ctx).DB(config.GetDatabaseV1()).Insert(do.V1RechargeTMallOrder{
		OrderNo:           orderNo,
		AccountId:         input.AccountId,
		AccountNumber:     input.AccountNumber,
		Amount:            input.Amount,
		Status:            consts.RechargeTMallGameOrderStatusCreated,
		MerchantOrder:     input.MerchantOrder,
		ThirdMerhantOrder: input.ThirdMerchantOrder,
		CallbackUrl:       input.CallbackUrl,
		CallbackType:      input.CallbackType,
		ChannelName:       input.ChannelName,
		Remark:            input.Attach,
	})
	return
}

// GetById 根据Id获取单个订单
func (h *sRechargeTMallGameOrder) GetById(ctx context.Context, orderNo string, tx gdb.TX) (data *entity.V1RechargeTMallOrder, err error) {
	data = &entity.V1RechargeTMallOrder{}
	m := dao.V1RechargeTMallOrder.Ctx(ctx).DB(config.GetDatabaseV1())
	if tx != nil {
		m = m.TX(tx)
	}
	err = m.Where(dao.V1RechargeTMallOrder.Columns().OrderNo, orderNo).Scan(&data)
	return
}

// GetByShopId 根据天猫订单关联查找对应订单
func (h *sRechargeTMallGameOrder) GetByShopId(ctx context.Context, shopOrderId int64, tx gdb.TX) (data *entity.V1RechargeTMallOrder, err error) {
	data = &entity.V1RechargeTMallOrder{}
	m := dao.V1RechargeTMallOrder.Ctx(ctx).DB(config.GetDatabaseV1())
	if tx != nil {
		m = m.TX(tx)
	}
	err = m.Where(dao.V1RechargeTMallOrder.Columns().ShopId, shopOrderId).Scan(&data)
	return
}

// AssociateCreatedOrderAndStatus 淘宝订单相互关联
func (h *sRechargeTMallGameOrder) AssociateCreatedOrderAndStatus(ctx context.Context, input *model.AssociateCreatedOrderAndStatusInput, tx gdb.TX) (err error) {
	m := dao.V1RechargeTMallOrder.Ctx(ctx).DB(config.GetDatabaseV1())
	if tx != nil {
		m = m.TX(tx)
	}
	err = m.Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
		data := entity.V1RechargeTMallOrder{}
		if err2 := dao.V1RechargeTMallOrder.Ctx(ctx).DB(config.GetDatabaseV1()).TX(tx).
			Where(dao.V1RechargeTMallOrder.Columns().AccountNumber, input.AccountNumber).
			Where(dao.V1RechargeTMallOrder.Columns().Status, consts.RechargeTMallGameOrderStatusCreated).
			Scan(&data); err2 != nil {
			return err2
		}
		if _, err2 := dao.V1RechargeTMallOrder.Ctx(ctx).DB(config.GetDatabaseV1()).TX(tx).
			Where(dao.V1RechargeTMallOrder.Columns().Id, data.Id).Update(do.V1RechargeTMallOrder{
			ShopId: input.ShopId,
			Status: consts.RechargeTMallGameBindShopOrderSucceed,
		}); err2 != nil {
			return err2
		}
		//反向Id关联
		if _, err2 := dao.V1RechargeTMallShop.Ctx(ctx).DB(config.GetDatabaseV1()).TX(tx).
			Where(dao.V1RechargeTMallShop.Columns().Id, input.ShopId).Update(do.V1RechargeTMallShop{
			OrderNo: data.OrderNo,
			Account: data.AccountNumber,
		}); err2 != nil {
			return err2
		}
		_ = h.AddOrderHistory(ctx, &model.AddAgisoCallBackHistoryInput{
			OrderNo:      data.OrderNo,
			OriginalData: "",
			Status:       consts.RechargeTMallGameBindShopOrderSucceed,
			SourceType:   "",
			Remark:       fmt.Sprintf("关联账号：%s成功", input.AccountNumber),
		}, tx)
		return nil
	})
	if err != nil {
		_ = h.AddShopHistory(ctx, &model.AddOrderShopHistoryInput{
			ShopId:  input.ShopId,
			RawData: "",
			Remark:  fmt.Sprintf("提取账号：%s失败", input.AccountNumber),
			Status:  consts.EnumShopStatusBindOrderFail,
		}, nil)
	} else {
		_ = h.AddShopHistory(ctx, &model.AddOrderShopHistoryInput{
			ShopId:  input.ShopId,
			RawData: "",
			Remark:  fmt.Sprintf("提取账号：%s成功", input.AccountNumber),
			Status:  consts.EnumShopStatusBindOrderSucceed,
		}, nil)
	}
	return
}

// GetAllCreatedAccount 查询出所有正在创建状态的账号信息
func (h *sRechargeTMallGameOrder) GetAllCreatedAccount(ctx context.Context, tx gdb.TX) (data []model.RechargeTMallGameAccountOutput, err error) {
	data = make([]model.RechargeTMallGameAccountOutput, 0)
	m := dao.V1RechargeTMallOrder.Ctx(ctx).DB(config.GetDatabaseV1())
	if tx != nil {
		m = m.TX(tx)
	}
	err = m.Where(dao.V1RechargeTMallOrder.Columns().Status, consts.RechargeTMallGameOrderStatusCreated).Scan(&data)
	return
}
