package models

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

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"`
	LiveInfo     *LiveInfo `gorm:"foreignkey:LiveId" json:"live,omitempty"`
}

type LiveTitleRecordResp struct {
	Id           int    `json:"id"`
	LiveId       int    `json:"live_id"`
	CurrentTitle string `json:"current_title"`
	NewTitle     string `json:"new_title"`
	Status       uint8  `json:"status"`
	CreateTime   string `json:"create_time"`
	ApplyName    string `json:"apply_name"`
}

type LiveTitleRecordTemp struct {
	LiveTitleRecord
	CreatedTime string `json:"created_time,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.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["status"].(uint8),
		PlatformId:   data["platform_id"].(int64),
		CreateTime:   time.Now().UTC().Unix(),
	}

	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
}
