package model

import (
	"leafstalk/otherutils/deepcopy"
	"strconv"
	"time"

	"xorm.io/xorm"
)

// 支付状态
const (
	PayStateNo        = 0 // 未支付
	PayStateNotify    = 1 // 已通知
	PayStatePayed     = 2 // 已支付
	PayStateCancle    = 3 // 已取消
	PayStateItemError = 4 // 购买的道具不对
)

// 扣款状态
const (
	DeductStateNo      = 0
	DeductStateSucess  = 1
	DeductStateUnKnown = 2
	DeductStateFail    = 3
)

// 发货状态
const (
	DeliverStateNo         = 0 //未发货
	DeliverStateSending    = 1 // 发货中
	DeliverStateSucess     = 2 // 已发货
	DeliverStateSucessMail = 3 // 已发货 邮件
	DeliverStateFail       = 4
	DeliverStateExcept     = 5
)

const (
	PayMethodForbid        = 0 // 禁止
	PayMethodNormal        = 1 // 正常
	PayMethodClientService = 2 // 客服
)

const (
	PhoneAndroid = 1 // 安卓
	PhoneIos     = 2 // 苹果
)

type TraceState struct {
	QueryTs   int64
	PayMethod int
}

type PayPlayer struct {
	Id          int64
	PlayerId    int64                  `xorm:"BIGINT index 'playerid'"`
	OpenId      string                 `xorm:"varchar(255) 'openId'"`
	GdtVid      string                 `xorm:"varchar(255) 'gdtVid'"`
	GateId      int64                  `xorm:"varchar(255) 'gateId'"`
	AdSrc       string                 `xorm:"varchar(255) 'adSrc'"`
	SessionKey  string                 `xorm:"varchar(255) 'sessionKey'"`
	TraceOrders map[string]*TraceState `xorm:"text 'traceOrders'"` // 游戏内订单 //最近支付订单 不用保存太多，最多50笔
	IP          string                 `xorm:"varchar(50) 'ip'"`
	// Friends           []int64  `xorm:"-"`
	// GameOutOrders map[string]int64 `xorm:"text 'outOrders'"` // 游戏外订单
}

func (m *PayPlayer) TableName() string {
	return "pay_player"
}

func (m *PayPlayer) QueryExist(eng *xorm.Engine) (bool, error) {
	q := new(PayPlayer)
	q.PlayerId = m.PlayerId
	return eng.Exist(q)
}

func (m *PayPlayer) UpdateDB(eng *xorm.Engine) (int64, error) {
	return eng.Where("playerid=?", m.PlayerId).AllCols().Update(m)
}

func (m *PayPlayer) GetUniqueKey() string {
	//return m.PlayerID
	return strconv.FormatInt(m.PlayerId, 10)
}

func CopyPayPlayer(old *PayPlayer) *PayPlayer {
	new1 := deepcopy.MustCopy(old).(*PayPlayer)
	return new1
}

// //0：苹果游戏外微信支付 1:安卓游戏内支付 2：安卓游戏外微信支付 3:苹果游戏内支付
// 订单信息
type NewPayOrder struct {
	Id            int64
	PlayerId      int64     `xorm:"BIGINT index 'playerid'"`
	Platform      string    `xorm:"varchar(10) 'platform'"`
	GoodsId       int64     `xorm:"BIGINT 'goodsId'"`
	OutTradeNo    string    `xorm:"varchar(255) index 'outTradeNo'"`
	PayMethod     int       `xorm:"int 'method'"` //支付方式 1:虚拟支付  2：游戏外支付
	PhoneType     int64     `xorm:"int 'phone'"`  // 1: 安卓;  2: 苹果
	OpenId        string    `xorm:"varchar(255) 'openId'"`
	PayState      int       `xorm:"int 'payState'"`     //支付状态 未支付 已通知 已支付
	DeductState   int       `xorm:"int 'deductState'"`  //扣费状态
	DeliverState  int       `xorm:"int 'deliverState'"` //发货状态
	Price         int64     `xorm:"BIGINT 'price'"`
	CreateTime    time.Time `xorm:"created"`
	QueryPayCount int64     `xorm:"-"`                    // 查询支付结果次数
	LastQueryTs   int64     `xorm:"BIGINT 'lastQueryTs'"` // 查询支付服务的时间戳
}

func (m *NewPayOrder) TableName() string {
	return "newpayorder"
}

func (m *NewPayOrder) QueryExist(eng *xorm.Engine) (bool, error) {
	q := new(NewPayOrder)
	q.OutTradeNo = m.OutTradeNo
	return eng.Exist(q)
}

func (m *NewPayOrder) UpdateDB(eng *xorm.Engine) (int64, error) {
	return eng.Where("outTradeNo=?", m.OutTradeNo).MustCols("state").Update(m)
}

func (m *NewPayOrder) GetUniqueKey() string {
	return m.OutTradeNo
}

func CopyWxPayOrder(old *NewPayOrder) *NewPayOrder {
	new1 := deepcopy.MustCopy(old).(*NewPayOrder)
	//*new1 = *old
	return new1
}

// 微信订单
type VirtualPayOrder struct {
	Id         int64
	PlayerId   int64     `xorm:"BIGINT index 'playerId'"`
	GoodsId    int64     `xorm:"BIGINT 'goodsId'"`          // 购买物品
	Price      int64     `xorm:"BIGINT 'price'"`            //价格
	State      int       `xorm:"int 'state'"`               //支付方式
	Platform   string    `xorm:"varchar(50) 'platform'"`    //平台 wx：微信 tt：抖音
	PayMethod  int       `xorm:"int 'payMethod'"`           //支付方式 //0：苹果游戏外微信支付 1:安卓游戏内支付 2：安卓游戏外微信支付 3:苹果游戏内支付
	PrePayNo   string    `xorm:"varchar(255) 'prePayNo'"`   //预支付订单号
	OutTradeNo string    `xorm:"varchar(255) 'outTradeNo'"` //支付订单号
	MchOrderNo string    `xorm:"varchar(255) 'mchOrderNo'"` //商户订单号
	Balance    int64     `xorm:"int 'balance'"`             //游戏币个数（包含赠送）
	SaveAmt    int64     `xorm:"int 'saveAmt'"`             //累计充值金额的游戏币数量
	PresentSum int64     `xorm:"int 'presentSum'"`          //历史累计收到赠送金额
	CreateTime time.Time `xorm:"created"`

	// SaveSum    int64     `xorm:"int 'saveSum'"`             //历史总游戏币金额
	// PayBalance int64     `xorm:"int 'payBalance'"`          //预扣后的余额
	// CostSum      int       `xorm:"int 'costSum'"`    //历史总消费游戏币金额
	// PresentSum   int       `xorm:"int 'presentSum'"` //历史累计收到赠送金额
	// GenBalance   int       `xorm:"int 'genBalance'"` //赠送游戏币数量（赠送游戏币数量
	// UsedGenAmt   int       `xorm:"int 'usedGenAmt'"`   //本次扣的赠送币的金额
	// Operation  string    `xorm:"varchar(255) 'operation'"`
}

func (m *VirtualPayOrder) TableName() string {
	return "virtualpayorder"
}

func (m *VirtualPayOrder) QueryExist(eng *xorm.Engine) (bool, error) {
	q := new(VirtualPayOrder)
	q.OutTradeNo = m.OutTradeNo
	return eng.Exist(q)
}

// 不许修改
func (m *VirtualPayOrder) UpdateDB(eng *xorm.Engine) (int64, error) {
	//return eng.Where("playerid=?", m.PlayerID).Update(m)
	return 0, nil
}

func (m *VirtualPayOrder) GetUniqueKey() string {
	return m.OutTradeNo
}

func CopyVirtualPayOrder(old *VirtualPayOrder) *VirtualPayOrder {
	new1 := deepcopy.MustCopy(old).(*VirtualPayOrder)
	return new1
}

type ItemPayOrder struct {
	Id            int64
	PlayerID      int64     `xorm:"BIGINT index 'playerid'"`
	OutTradeNo    string    `xorm:"varchar(255) 'outTradeNo'"`
	Price         int64     `xorm:"BIGINT 'price'"`
	GoodsId       int64     `xorm:"BIGINT 'goodsId'"`
	PayState      int64     `xorm:"int 'payState'"`
	DeliverState  int64     `xorm:"int 'deliverState'"`
	GameInState   int64     `xorm:"int 'gameInState'"` //游戏内支付状态
	PayTime       int64     `xorm:"BIGINT 'payTime'"`
	MchOrderNo    string    `xorm:"varchar(255) 'mchOrderNo'"`
	TransactionId string    `xorm:"varchar(255) 'transactionId'"`
	CreateTime    time.Time `xorm:"created"`
}

// IOS订单
type IosPayOrder struct {
	Id            int64
	PlayerId      int64     `xorm:"bigint index 'playerId'"`
	GoodsId       int64     `xorm:"BIGINT 'goodsId'"`
	OpenId        string    `xorm:"varchar(255) 'openId'"`
	OutTradeNo    string    `xorm:"varchar(100) 'outTradeNo'"`
	Total         int64     `xorm:"BIGINT 'total'"`
	TradeState    string    `xorm:"varchar(50) 'tradeState'"`
	TransactionId string    `xorm:"varchar(255) 'transactionId'"`
	PayerTotal    int64     `xorm:"BIGINT 'payerTotal'"`
	SuccessTime   string    `xorm:"varchar(255) 'successTime'"`
	PrepayId      string    `xorm:"varchar(255) 'prepayId'"`
	DeliverState  int       `xorm:"int default(0) 'deliver'"`
	CreateTime    time.Time `xorm:"created" redis:"-"`
	Platform      string    `xorm:"varchar(50) 'platform'"` // 微信； 抖音：
	PhoneType     int64     `xorm:"int 'phone'"`            //1:安卓手机; 2: 苹果手机
	PayUrl        string    `xorm:"-"`

	// GateId        int       `xorm:"int 'gateId'"`           //支付完，客户端查询时设置
	// QueryPayCount int64     `xorm:"-"`                    // 查询支付结果次数
	// LastQueryTs   int64     `xorm:"BIGINT 'lastQueryTs'"` // 查询支付服务的时间戳
	// LastQueryThirdTs  int64     `xorm:"-"`
	// Level         int       `xorm:"-"`
}

func (order IosPayOrder) TableName() string {
	return "wxpay_iosorder"
}

func (m *IosPayOrder) QueryExist(eng *xorm.Engine) (bool, error) {
	q := new(IosPayOrder)
	q.OutTradeNo = m.OutTradeNo
	return eng.Exist(q)
}

func (m *IosPayOrder) UpdateDB(eng *xorm.Engine) (int64, error) {
	return eng.Where("outTradeNo=?", m.OutTradeNo).Cols("tradeState", "transactionId", "payerTotal", "successTime", "state").Update(m)
}

func (m *IosPayOrder) GetUniqueKey() string {
	return m.OutTradeNo
}

func CopyIosPayOrder(old *IosPayOrder) *IosPayOrder {
	new1 := deepcopy.MustCopy(old).(*IosPayOrder) //new(IosPayOrder)
	// 	*new1 = *old
	return new1
}

type PlayerPayNotify struct {
	PlayerId   int64
	GateId     int64
	Platform   string
	OutTradeNo string
	SysCDRP    *CDRP
	PayMethod  int
	ToMail     int // 1: 邮箱中; 0: 背包中
}

// priceId int64,  , outTradeNo string, sysCDRP *CDRP
func NewPlayerPayNotify(playerId int64, gateId int64, plat string) *PlayerPayNotify {
	payNotify := new(PlayerPayNotify)
	payNotify.PlayerId = playerId
	payNotify.GateId = gateId
	payNotify.Platform = plat
	return payNotify
}

func (p *PlayerPayNotify) SetOrderInfo(outTradeNo string, payMethod int, sysCDRP *CDRP) {
	// p.PriceId = priceId
	p.OutTradeNo = outTradeNo
	p.SysCDRP = sysCDRP
	p.PayMethod = payMethod
}
func (p *PlayerPayNotify) GetPayPointId() int64 {
	return p.SysCDRP.Uid
}

// 玩家发货通知
type OrderDeliverResult struct {
	ErrCode    int // 见 model.DeliverStateFail
	PlayerId   int64
	GateId     int64
	OutTradeNo string
	PayMethod  int
}

// const (
// 	DeliverResultNormal = 0
// 	DeliverResultError  = 1
// 	DeliverResultExcept = 2
// )

func NewOrderDeliverResult(payNotify *PlayerPayNotify) *OrderDeliverResult {
	return &OrderDeliverResult{
		PlayerId:   payNotify.PlayerId,
		GateId:     payNotify.GateId,
		OutTradeNo: payNotify.OutTradeNo,
	}
}
