package service

import (
	"sws_xcx/models"
	"time"

	"github.com/jinzhu/gorm"
)

type ArticleService struct {
	artDb *gorm.DB
}

func NewArticleService() *ArticleService {
	return &ArticleService{artDb: ArtDB()}
}

func (s *ArticleService) GetArticleMenu(t int) (menus []*models.SyhArticlesMenu, err error) {

	db := s.artDb.Model(&models.SyhArticlesMenu{}).Where("status = ? ", 1)
	if t > 0 {
		db = db.Where("type = ?", t)
	}
	err = db.Order("`order` asc").Find(&menus).Error
	return
}
func (s *ArticleService) GetArticleByID(id int64) (article models.SyhArticlesVO, err error) {
	var art models.SyhArticles
	err = s.artDb.Model(&art).Where("id = ?", id).First(&art).Error
	article = MapArticlesVO(art)
	return
}
func MapArticlesVO(art models.SyhArticles) (article models.SyhArticlesVO) {
	article.ID = art.ID
	article.Title = art.Title
	article.Summary = art.Summary
	nt := time.Unix(int64(art.NewTime), 0)
	article.NewTime = models.Time(nt)
	ct := time.Unix(int64(art.Ctime), 0)
	article.Ctime = models.Time(ct)
	article.MenuID = art.MenuID
	article.Status = art.Status
	article.Img = art.Img
	article.Tags = art.Tags
	article.Content = art.Content
	article.Author = art.Author
	article.Reason = art.Reason
	article.FromID = art.FromID
	article.ClassID = art.ClassID
	article.ArticleType = art.ArticleType
	article.Type = art.Type
	article.TModule = art.TModule
	article.CommentNum = art.CommentNum
	article.Num = art.Num
	article.StarNum = art.StarNum
	article.IsDel = art.IsDel
	article.OrgID = art.OrgID
	return
}

func (s *ArticleService) GetRamdonArticleList(limit int) (articles []*models.SyhArticlesVO, err error) {
	var arts []models.SyhArticles
	err = s.artDb.Model(&models.SyhArticles{}).Where("status in(?,?) and is_del = 0", 1, 4).Order("ctime desc").Limit(limit).Find(&arts).Error
	articles = make([]*models.SyhArticlesVO, len(arts))
	for i, v := range arts {
		a := MapArticlesVO(v)
		articles[i] = &a
	}
	return
}

func (s *ArticleService) GetArticleList(pageNum, pageSize, menuId int, keyword string) (articles []*models.SyhArticlesVO, total int, err error) {
	offset := (pageNum - 1) * pageSize
	var arts []models.SyhArticles
	db := s.artDb.Model(&models.SyhArticles{}).Where("status in(?,?) and is_del = 0", 1, 4)
	if menuId > 0 {
		db = db.Where("menu_id = ?", menuId)
	}
	if keyword != "" {
		db = db.Where("title like ? or summary like ?", "%"+keyword+"%", "%"+keyword+"%")
	}
	err = db.Count(&total).Order("new_time desc").Offset(offset).Limit(pageSize).Find(&arts).Error
	articles = make([]*models.SyhArticlesVO, len(arts))
	for i, v := range arts {
		a := MapArticlesVO(v)
		articles[i] = &a
	}
	return
}
