package yb_message

import (
	"hongze/hongze_yb/global"
	"hongze/hongze_yb/utils"
)

// GetUnreadByUserId 获取用户的未读数
func GetUnreadByUserId(UserId uint64) (total int64, err error) {
	err = global.DEFAULT_MYSQL.Model(YbMessage{}).
		Where("user_id = ? and enabled = 1 and is_read=0", UserId).
		Count(&total).Error
	return
}

// GetListByType 根据消息类型查询用户消息列表
func GetListByType(userId uint64, msgType int, offset, limit int) (list []*YbMessage, err error) {
	var pars []interface{}
	pars = append(pars, userId)
	sql := ` SELECT * FROM yb_message 
WHERE user_id = ? and enabled = 1 `
	if msgType > 0 {
		sql += " and type= ?"
		pars = append(pars, msgType)
	}
	sql += " GROUP BY create_time desc, msg_id desc LIMIT ?,? "
	pars = append(pars, offset, limit)
	err = global.DEFAULT_MYSQL.Raw(sql, pars...).Scan(&list).Error
	return
}

// GetListTotalByType 根据消息类型查询用户消息列表总数
func GetListTotalByType(userId uint64, msgType int) (total int64, err error) {
	var pars []interface{}
	pars = append(pars, userId)
	sql := ` SELECT count(*) FROM yb_message 
WHERE user_id = ? and enabled = 1 `
	if msgType > 0 {
		sql += " and type= ?"
		pars = append(pars, msgType)
	}
	err = global.DEFAULT_MYSQL.Raw(sql, pars...).Count(&total).Error
	return
}

// GetMsgByMsgId 根据消息ID查询消息详情
func GetMsgByMsgId(userId, msgId uint64) (item *YbMessage, err error) {
	err = global.DEFAULT_MYSQL.Model(YbMessage{}).
		Where("user_id = ? and msg_id = ?", userId, msgId).
		First(&item).Error
	if err == utils.ErrNoRow {
		err = nil
	}
	return
}
