package advisory

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"github.com/rdlucklib/rdluck_tools/paging"
	"time"
)

type AdvisoryArticle struct {
	ArticleId           int       `orm:"column(advisory_article_id);pk"`
	Title               string    `description:"标题"`
	Body                string    `description:"内容"`
	Abstract            string    `description:"简介"`
	PublishStatus       int       `description:"发布状态1已发布、0未发布"`
	ChartPermissionId   int       `description:"所属分类ID"`
	ChartPermissionName string    `description:"所属分类名称"`
	ActualPublishTime   time.Time `description:"实际发布时间"`
	TimingPublishTime   time.Time `description:"定时发布时间"`
	LinkName            string    `description:"链接名称"`
	LinkAddress         string    `description:"链接地址"`
	CreateTime          time.Time `description:"创建时间"`
	LastUpdateTime      time.Time `description:"修改时间"`
	AdminId             int       `description:"发布者的用户ID"`
	IsTiming            int       `description:"是否定时发布，1，定时发布，0不定时"`
	Code                string    `description:"分享字符串"`
}

type AdvisoryArticleLog struct {
	ArticleId           int       `orm:"column(advisory_article_id);pk"`
	Title               string    `description:"标题"`
	Body                string    `description:"内容"`
	Abstract            string    `description:"简介"`
	PublishStatus       int       `description:"发布状态1已发布、0未发布"`
	ChartPermissionId   int       `description:"所属分类ID"`
	ChartPermissionName string    `description:"所属分类名称"`
	ActualPublishTime   time.Time `description:"实际发布时间"`
	TimingPublishTime   time.Time `description:"定时发布时间"`
	LinkName            string    `description:"链接名称"`
	LinkAddress         string    `description:"链接地址"`
	CreateTime          time.Time `description:"创建时间"`
	LastUpdateTime      time.Time `description:"修改时间"`
	AdminId             int       `description:"发布者的用户ID"`
}

//文章详情
type AdvisoryArticleDetail struct {
	ArticleId           int    `orm:"column(advisory_article_id);pk"`
	Title               string `description:"标题"`
	Body                string `description:"内容"`
	Abstract            string `description:"简介"`
	PublishStatus       int    `description:"发布状态1已发布、0未发布"`
	ChartPermissionId   int    `description:"所属分类ID"`
	ChartPermissionName string `description:"所属分类名称"`
	ActualPublishTime   string `description:"实际发布时间"`
	TimingPublishTime   string `description:"定时发布时间"`
	LinkName            string `description:"链接名称"`
	LinkAddress         string `description:"链接地址"`
	CreateTime          string `description:"创建时间"`
	LastUpdateTime      string `description:"修改时间"`
	AdminId             int    `description:"发布者的用户ID"`
	Code                string `description:"分享字符串"`
	ArtCode             string `orm:"column(code);"`
}

//预览文章详情带文章所属分类
type PreviewArticleDetail struct {
	WhatWeek            string `description:"周几"`
	ArticleId           int    `orm:"column(advisory_article_id);pk"`
	Title               string `description:"标题"`
	Body                string `description:"内容"`
	ChartPermissionId   int    `description:"所属分类ID"`
	ChartPermissionName string `description:"所属分类名称"`
	LinkName            string `description:"链接名称"`
	LinkAddress         string `description:"链接地址"`
	TimingPublishTime   string `description:"定时发布时间"`
	PublishStatus       int    `description:"发布状态1已发布、0未发布"`
	//ClassifyChartPermissionName string `description:"所属一级分类名称"`
	ActualPublishTime string `description:"实际发布时间"`
	LastUpdateTime    string `description:"上次编辑的时间"`
	Pv                int    `description:"PV"`
	Uv                int    `description:"UV"`
}

type PreviewArticleDetailList struct {
	List []*PreviewArticleDetail
}

type ArticleAddReq struct {
	ArticleId           int    `orm:"column(advisory_article_id);pk"`
	Title               string `description:"标题"`
	Body                string `description:"内容"`
	Abstract            string `description:"文章个简介"`
	ChartPermissionId   int    `description:"所属分类ID"`
	ChartPermissionName string `description:"所属分类名称"`
	TimingPublishTime   string `description:"定时发布时间"`
	LinkName            string `description:"链接名称"`
	LinkAddress         string `description:"链接地址"`
}

//保存文章
type PreservationArticle struct {
	ArticleId           int    `orm:"column(advisory_article_id);pk"`
	Title               string `description:"标题"`
	Body                string `description:"内容"`
	Abstract            string `description:"文章个简介"`
	ChartPermissionId   int    `description:"所属分类ID"`
	ChartPermissionName string `description:"所属分类名称"`
	TimingPublishTime   string `description:"定时发布时间"`
	LinkName            string `description:"链接名称"`
	LinkAddress         string `description:"链接地址"`
}

type ArticleDeleteReq struct {
	ArticleId int64 `description:"ArticleId"`
}

//添加文章
func AddArticle(item *AdvisoryArticle) (newId int64, err error) {
	fmt.Println(item)
	o := orm.NewOrm()
	newId, err = o.Insert(item)
	fmt.Println(newId)
	return
}

//添加文章日志
func AddArticleLog(item *AdvisoryArticleLog) (newId int64, err error) {
	o := orm.NewOrm()
	newId, err = o.Insert(item)
	return
}

//编辑文章
func EditArticle(item *AdvisoryArticle) (err error) {
	o := orm.NewOrm()
	sql := " UPDATE advisory_article SET title = ?, body = ?, chart_permission_id = ?,chart_permission_name=?,timing_publish_time=?,publish_status=?, link_name=?, link_address=?,  actual_publish_time=? ,is_timing=? ,last_update_time = NOW() WHERE advisory_article_id = ? "
	o.Raw(sql, item.Title, item.Body, item.ChartPermissionId, item.ChartPermissionName, item.TimingPublishTime, item.PublishStatus, item.LinkName, item.LinkAddress, item.ActualPublishTime, item.IsTiming, item.ArticleId).Exec()
	return
}

//获取文章详情
func GetUserArticleInfo(Uid int, ArticleId int64) (items *AdvisoryArticleDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM advisory_article WHERE  advisory_article_id = ? LIMIT 1`
	err = o.Raw(sql, ArticleId).QueryRow(&items)
	return
}

//获取文章详情
func GetUserArticleInfoByCode(Code string) (items *AdvisoryArticleDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM advisory_article WHERE publish_status = 1 AND code = ?`
	err = o.Raw(sql, Code).QueryRow(&items)
	return
}

//获取管理员今天是否在这个类目下发文章
func GetUserTodayRticleInfo(Uid int, ChartPermissionId int) (items *AdvisoryArticleDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM advisory_article WHERE admin_id = ? AND chart_permission_id = ?  AND publish_status = 1 AND last_update_time>=date(now()) and last_update_time<DATE_ADD(date(now()),INTERVAL 1 DAY)  LIMIT 1`
	err = o.Raw(sql, Uid, ChartPermissionId).QueryRow(&items)
	return
}

type PreviewRsp struct {
	List []*PreviewArticleDetail
	Item *PreviewArticleDetail
}

//获取用户最新编辑的文章
func GetUserNewArticleInfo(Uid int) (items *PreviewArticleDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM advisory_article WHERE admin_id = ? AND publish_status = 0 ORDER BY last_update_time DESC LIMIT 1`
	err = o.Raw(sql, Uid).QueryRow(&items)
	return
}

//文章删除
func DeleteArticle(ArticleId int64) (err error) {
	sql := `DELETE FROM advisory_article WHERE advisory_article_id=? `
	o := orm.NewOrm()
	_, err = o.Raw(sql, ArticleId).Exec()
	return
}

//文章取消发布
func UnpublishArticle(ArticleId int) (err error) {
	sql := `UPDATE advisory_article SET publish_status = 0  WHERE advisory_article_id=? `
	o := orm.NewOrm()
	_, err = o.Raw(sql, ArticleId).Exec()
	return
}

//校验用户是否关注了添加文章的分类
func CheckIsFllow(fllowList []string, ChartPermissionId string) bool {
	for _, v := range fllowList {
		if ChartPermissionId == v {
			return true
		}
	}
	return false
}

//获取预览列表
func GetPreviewArticleList(condition string, pars []interface{}, startSize, pageSize int) (items []*PreviewArticleDetail, err error) {
	sql := ` SELECT * FROM advisory_article WHERE 1=1 `
	if condition != "" {
		sql += condition
	}
	sql += ` ORDER BY  create_time DESC LIMIT ?,? `
	o := orm.NewOrm()
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

//获取预览数量
func GetPreviewArticleListCount(condition string, pars []interface{}) (count int, err error) {
	sqlCount := ` SELECT COUNT(1) AS count  FROM advisory_article WHERE 1=1 `
	if condition != "" {
		sqlCount += condition
	}
	o := orm.NewOrm()
	err = o.Raw(sqlCount, pars).QueryRow(&count)
	return
}

//获取文章列表
func GetArticlerList(condition string, pars []interface{}, startSize, pageSize int) (items []*PreviewArticleDetail, err error) {
	sql := ` SELECT * ,
		(SELECT COUNT(1) FROM advisory_article_view_record AS avr WHERE avr.article_id=advisory_article.advisory_article_id) AS pv,
        (SELECT COUNT(DISTINCT user_id) FROM advisory_article_view_record AS avr WHERE avr.article_id=advisory_article.advisory_article_id) AS uv
		FROM advisory_article WHERE 1=1 `
	if condition != "" {
		sql += condition
	}
	sql += `  LIMIT ?,? `
	o := orm.NewOrm()
	//o.Using("rddp")
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

//获取文章数量
func GetArticleListCount(condition string, pars []interface{}) (count int, err error) {
	sqlCount := ` SELECT COUNT(1) AS count  FROM advisory_article WHERE 1=1 `
	if condition != "" {
		sqlCount += condition
	}

	o := orm.NewOrm()
	//o.Using("rddp")
	err = o.Raw(sqlCount, pars).QueryRow(&count)
	return
}

type PreviewArticleListResp struct {
	CharList []*ArtChartPermission
	Preview  *PreviewArticleDetail
	List     []*PreviewArticleDetail
	Paging   *paging.PagingItem `description:"分页数据"`
}

type ArticleListResp struct {
	List   []*PreviewArticleDetail
	Paging *paging.PagingItem `description:"分页数据"`
}

//文章预览分类
type ArtChartPermission struct {
	ChartPermissionId int    `description:"权限id"`
	ClassifyName      string `description:"分类名称"`
	PermissionName    string `description:"名称"`
	ImageUrl          string `description:"图片地址"`
	IsBlongChart      bool   `description:"是否属于这个分类"`
	ChildPermission   []*ArtChartPermission
}

//获取一级分类名称
func GetFirstChartPermissionAll() (items []*ArtChartPermission, err error) {
	o := orm.NewOrm()
	sql := `SELECT  * FROM chart_permission as ch  WHERE product_id = 1  AND product_name = 'ficc'  GROUP BY ch.classify_name ORDER BY sort ASC; `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

func GetChartToClassifyName(ClassifyName string) (items []*ArtChartPermission, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM chart_permission  WHERE product_id = 1  AND product_name = 'ficc' AND classify_name = ?  ORDER BY sort ASC `
	_, err = o.Raw(sql, ClassifyName).QueryRows(&items)
	return
}

//end
//定时发布任务
func ArticleTask() (err error) {
	o := orm.NewOrm()
	sql := " UPDATE advisory_article SET publish_status = 1,   actual_publish_time=NOW() ,last_update_time = NOW() WHERE publish_status = 0  AND is_timing = 1 "
	_, err = o.Raw(sql).Exec()
	//fmt.Println(err)
	return
}

//获取文章数量
func GetThisDayTimingPublishTimeCount(condition string, pars []interface{}) (count int, err error) {
	sqlCount := ` SELECT COUNT(1) AS count  FROM advisory_article WHERE 1=1 `
	if condition != "" {
		sqlCount += condition
	}
	fmt.Println(sqlCount)
	o := orm.NewOrm()
	err = o.Raw(sqlCount, pars).QueryRow(&count)
	return
}

type PvAndUvResp struct {
	Pv int `description:"PV"`
	Uv int `description:"UV"`
}

//获取PV和Uv数量
func GetPVAndUv() (items []*PvAndUvResp, err error) {
	o := orm.NewOrm()
	sql := `SELECT id,
(SELECT COUNT( id )   FROM advisory_user_chart_article_record) AS pv,
(SELECT COUNT(DISTINCT user_id) AS uv FROM advisory_user_chart_article_record) AS uv
FROM advisory_user_chart_article_record LIMIT 0,1 `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}
