package model

import (
	"time"

	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"gogs.daxia.dev/huanan/pkg.daxia.dev/db"
)

type GameOpenLogQP struct {
	ID        uint `gorm:"primarykey"`
	CreatedAt time.Time
	UpdatedAt time.Time

	Issue       string `gorm:"type:varchar(25);comment:'期号'"`
	RoomID      int32  `gorm:"type:int;comment:'房间ID'"`
	RoomType    int32  `gorm:"type:int;comment:'房间类型'"`
	GameID      int32  `gorm:"type:int;comment:'游戏ID'"`
	GameName    string `gorm:"type:varchar(255);comment:'游戏名称'"`
	DayStr      string `gorm:"type:varchar(255);comment:'日期'"`
	Index       int32  `gorm:"type:int;comment:'开奖索引'"`
	OpenNumber1 string `gorm:"type:varchar(255);comment:'开奖号码1'"`
	OpenNumber2 string `gorm:"type:varchar(255);comment:'开奖号码2'"`
	OpenNumber3 string `gorm:"type:varchar(255);comment:'开奖号码3'"`
	OpenNumber4 string `gorm:"type:varchar(255);comment:'开奖号码4'"`
	OpenNumber5 string `gorm:"type:varchar(255);comment:'开奖号码5'"`
	Hash        string `gorm:"type:varchar(255);comment:'开奖hash'"`
	OpenTime    *time.Time
	IsOpen      int32 `gorm:"type:int;comment:'是否开放搜索'"`
}

func (GameOpenLogQP) TableName() string {
	return "game_open_log_qp"
}

func (p GameOpenLogQP) Init() error {
	var err error

	if db.GetDB().Migrator().HasTable(p) {
		return nil
	}

	err = db.GetDB().Migrator().CreateTable(p)
	if err != nil {
		logrus.Fatal(err)
		return err
	}

	err = db.GetDB().Exec("create unique index idx_game_id_issue on game_open_log_qp (game_id, issue)").Error
	if err != nil {
		return err
	}

	return nil
}

func (p *GameOpenLogQP) GetByIssue(issueStr string) error {
	gameID := viper.GetInt32("game_id")

	err := db.GetDB().Model(p).Where("game_id = ? and issue = ?", gameID, issueStr).First(p).Error
	if err != nil {
		logrus.Error(err)
		return err
	}

	return nil
}

func (p GameOpenLogQP) GetListByIssueList(issueStrList []string) ([]GameOpenLogQP, error) {
	gameID := viper.GetInt32("game_id")

	GameOpenLogQPListModel := make([]GameOpenLogQP, 0)
	err := db.GetDB().Model(p).Where("game_id = ? and issue in ?", gameID, issueStrList).Scan(&GameOpenLogQPListModel).Error
	if err != nil {
		logrus.Error(err)
		return nil, err
	}

	return GameOpenLogQPListModel, nil
}

func (p GameOpenLogQP) Exists(issueStr string) (bool, error) {
	var err error
	gameID := viper.GetInt32("game_id")

	count := int64(0)
	err = db.GetDB().Model(p).Where("issue = ? and game_id = ?", issueStr, gameID).Count(&count).Error
	if err != nil {
		logrus.Error(err, issueStr)
		return false, err
	}

	return count != 0, nil
}
