package orchard

import (
	"active/tools"
	"gorm.io/gorm"
)

type OrchardMsg struct {
	Id         int64  `json:"id"`
	CreateTime int64  `json:"create_time"`
	PlayerId   int64  `json:"player_id"`
	Msg        string `json:"msg"`
	UserId     int64  `json:"user_id"`
	IsRead     bool   `json:"is_read"`
}

func (this *OrchardMsg) TableName() string {
	return "orchard_msg"
}

func GetRecentMsgList(userid int64, open bool) (*[]OrchardMsg, int64) {
	var orchardMsgList []OrchardMsg
	db := tools.NewConn(MysqlExtDb)
	var odInt []int64
	db.Where("user_id = ?", userid).Order("create_time desc").Limit(OrchardConf.Limit).Find(&orchardMsgList)
	for i := range orchardMsgList {
		if !orchardMsgList[i].IsRead {
			odInt = append(odInt, orchardMsgList[i].Id)
		}
	}
	if len(odInt) > 0 && open {
		index := 0
		for index < len(odInt) {
			if index+20 < len(odInt) {
				db.Table(orchardMsgList[0].TableName()).Where("id in ?", odInt[index:index+20]).Update("is_read", true)
			} else {
				db.Table(orchardMsgList[0].TableName()).Where("id in ?", odInt[index:]).Update("is_read", true)
			}
			index += 20
		}
	}

	return &orchardMsgList, int64(len(odInt))
}

func (this *OrchardMsg) Insert(db *gorm.DB) error {
	//db := tools.NewConn(MysqlExtDb)
	return db.Create(this).Error
}
