package user

import (
	logger "eta/eta_mini_ht_api/common/component/log"
	"eta/eta_mini_ht_api/models"
	"gorm.io/gorm"
	"time"
)

type StatusType string
type SourceType string
type MetaType string

const (
	UserNoticeType    MetaType   = "USER_NOTICE"
	InitStatusType    StatusType = "INIT"
	PendingStatusType StatusType = "PENDING"
	FinishStatusType  StatusType = "FINISH"
	FailedStatusType  StatusType = "FAILED"

	ReportSourceType SourceType = "REPORT"
	VideoSourceType  SourceType = "VIDEO"
	AudioSourceType  SourceType = "AUDIO"
)

// MetaInfo 表示 meta_infos 表的模型
type MetaInfo struct {
	Id          int        `gorm:"primaryKey;autoIncrement;column:id"`
	Uid         string     `gorm:"column:uid"`
	Meta        string     `gorm:"column:meta"`
	From        string     `gorm:"column:from"`
	To          string     `gorm:"column:to"`
	SourceType  SourceType `gorm:"column:source_type;type:enum('REPORT','VIDEO','AUDIO')"`
	MetaType    MetaType   `gorm:"column:meta_type;type:enum('USER_NOTICE')"`
	Status      StatusType `gorm:"column:status;type:enum('INIT','PENDING','FINISH','FAILED')"`
	CreatedTime time.Time
	UpdatedTime time.Time
}

func (mt *MetaInfo) BeforeCreate(_ *gorm.DB) (err error) {
	mt.CreatedTime = time.Now()
	mt.Status = InitStatusType
	return nil
}

func CreateMetaInfo(metaInfo MetaInfo) (err error) {
	db := models.Main()
	return db.Create(&metaInfo).Error
}

func GetInitMetaInfos() (list []MetaInfo) {
	db := models.Main()
	err := db.Where("status = ?", InitStatusType).Order("id asc").Limit(100).Find(&list).Error
	if err != nil {
		logger.Error("获取meta数据失败:%v", err)
		return []MetaInfo{}
	}
	return list
}

func PendingMetaInfo(id int) bool {
	return updateStatus(id, PendingStatusType)
}

func FinishMetaInfo(id int) bool {
	return updateStatus(id, FinishStatusType)
}
func FailedMetaInfo(id int) bool {
	return updateStatus(id, FailedStatusType)
}

func updateStatus(id int, status StatusType) bool {
	db := models.Main()
	err := db.Model(&MetaInfo{}).Where("id = ?", id).Update("status", status).Error
	if err != nil {
		logger.Error("更新meta数据失败:%v", err)
		return false
	}
	return true
}
