package models

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

type LiveTitleRecord struct {
	Model

	LiveId       int       `json:"live_id"`
	CurrentTitle string    `json:"current_title"`
	NewTitle     string    `json:"new_title"`
	Status       uint8     `json:"status"`
	PlatformId   int64     `json:"platform_id,omitempty"`
	CreateTime   int64     `json:"create_time,omitempty"`
	CreatedTime  string    `json:"created_time,omitempty"`
	ApplyId      uint32    `json:"apply_id"`
	LiveInfo     *LiveInfo `gorm:"foreignkey:LiveId" json:"live,omitempty"`
}

func (w LiveTitleRecord) TableName() string {
	return setting.DatabaseSetting.Name_Sources + ".wallet_live_title_record"
}

func ExistLiveTitleRecordById(id int) (bool, error) {
	var live LiveTitleRecord
	err := db.Select("id").Where("id = ?", id).First(&live).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}

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

	return false, nil
}

func GetLiveTitleRecordTotal(maps interface{}) (int, error) {
	var count int

	if err := db.Model(&LiveTitleRecord{}).Where(maps).Count(&count).Error; err != nil {
		return 0, err
	}

	return count, nil
}

func GetRecord(id int) (*LiveTitleRecord, error) {
	var record LiveTitleRecord
	err := db.Where("id = ?", id).First(&record).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	err = db.Model(&record).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return &record, nil
}

func GetLiveTitleRecord(pageNum, pageSize int, maps interface{}) ([]*LiveTitleRecord, error) {
	var live []*LiveTitleRecord
	err := db.Debug().Where(maps).Preload("LiveInfo").Order("create_time desc").Offset(pageNum).Limit(pageSize).Find(&live).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return live, nil
}

func AddLiveTitleRecord(data map[string]interface{}) (error) {
	live := LiveTitleRecord{
		LiveId:       data["live_id"].(int),
		CurrentTitle: data["current_title"].(string),
		NewTitle:     data["new_title"].(string),
		Status:       data["sort"].(uint8),
		PlatformId:   data["platform_id"].(int64),
		CreateTime:   data["create_time"].(int64),
	}

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

	return nil
}

func EditLiveTitleRecord(id int, data interface{}) error {
	if err := db.Model(&LiveTitleRecord{}).Where("id = ?", id).Updates(data).Error; err != nil {
		return err
	}

	return nil
}
