package manage

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

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

func GetInIdListArticle(ids []int) ([]domain.Article, error) {
	rows, err := configs.Engine.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
		list = append(list, u)
	}
	return list, nil
}

func GetListArticle(article domain.Article, pageNum, pageSize int) (vo.BaseListVo, error) {
	rows, err := configs.Engine.Limit(pageSize, (pageNum-1)*pageSize).Desc("id").Rows(&article)
	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.Article
		rows.Scan(&u)
		vo.List = append(vo.List, u)
	}
	//查询数量
	count, err := configs.Engine.Count(&article)
	vo.Total = int(count)
	return vo, nil
}

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

func SetArticle(articleMap map[string]interface{}, id int) (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(article domain.Article) bool {
	i, err := configs.Engine.Where("id = ?", article.Id).Delete(&article)
	if err != nil {
		return false
	}
	return i > 0
}
