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 BookAuthorService struct{}

func (s *BookAuthorService) CreateBookAuthor(item book.BookAuthor) error {
	if err := validateBookAuthor(item); err != nil {
		return err
	}
	return global.GVA_DB.Create(&item).Error
}

func (s *BookAuthorService) DeleteBookAuthor(item book.BookAuthor) error {
	return global.GVA_DB.Delete(&item).Error
}

func (s *BookAuthorService) DeleteBookAuthorByIds(ids commonReq.IdsReq) error {
	return deleteByIDs[book.BookAuthor](ids.Ids)
}

func (s *BookAuthorService) UpdateBookAuthor(item book.BookAuthor) error {
	if err := validateBookAuthor(item); err != nil {
		return err
	}
	return global.GVA_DB.Save(&item).Error
}

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

func (s *BookAuthorService) GetBookAuthorInfoList(info bookReq.BookAuthorSearch) (list []book.BookAuthor, total int64, err error) {
	db := global.GVA_DB.Model(&book.BookAuthor{})
	if info.Name != "" {
		db = db.Where("name LIKE ?", "%"+info.Name+"%")
	}
	if info.Keyword != "" {
		db = db.Where("name LIKE ?", "%"+info.Keyword+"%")
	}
	if info.AuthorStatus != "" {
		db = db.Where("author_status = ?", info.AuthorStatus)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Scopes(paginate(info.PageInfo)).Order("id desc").Find(&list).Error
	return
}
