package models

import (
	orm "go-admin/common/global"
	"go-admin/logger"
)

type Article struct {
	Model

	Title       string `json:"title"`
	SubTitle    string `json:"sub_title"`
	IconUrl     string `json:"icon_url"`
	Content     string `json:"content"`
	SourceName  string `json:"source_name"`
	SourceUrl   string `json:"source_url"`
	ReadCount   uint32 `json:"read_count"`
	ThumbsCount uint32 `json:"thumbs_count"`
	Status      uint32 `json:"status"`
	ColumnType  int    `json:"column_type"` // 1-攻略 2-新闻
}

type ArticleCollect struct {
	Model

	ArticleId  uint32 `json:"article_id"`
	Uid        uint32 `json:"uid"`
	ColumnType int    `json:"column_type"` // 1-攻略 2-新闻
}

func (m *Article) TableName() string {
	return "article"
}

type ArticleListReq struct {
	Title    string `json:"title"`
	Status   uint32 `json:"status"`
	Column   int    `json:"column_type"`
	PageIdx  int    `json:"pageIndex"`
	PageSize int    `json:"pageSize"`
}

func (m *ArticleListReq) GetArticleList() ([]Article, int64, error) {
	page := m.PageIdx - 1
	if page < 0 {
		page = 0
	}
	if m.PageSize == 0 {
		m.PageSize = 10
	}
	var articles []Article
	qs := orm.Eloquent.Table("article")
	if m.Title != "" {
		qs = qs.Where("title LIKE '%" + m.Title + "%'")
	}
	if m.Status != 0 {
		qs = qs.Where("status = ?", m.Status)
	}
	if m.Column != 0 {
		qs = qs.Where("column_type = ?", m.Column)
	}

	var count int64
	err := qs.Count(&count).Error
	if err != nil {
		logger.Error(err.Error())
		return articles, 0, err
	}

	err = qs.Order("id desc").Offset(page * m.PageSize).Limit(m.PageSize).Find(&articles).Error
	if err != nil {
		logger.Error(err.Error())
		return articles, count, err
	}
	return articles, count, nil
}
