package manage

import (
	"demo/configs"
	"demo/data/domain"
	"demo/data/domain/vo"
)

func GetByIdArticleTag(id int) (domain.ArticleTag, error) {
	var articleTag domain.ArticleTag
	_, err := configs.Engine.Where("id = ?", id).Get(&articleTag)
	if err != nil {
		return articleTag, err
	}
	return articleTag, nil
}

func GetInIdListArticleTag(ids []int) ([]domain.ArticleTag, error) {
	rows, err := configs.Engine.In("id", ids).Rows(&domain.ArticleTag{})
	if err != nil {
		return make([]domain.ArticleTag, 0), err
	}
	defer rows.Close()
	var list []domain.ArticleTag
	for rows.Next() {
		var u domain.ArticleTag
		list = append(list, u)
	}
	return list, nil
}

func GetListArticleTag(articleTag domain.ArticleTag, pageNum, pageSize int) (vo.BaseListVo, error) {
	rows, err := configs.Engine.Limit(pageSize, (pageNum-1)*pageSize).Desc("id").Rows(&articleTag)
	var vo vo.BaseListVo
	if err != nil {
		return vo, err
	}
	vo.PageNum = pageNum
	vo.PageSize = pageSize
	vo.List = make([]any, 0)
	for rows.Next() {
		var u domain.ArticleTag
		rows.Scan(&u)
		vo.List = append(vo.List, u)
	}
	//查询数量
	count, err := configs.Engine.Count(&articleTag)
	vo.Total = int(count)
	return vo, nil
}

func SaveArticleTag(articleTag *domain.ArticleTag) (domain.ArticleTag, error) {
	_, err := configs.Engine.Insert(&articleTag)
	if err != nil {
		return *articleTag, err
	}
	return *articleTag, nil
}

func SetArticleTag(articleTagMap map[string]interface{}, id int) (domain.ArticleTag, bool, error) {
	var articleTag domain.ArticleTag
	_, err := configs.Engine.Table("article_tag").Where("id = ?", id).Update(articleTagMap)
	if err != nil {
		return articleTag, false, err
	}
	return articleTag, true, nil
}

func DeleteArticleTag(articleTag domain.ArticleTag) bool {
	i, err := configs.Engine.Where("id = ?", articleTag.Id).Delete(&articleTag)
	if err != nil {
		return false
	}
	return i > 0
}
