package autocode

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/autocode"
	autoCodeReq "github.com/flipped-aurora/gin-vue-admin/server/model/autocode/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
	"gorm.io/gorm"
)

type ReadCountService struct {
}

// CreateReadCount 创建ReadCount记录
// Author [piexlmax](https://github.com/piexlmax)
func (readCountService *ReadCountService) CreateReadCount(readCount autocode.ReadCount) (err error) {
	err = global.GVA_DB.Create(&readCount).Error
	return err
}

// DeleteReadCount 删除ReadCount记录
// Author [piexlmax](https://github.com/piexlmax)
func (readCountService *ReadCountService) DeleteReadCount(readCount autocode.ReadCount) (err error) {
	err = global.GVA_DB.Delete(&readCount).Error
	return err
}

// DeleteReadCountByIds 批量删除ReadCount记录
// Author [piexlmax](https://github.com/piexlmax)
func (readCountService *ReadCountService) DeleteReadCountByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]autocode.ReadCount{}, "id in ?", ids.Ids).Error
	return err
}

// UpdateReadCount 更新ReadCount记录
// Author [piexlmax](https://github.com/piexlmax)
func (readCountService *ReadCountService) UpdateReadCount(readCount autocode.ReadCount) (err error) {
	err = global.GVA_DB.Save(&readCount).Error
	return err
}

// GetReadCount 根据id获取ReadCount记录
// Author [piexlmax](https://github.com/piexlmax)
func (readCountService *ReadCountService) GetReadCountByUserId(userId int, problemId int) (err error, readCount autocode.ReadCount) {
	err = global.GVA_DB.Where("user_id = ?", userId).Where("problem_id = ?", problemId).First(&readCount).Error
	return
}

func (readCountService *ReadCountService) UpdateReadCountBy(id uint) (err error) {
	err = global.GVA_DB.Model(&autocode.ReadCount{}).Where("id=?", id).Update("count", gorm.Expr("count+1")).Error
	return err
}

func (readCountService *ReadCountService) GetReadCount(id uint) (err error, readCount autocode.ReadCount) {
	err = global.GVA_DB.Where("id = ?", id).First(&readCount).Error
	return
}

// GetReadCountInfoList 分页获取ReadCount记录
// Author [piexlmax](https://github.com/piexlmax)
func (readCountService *ReadCountService) GetReadCountInfoList(info autoCodeReq.ReadCountSearch) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&autocode.ReadCount{})
	var readCounts []autocode.ReadCount
	db.Where("problem_id = ?", info.ProblemId)
	// 如果有条件搜索 下方会自动创建搜索语句
	err = db.Count(&total).Error
	err = db.Limit(limit).Offset(offset).Find(&readCounts).Error
	return err, readCounts, total
}
