package manage

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

func GetArticleById(id int64) (domain.Article, error) {
	var article domain.Article
	_, err := configs.Engine.Table("article").Where("id = ?", id).Get(&article)
	if err != nil {
		return article, err
	}
	return article, nil
}

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

func GetArticleList(article domain.Article, pageNum, pageSize int) (vo.BaseListVo, error) {
	var arr []domain.Article
	Count, err := configs.Engine.Table("article").Limit(pageSize, (pageNum-1)*pageSize).FindAndCount(&arr, &article)
	var vo vo.BaseListVo
	if err != nil {
		return vo, err
	}
	if err != nil {
		return vo, err
	}
	vo.PageNum = pageNum
	vo.PageSize = pageSize
	vo.List = make([]any, len(arr))
	for i, v := range arr {
		vo.List[i] = v
	}
	vo.Total = int(Count)
	return vo, nil
}

func SaveArticle(article *domain.Article) (domain.Article, error) {
	_, err := configs.Engine.Table("article").Insert(&article)
	if err != nil {
		return *article, err
	}
	return *article, nil
}

func SetArticle(articleMap map[string]interface{}, id int64) (domain.Article, bool, error) {
	var article domain.Article
	_, err := configs.Engine.Table("article").Where("id = ?", id).Update(articleMap)
	if err != nil {
		return article, false, err
	}
	return article, true, nil
}

func DeleteArticle(id int64) bool {
	var article domain.Article
	i, err := configs.Engine.Table("article").Where("id = ?", id).Delete(&article)
	if err != nil {
		return false
	}
	return i > 0
}
