package models

import (
	"bwallet/pkg/setting"
	"github.com/jinzhu/gorm"
	"time"
)

type RedPacket struct {
	Model

	PacketId   string  `json:"packet_id"`
	LiveId     int32   `json:"live_id"`
	Avatar     string  `json:"avatar"`
	Receive    string  `json:"receive"`
	UserId     string  `json:"user_id"`
	UserName   string  `json:"user_name"`
	UserMobile string  `json:"user_mobile"`
	PlatformId string  `json:"platform_id"`
	Type       uint8   `json:"type"`
	CoinId     int32   `json:"coin_id"`
	CoinName   string  `json:"coin_name"`
	Amount     float32 `json:"amount"`
	Size       uint8   `json:"size"`
	To         string  `json:"to"`
	Remain     uint8   `json:"remain"`
	Status     uint8   `json:"status"`
	Remark     string  `json:"remark"`
	CreateAt   int32   `json:"create_at"`
	UpdateAt   int32   `json:"update_at"`
	ExpireAt   int32   `json:"expire_at"`
}

func (c RedPacket) TableName() string {
	return setting.DatabaseSetting.Name_Sources + ".wallet_red_packet"
}

func ExistByPacketInfoId(packet_id string) (bool, error) {
	var red_packet_info RedPacket
	err := db.Select("id").Where("packet_id = ?", packet_id).First(&red_packet_info).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}

	if red_packet_info.ID > 0 {
		return true, nil
	}

	return false, nil
}

func GetRedPackets(maps interface{}) ([]*RedPacket, error) {
	var redPackets []*RedPacket
	err := db.Where(maps).Find(&redPackets).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return redPackets, nil
}

func GetRedPacketsForReceive() ([]*RedPacket, error) {
	var redPackets []*RedPacket
	status_map := [] int{1, 2, 4}
	if err := db.Where("status in (?)", status_map).Where("expire_at > (?)", time.Now().UTC().Unix()).Find(&redPackets).Error; err != nil {
		return nil, err
	}

	return redPackets, nil
}

func AddRedPacket(data map[string]interface{}) (error) {
	redPacket := RedPacket{
		PacketId:   data["packet_id"].(string),
		LiveId:     data["live_id"].(int32),
		Avatar:     data["avatar"].(string),
		Receive:    data["receive"].(string),
		UserId:     data["user_id"].(string),
		UserName:   data["user_name"].(string),
		UserMobile: data["user_mobile"].(string),
		PlatformId: data["platform_id"].(string),
		Type:       data["type"].(uint8),
		CoinId:     data["coin_id"].(int32),
		CoinName:   data["coin_name"].(string),
		Amount:     data["amount"].(float32),
		Size:       data["size"].(uint8),
		To:         data["to"].(string),
		Remain:     data["remain"].(uint8),
		Status:     data["status"].(uint8),
		Remark:     data["remark"].(string),
		CreateAt:   data["create_at"].(int32),
		UpdateAt:   data["update_at"].(int32),
		ExpireAt:   data["expire_at"].(int32),
	}

	if err := db.Create(&redPacket).Error; err != nil {
		return err
	}

	return nil
}

func EditRedPacket(maps interface{}, data interface{}) error {
	if err := db.Model(&RedPacket{}).Where(maps).Updates(data).Error; err != nil {
		return err
	}

	return nil
}
