package user

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

type MessageType string

const (
	UnReadStatus     StatusType = "UNREAD"
	ReadStatus       StatusType = "READ"
	MaxBatchNum                 = 1000
	MyMessageColumns            = "id,source_id,type,message"
)

// UserMessage 表示 user_message 表的模型
type UserMessage struct {
	Id          int        `gorm:"primaryKey;autoIncrement;column:id"`
	AnalystId   int        `gorm:"column:analyst_id"`
	UserId      int        `gorm:"column:user_id"`
	SourceId    int        `gorm:"column:source_id"`
	Message     string     `gorm:"column:message"`
	Type        SourceType `gorm:"column:type;type:enum('REPORT','VIDEO','AUDIO')"`
	Status      StatusType `gorm:"column:status;type:enum('UNREAD','READ')"`
	CreatedTime time.Time  `gorm:"column:created_time;type:timestamps;comment:创建时间"`
	UpdatedTime time.Time  `gorm:"column:updated_time"`
}

func (u *UserMessage) BeforeCreate(_ *gorm.DB) (err error) {
	u.CreatedTime = time.Now()
	return
}

func CreateMessage(message UserMessage) (err error) {
	db := models.Main()
	return db.Create(&message).Error
}

func BatchInsertMessage(messages []UserMessage) bool {
	db := models.Main()
	//手动事务
	tx := db.Begin()
	err := db.CreateInBatches(messages, MaxBatchNum).Error
	if err != nil {
		logger.Error("批量插入消息失败:%v", err)
		tx.Rollback()
		return false
	}
	tx.Commit()
	return true
}

func NeedNotice(userId int, analystId int) bool {
	db := models.Main()
	var count int
	err := db.Model(&UserMessage{}).Select("count(*)").Where("user_id =? and analyst_id =? and status=?", userId, analystId, UnReadStatus).Scan(&count).Error
	if err != nil {
		logger.Error("统计未读消息失败:%v", err)
		return false
	}
	return count > 0
}

func GetUnReadMessageList(userId int) (messages []UserMessage, err error) {
	db := models.Main()
	err = db.Select(MyMessageColumns).Where("user_id=?  and status=?", userId, UnReadStatus).Order("created_time desc").Find(&messages).Error
	return
}

func ReadMessage(userId int, messageId int) bool {
	db := models.Main()
	err := db.Model(&UserMessage{}).Where("id=? and user_id=?", messageId, userId).Update("status", ReadStatus).Error
	if err != nil {
		return false
	}
	return true
}

func ReadMessages(userId int, analystId int) bool {
	db := models.Main()
	err := db.Model(&UserMessage{}).Where("user_id=? and analyst_id =?", userId, analystId).Update("status", ReadStatus).Error
	if err != nil {
		return false
	}
	return true
}
