package book

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/book"
	bookReq "github.com/flipped-aurora/gin-vue-admin/server/model/book/request"
	commonReq "github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
)

type BookService struct{}

func (s *BookService) CreateBook(item book.Book) error {
	if err := validateBook(item); err != nil {
		return err
	}
	return global.GVA_DB.Create(&item).Error
}

func (s *BookService) DeleteBook(item book.Book) error { return global.GVA_DB.Delete(&item).Error }

func (s *BookService) DeleteBookByIds(ids commonReq.IdsReq) error {
	return deleteByIDs[book.Book](ids.Ids)
}

func (s *BookService) UpdateBook(item book.Book) error {
	if err := validateBook(item); err != nil {
		return err
	}
	return global.GVA_DB.Save(&item).Error
}

func (s *BookService) GetBook(id uint) (item book.Book, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&item).Error
	return
}

func (s *BookService) GetBookInfoList(info bookReq.BookSearch) (list []book.Book, total int64, err error) {
	db := global.GVA_DB.Model(&book.Book{})
	if info.Title != "" {
		db = db.Where("title LIKE ?", "%"+info.Title+"%")
	}
	if info.Keyword != "" {
		db = db.Where("title LIKE ? OR subtitle LIKE ?", "%"+info.Keyword+"%", "%"+info.Keyword+"%")
	}
	if info.BookType != "" {
		db = db.Where("book_type = ?", info.BookType)
	}
	if info.EraTag != "" {
		db = db.Where("era_tag = ?", info.EraTag)
	}
	if info.CompletionStatus != "" {
		db = db.Where("completion_status = ?", info.CompletionStatus)
	}
	if info.PublishStatus != "" {
		db = db.Where("publish_status = ?", info.PublishStatus)
	}
	if info.SeriesID != nil {
		db = db.Where("series_id = ?", *info.SeriesID)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Scopes(paginate(info.PageInfo)).Order("id desc").Find(&list).Error
	return
}
