package user

import (
	"encoding/json"
	logger "eta/eta_mini_ht_api/common/component/log"
	userDao "eta/eta_mini_ht_api/models/user"
	"fmt"
	"strconv"
	"strings"
)

type MessageDTO struct {
	From    int    `gorm:"column:from"`
	To      int    `gorm:"column:to"`
	Message string `gorm:"column:message"`
	Type    string `gorm:"column:type;type:enum('REPORT','VIDEO','AUDIO')"`
	Status  string `gorm:"column:status;type:enum('UNREAD','READ')"`
}

type MyMessage struct {
	Id       int    `json:"messageId"`
	SourceId int    `json:"SourceId"`
	Type     string `json:"Type"`
	Message  string `json:"Message"`
}

const (
	ReportMessageTemplate = "您关注的研究员%v更新了一篇报告"
	VideoMessageTemplate  = "您关注的研究员%v更新了一个视频"
	AudioMessageTemplate  = "您关注的研究员%v更新了一个音频"
)

type MessageInfo struct {
	analyst string
}

func CreateMessage(meta MetaInfoDTO) (err error) {
	messageType := userDao.SourceType(meta.SourceType)
	var messageList []userDao.UserMessage
	users := strings.Split(meta.To, ",")
	var message string
	var content MetaData
	err = json.Unmarshal([]byte(meta.Meta), &content)
	if err != nil {
		logger.Error("生成消息信息失败:%v", err)
		userDao.FailedMetaInfo(meta.Id)
	}
	switch userDao.SourceType(meta.SourceType) {
	case userDao.ReportSourceType:
		message = fmt.Sprintf(ReportMessageTemplate, content.AuthorName)
		messageType = userDao.ReportSourceType
	case userDao.VideoSourceType:
		message = fmt.Sprintf(VideoMessageTemplate, content.AuthorName)
	case userDao.AudioSourceType:
		message = fmt.Sprintf(AudioMessageTemplate, content.AuthorName)
	}
	for _, user := range users {
		id, _ := strconv.Atoi(user)
		userMessage := userDao.UserMessage{
			AnalystId: content.AuthorId,
			UserId:    id,
			Message:   message,
			SourceId:  content.SourceId,
			Type:      messageType,
			Status:    userDao.UnReadStatus,
		}
		messageList = append(messageList, userMessage)
	}
	if userDao.BatchInsertMessage(messageList) {
		userDao.FinishMetaInfo(meta.Id)
	} else {
		logger.Error("生成消息信息失败:%v", err)
		userDao.FailedMetaInfo(meta.Id)
	}
	return
}

func NeedNotice(userId int, analystId int) bool {
	return userDao.NeedNotice(userId, analystId)
}

func ReadMessage(userId int, messageId int) bool {
	return userDao.ReadMessage(userId, messageId)
}
func ReadMessages(userId int, analystId int) bool {
	return userDao.ReadMessages(userId, analystId)
}
func GetUnReadMessageList(userId int) (messageList []MyMessage, err error) {
	list, err := userDao.GetUnReadMessageList(userId)
	if err != nil {
		logger.Error("获取我的未读消息失败:%v", err)
		return
	}
	for _, message := range list {
		messageList = append(messageList, convertToMyMessage(message))
	}
	return
}

func convertToMyMessage(message userDao.UserMessage) MyMessage {
	return MyMessage{
		Id:       message.Id,
		SourceId: message.SourceId,
		Type:     string(message.Type),
		Message:  message.Message,
	}
}
