package model

import (
	"errors"
	"f5"
	"main/constant"

	"gorm.io/gorm"
)

type InAppOrder struct {
	Idx            int64  `gorm:"column:idx;AUTO_INCREMENT;primaryKey"`
	AccountId      string `gorm:"column:account_id;<-:create;comment:account_id"`
	OrderId        string `gorm:"column:orderid;comment:订单id"`
	RoleId         string `gorm:"column:roleid;comment:角色id"`
	ServerId       int32  `gorm:"column:server_id;comment:服务器id"`
	Channel        int32  `gorm:"column:channel;comment:channel"`
	PolySdkChannel int32  `gorm:"column:poly_sdk_channel;comment:poly_sdk_channel"`
	UnifiedChannel int32  `gorm:"column:unified_channel;comment:unified_channel"`
	GameId         int32  `gorm:"column:gameid;comment:gameid"`
	OpenId         string `gorm:"column:openid;comment:平台openid"`
	ItemId         int32  `gorm:"column:itemid;comment:商品id"`
	TryCount       int32  `gorm:"column:try_count;comment:补单次数"`
	Price          int32  `gorm:"column:price;comment:price"`
	IP             string `gorm:"column:ipv4;comment:ipv4地址"`
	Status         int32  `gorm:"column:status;comment:0: 新添加订单 1:已支付 2：已发货"`
	ConfirmTime    int32  `gorm:"column:confirmtime;comment:GameServer订单确认时间"`
	CreateTime     int32  `gorm:"column:createtime;<-:create"`
	ModifyTime     int32  `gorm:"column:modifytime"`

	SpOrderId string `gorm:"column:sp_orderid;comment:平台的订单id"`
	SpAmount  int32  `gorm:"column:sp_amount;comment:充值获得游戏货币"`
	SpOthers  int32  `gorm:"column:sp_others;comment:游戏货币补单"`
	SpConfirm int32  `gorm:"column:sp_confirmtime;comment:平台确认时间"`
	SpResult  int32  `gorm:"column:sp_pay_result;comment:0: 未确认 1: 支付成功 -1:支付失败"`
}

func (this *InAppOrder) TableName() string {
	return "t_order"
}

func (this *InAppOrder) Create() error {
	if result := f5.GetApp().GetOrmDb(constant.PAY_DB).Create(this); result.Error != nil {
		return result.Error
	}
	return nil
}

func (this *InAppOrder) UpdateFields(fields []string) error {
	if result := f5.GetApp().GetOrmDb(constant.PAY_DB).Model(this).Select(
		fields).Updates(this); result.Error != nil {
		return result.Error
	}
	return nil
}

func (this *InAppOrder) Find(accountId string, orderId string) (error, bool) {
	err, ok := this.FindByOrderId(orderId)
	if err != nil {
		return err, false
	} else {
		return nil, ok && this.AccountId == accountId
	}
}

func (this *InAppOrder) FindByOrderId(orderId string) (error, bool) {
	if result := f5.GetApp().GetOrmDb(constant.PAY_DB).Table(this.TableName()).Take(
		this, "orderid = ?", orderId); result.Error != nil &&
		!errors.Is(result.Error, gorm.ErrRecordNotFound) {
		return result.Error, false
	} else {
		return nil, result.RowsAffected > 0
	}
}
