package manage

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

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

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

func GetArticleTopicList(articleTopic domain.ArticleTopic, pageNum, pageSize int) (vo.BaseListVo, error) {
	var arr []domain.ArticleTopic
	Count, err := configs.Engine.Table("article_topic").Limit(pageSize, (pageNum-1)*pageSize).FindAndCount(&arr, &articleTopic)
	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 SaveArticleTopic(articleTopic *domain.ArticleTopic) (domain.ArticleTopic, error) {
	_, err := configs.Engine.Table("article_topic").Insert(&articleTopic)
	if err != nil {
		return *articleTopic, err
	}
	return *articleTopic, nil
}

func SetArticleTopic(articleTopicMap map[string]interface{}, id int64) (domain.ArticleTopic, bool, error) {
	var articleTopic domain.ArticleTopic
	_, err := configs.Engine.Table("article_topic").Where("id = ?", id).Update(articleTopicMap)
	if err != nil {
		return articleTopic, false, err
	}
	return articleTopic, true, nil
}

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