package models

import (
	"github.com/beego/beego/v2/client/orm"
	"hongze/hongze_cygx/utils"
	"strings"
	"time"
)

type CygxArticle struct {
	Id                   int       `orm:"column(id);pk"`
	ArticleId            int       `description:"文章id"`
	Title                string    `description:"标题"`
	TitleEn              string    `description:"英文标题 "`
	UpdateFrequency      string    `description:"更新周期"`
	CreateDate           string    `description:"创建时间"`
	PublishDate          string    `description:"发布时间"`
	Body                 string    `description:"内容"`
	BodyText             string    `description:"内容"`
	Abstract             string    `description:"摘要"`
	CategoryName         string    `description:"一级分类"`
	SubCategoryName      string    `description:"二级分类"`
	PublishStatus        int       `description:"发布状态"`
	CategoryId           int       `description:"分类id"`
	CategoryIdTwo        int       `description:"分类id用作修改匹配类型使用"`
	ExpertBackground     string    `description:"专家背景"`
	ExpertNumber         string    `description:"专家编号"`
	InterviewDate        string    `description:"访谈日期"`
	Department           string    `description:"作者"`
	ArticleIdMd5         string    `description:"ID，md5值"`
	IsClass              int       `description:"是否归类，1是，0否"`
	IsSummary            int       `description:"是否是纪要库，1是，0否"`
	IsReport             int       `description:"是否属于报告，1是，0否"`
	ReportType           int       `description:"报告类型，1行业报告，2产业报告,0无"`
	FileLink             string    `description:"下载预览链接"`
	MatchTypeName        string    `description:"匹配类型"`
	Periods              string    `description:"期数"`
	ReportLink           string    `description:"报告链接"`
	ArticleType          string    `description:"文章类型 文章类型，lyjh:路演精华 "`
	HavePublish          int       `description:"是否发布过，1是 ，0 否"`
	Source               int       `description:"来源 0策略平台同步，1小程序后台添加"`
	SellerAndMobile      string    `description:"销售和手机号"`
	VideoUrl             string    `description:"音频文件URL"`
	VideoName            string    `description:"音频文件名称"`
	VideoPlaySeconds     string    `description:"音频播放时长"`
	Stock                string    `description:"个股标签"`
	FieldName            string    `description:"产业标签"`
	SeriesName           string    `description:"系列名称"`
	Annotation           string    `description:"核心观点"`
	TypeName             string    `description:"策略平台报告类型"`
	ModifyTimeByCl       string    `description:"策略平台报告更新时间"`
	CeLueFieldId         int       `description:"策略平台领域ID"`
	Cover                string    `description:"封面图片"`
	ReportId             int       `description:"FICC研报ID"`
	CreateTime           time.Time `description:"创建时间"`
	ChartPermissionId    int       `description:"行业id"`
	ChartPermissionName  string    `description:"行业名称"`
	ArticleSearchContent string    `description:"搜索匹配用的内容"`
}

type CygxArticleEs struct {
	Id               int    `orm:"column(id);pk"`
	ArticleId        int    `description:"文章id"`
	Title            string `description:"标题"`
	TitleEn          string `description:"英文标题 "`
	UpdateFrequency  string `description:"更新周期"`
	CreateDate       string `description:"创建时间"`
	PublishDate      string `description:"发布时间"`
	Body             string `description:"内容"`
	BodyText         string `description:"内容"`
	Abstract         string `description:"摘要"`
	CategoryName     string `description:"一级分类"`
	SubCategoryName  string `description:"二级分类"`
	PublishStatus    int    `description:"发布状态"`
	CategoryId       string `description:"分类id"`
	ExpertBackground string `description:"专家背景"`
	ExpertNumber     string `description:"专家编号"`
	InterviewDate    string `description:"访谈日期"`
	Department       string `description:"作者"`
	ArticleIdMd5     string `description:"ID，md5值"`
	IsClass          int    `description:"是否归类，1是，0否"`
	IsSummary        bool   `description:"是否是纪要库，1是，0否"`
	IsReport         bool   `description:"是否属于报告，1是，0否"`
	ReportType       int    `description:"报告类型，1行业报告，2产业报告,0无"`
	FileLink         string `description:"下载预览链接"`
	MatchTypeName    string `description:"匹配类型"`
}

type CygxArticleIdReq struct {
	ArticleId int `description:"文章id"`
}

// 新增文章
func AddCygxArticle(item *CygxArticle) (lastId int64, err error) {
	o := orm.NewOrm()
	lastId, err = o.Insert(item)
	return
}

type HomeArticle struct {
	ArticleId           int                  `description:"文章id"`
	Title               string               `description:"标题"`
	TitleEn             string               `description:"英文标题 "`
	UpdateFrequency     string               `description:"更新周期"`
	CreateDate          string               `description:"创建时间"`
	PublishDate         string               `description:"发布时间"`
	Body                string               `description:"内容"`
	BodyHtml            string               `description:"内容带有HTML标签"`
	Abstract            string               `description:"摘要"`
	CategoryName        string               `description:"一级分类"`
	SubCategoryName     string               `description:"二级分类"`
	ExpertBackground    string               `description:"专家背景"`
	IsResearch          bool                 `description:"是否属于研选"`
	Pv                  int                  `description:"PV"`
	ImgUrlPc            string               `description:"图片链接"`
	CategoryId          string               `description:"文章分类"`
	HttpUrl             string               `description:"文章链接跳转地址"`
	IsNeedJump          bool                 `description:"是否需要跳转链接地址"`
	Source              int                  `description:"来源  1:文章, 2:图表"`
	Annotation          string               `description:"核心观点"`
	HomeType            int                  `description:"数据类型：0-纪要(默认); 1-微路演音频"`
	MicroAudio          *MicroAudioUnionList `description:"微路演音频"`
	ChartPermissionName string               `description:"权限名称"`
	ArticleTypeName     string               `description:"权限名称"`
	IsReport            int                  `description:"是否属于报告，1是，0否"`
	ArticleResponse     int                  `description:"报告类型 0：啥也不是，1研选报告，2：研选纪要，3：研选沙龙，4;研选观点"`
	Readnum             int                  `description:"阅读数量"`
	Cover               string               `description:"封面图片"`
	BodyHighlight       []string             `description:"搜索高亮展示结果"`
	ArticleTypeId       int                  `description:"文章类型ID"`
	ReportId            int                  `description:"FICC研报ID"`
	Resource            int                  `description:"来源类型，1：文章、2：产品内测"`
	IsCollect           bool                 `description:"本人是否收藏"`
	CollectNum          int                  `description:"收藏人数"`
	IsShowAbstract      bool                 `description:"是否展示摘要"`
	List                []*IndustrialManagementIdInt
}

type ArticleDetail struct {
	ArticleId                int    `description:"报告id"`
	Title                    string `description:"标题"`
	TitleEn                  string `description:"英文标题 "`
	UpdateFrequency          string `description:"更新周期"`
	CreateDate               string `description:"创建时间"`
	PublishDate              string `description:"发布时间"`
	Body                     string `description:"内容"`
	Abstract                 string `description:"摘要"`
	CategoryName             string `description:"一级分类"`
	SubCategoryName          string `description:"二级分类"`
	IsCollect                bool   `description:"是否收藏:true，已收藏，false:未收藏"`
	IsInterviewApply         bool   `description:"是否申请访谈:true，已申请，false:未申请"`
	BodyText                 string `description:"内容"`
	InterviewApplyStatus     string `description:"当前访谈申请状态：'待邀请','待访谈','已完成','已取消'"`
	InterviewDate            string `description:"访谈时间"`
	ExpertBackground         string `description:"专家背景"`
	ExpertNumber             string `description:"专家编号"`
	Department               string `description:"作者"`
	SellerMobile             string `description:"销售手机号"`
	SellerName               string `description:"销售名称"`
	ArticleIdMd5             string `description:"纪要id"`
	IsClass                  int    `description:"是否归类，1是，0否"`
	CategoryId               int    `description:"分类ID"`
	IsSummary                int    `description:"是否是纪要库，1是，0否"`
	IsReport                 int    `description:"是否属于报告，1是，0否"`
	IsResearch               bool   `description:"是否属于研选"`
	FileLink                 string `description:"下载预览链接"`
	SellerAndMobile          string `description:"销售和手机号"`
	IsFollow                 bool   `description:"是否关注，1是，0否"`
	IsBelongSummary          bool   `description:"是否属于纪要库"`
	IsBelongReport           bool   `description:"是否属于报告"`
	FollowNum                int    `description:"关注数量"`
	CollectionNum            int    `description:"收藏数量"`
	DepartmentId             int    `description:"作者ID"`
	DepartmentImgUrl         string `description:"作者头像"`
	NickName                 string `description:"作者昵称"`
	SubjectIds               string `description:"文章关联标的的ID字符串"`
	IndustrialAndSubjectIds  string `description:"文章关联产业和标的的ID字符串"`
	IndustrialManagementId   int    `description:"文章关联产业ID"`
	SellerList               []*SellerRep
	HttpUrl                  string `description:"文章链接跳转地址"`
	IsNeedJump               bool   `description:"是否需要跳转链接地址"`
	ReportLink               string `description:"报告链接"`
	IsShowLinkButton         int    `description:"这种报告类型是否展示查看报告链接"`
	ArticleTypeId            int    `description:"文章类型ID"`
	IsSpecialArticle         bool   `description:"是否属于专项调研报告"`
	Annotation               string `description:"核心观点"`
	IsShowFollowButton       bool   `description:"是否展示关注取关按钮"`
	IsFollowButton           bool   `description:"是否关注"`
	IsRoadShow               bool   `description:"是否是路演精华"`
	ReportType               int    `description:"报告类型，1行业报告，2产业报告,0无"`
	FieldName                string `description:"策略平台的领域字段名称"`
	SeriesName               string `description:"策略平台系列名称"`
	TypeName                 string `description:"策略平台类型字段名称"`
	IsApplyAppointmentExpert bool   `description:"是否属于专家访谈"`
	ArticleTypeName          string `description:"权限名称"`
	MatchTypeName            string `description:"匹配类型"`
	Stock                    string `description:"个股标签"`
	Frequency                string `description:"更新周期(策略平台字段)"`
}

type ArticleDetailFileLink struct {
	FileLink string `description:"下载预览链接"`
	Scene    string `description:"资源参数"`
}
type SellerRep struct {
	SellerMobile string `description:"销售手机号"`
	SellerName   string `description:"销售名称"`
}

func GetArticleDetailById(articleId int) (item *ArticleDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_article WHERE article_id = ?  AND publish_status = 1  `
	err = o.Raw(sql, articleId).QueryRow(&item)
	return
}

func GetArticleDetailByReportId(reportId int) (item *ArticleDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_article WHERE report_id = ?  AND publish_status = 1  `
	err = o.Raw(sql, reportId).QueryRow(&item)
	return
}

func GetSellerList(articleId int) (items []*SellerRep, err error) {
	o := orm.NewOrm()
	sql := `SELECT
		au.mobile as  seller_mobile,
		au.name as  seller_name
		FROM
		cygx_article_author AS au
		WHERE article_id = ?`
	_, err = o.Raw(sql, articleId).QueryRows(&items)
	return
}

func GetArticleDetailByIdMd5(articleIdMd5 string) (item *ArticleDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_article WHERE article_id_md5 = ? `
	err = o.Raw(sql, articleIdMd5).QueryRow(&item)
	return
}

func GetArticleDetailByIdStr(articleIdStr string) (items []*ArticleDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT 	art.*,d.nick_name FROM
			cygx_article AS art
			LEFT JOIN cygx_article_department AS d ON d.department_id = art.department_id  WHERE article_id IN(` + articleIdStr + `) `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

func GetArticlePermission(categoryId int) (item *ChartPermissionItemResp, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			a.chart_permission_name as  permission_name,a.match_type_name
			FROM
			cygx_report_mapping AS a
			WHERE
			a.category_id = ? LIMIT  1 `
	err = o.Raw(sql, categoryId).QueryRow(&item)
	//_, err = o.Raw(sql, companyId).QueryRows(&item)
	return
}

type ArticleDetailResp struct {
	Detail           *ArticleDetail
	HasPermission    int    `description:"1:有该行业权限,正常展示，2：无该行业权限，不存在权益客户下，3:无该品类权限,已提交过申请，4：无该行业权限,未提交过申请，5：潜在客户，未提交过申请，6：潜在客户,已提交过申请"`
	HasFree          int    `description:"1:已付费(至少包含一个品类的权限)，2:未付费(没有任何品类权限)"`
	HaveResearch     bool   `description:"是否有研选权限"`
	Mobile           string `description:"用户手机号"`
	PopupMsg         string `description:"权限弹窗信息"`
	SellerMobile     string `description:"销售电话"`
	SellerName       string `description:"销售姓名"`
	IsSpecialArticle bool   `description:"是否属于专项调研报告"`
	IsResearch       bool   `description:"是否属于研选"`
}

type ArticleDetailHtgjResp struct {
	HasPermission int    `description:"1:有该行业权限,正常展示，0:试用期已过期"`
	CompanyName   string `description:"公司名称"`
	Detail        *ArticleDetail
}

func ModifyArticleExpert(articleId int, expertNumStr, expertContentStr, interviewDateStr, bodyText string) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE cygx_article SET expert_background=?,expert_number=?,interview_date=?,body_text=? WHERE article_id=? `
	_, err = o.Raw(sql, expertContentStr, expertNumStr, interviewDateStr, bodyText, articleId).Exec()
	return
}

// 更改文章发布状态
func UpdateArticlePublish(articleId, publishStatus int) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE cygx_article SET publish_status=? WHERE article_id=? `
	_, err = o.Raw(sql, publishStatus, articleId).Exec()
	return
}

type ArticleDetailTest struct {
	ArticleId int    `description:"报告id"`
	Title     string `description:"标题"`
	BodyText  string `description:"内容"`
	Body      string `json:"-" description:"内容"`
}

func GetArticleDetailTestById(articleId int) (item *ArticleDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_article WHERE article_id = ? `
	err = o.Raw(sql, articleId).QueryRow(&item)
	return
}

func GetArticleAll() (item []*ArticleDetail, err error) {
	o := orm.NewOrm()
	//sql := `SELECT * FROM cygx_article WHERE 1=1  is_summary=1`
	sql := `SELECT * FROM cygx_article WHERE 1=1   AND publish_status = 1 `
	_, err = o.Raw(sql).QueryRows(&item)
	return
}
func GetArticleAllDate(endDate string) (item []*ArticleDetail, err error) {
	o := orm.NewOrm()
	//sql := `SELECT * FROM cygx_article WHERE is_summary=1 AND publish_date >= ?   `
	sql := `SELECT * FROM cygx_article WHERE 1=1 AND publish_date >= ?   `
	_, err = o.Raw(sql, endDate).QueryRows(&item)
	return
}

func GetArticleAll2() (item []*ArticleDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_article  `
	_, err = o.Raw(sql).QueryRows(&item)
	return
}

// 获取文章列表
func GetArticleList(condition string, pars []interface{}) (items []*ArticleDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT 	*  FROM cygx_article  WHERE 1= 1 ` + condition
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

// 获取文章列表
func GetArticleListHomeTag(condition string, pars []interface{}) (items []*ArticleDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT	article_id,stock FROM cygx_article  WHERE 1= 1 ` + condition
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

func ModifyArticleContent(articleId int, content, expertNumStr, expertContentStr, interviewDateStr string) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE cygx_article SET body=?,expert_background=?,expert_number=?,interview_date=? WHERE article_id=? `
	_, err = o.Raw(sql, content, expertContentStr, expertNumStr, interviewDateStr, articleId).Exec()
	return
}

type ElasticArticleDetail struct {
	ArticleId            int    `description:"报告id"`
	Title                string `description:"标题"`
	TitleEn              string `description:"英文标题 "`
	UpdateFrequency      string `description:"更新周期"`
	CreateDate           string `description:"创建时间"`
	PublishDate          string `description:"发布时间"`
	Abstract             string `description:"摘要"`
	CategoryName         string `description:"一级分类"`
	SubCategoryName      string `description:"二级分类"`
	IsCollect            bool   `description:"是否收藏:true，已收藏，false:未收藏"`
	IsInterviewApply     bool   `description:"是否申请访谈:true，已申请，false:未申请"`
	BodyText             string `description:"内容"`
	InterviewApplyStatus string `description:"当前访谈申请状态：'待邀请','待访谈','已完成','已取消'"`
	InterviewDate        string `description:"访谈时间"`
	ExpertBackground     string `description:"专家背景"`
	ExpertNumber         string `description:"专家编号"`
	Department           string `description:"作者"`
	SellerMobile         string `description:"销售手机号"`
	SellerName           string `description:"销售名称"`
	ArticleIdMd5         string `description:"纪要id"`
}

func GetArticleCountById(articleId int) (count int, err error) {
	o := orm.NewOrm()
	sql := `SELECT COUNT(1) AS count FROM cygx_article WHERE article_id = ? `
	err = o.Raw(sql, articleId).QueryRow(&count)
	return
}

type CygxArticles struct {
	Id               int    `orm:"column(id);pk"`
	ArticleId        int    `description:"文章id"`
	Title            string `description:"标题"`
	TitleEn          string `description:"英文标题 "`
	UpdateFrequency  string `description:"更新周期"`
	CreateDate       string `description:"创建时间"`
	PublishDate      string `description:"发布时间"`
	Body             string `description:"内容"`
	BodyText         string `description:"内容"`
	Abstract         string `description:"摘要"`
	CategoryName     string `description:"一级分类"`
	SubCategoryName  string `description:"二级分类"`
	PublishStatus    int    `description:"发布状态"`
	CategoryId       int    `description:"分类id"`
	ExpertBackground string `description:"专家背景"`
	ExpertNumber     string `description:"专家编号"`
	InterviewDate    string `description:"访谈日期"`
	Department       string `description:"作者"`
	ArticleIdMd5     string `description:"ID，md5值"`
	IsClass          int    `description:"是否归类，1是，0否"`
	IsSummary        int    `description:"是否是纪要库，1是，0否"`
	IsReport         int    `description:"是否属于报告，1是，0否"`
	ReportType       int    `description:"报告类型，1行业报告，2产业报告,0无"`
}

// 新增文章
func AddCygxArticles(item *CygxArticle) (lastId int64, err error) {
	o := orm.NewOrm()
	lastId, err = o.Insert(item)
	return
}

func GetPermissionMappingById(categoryId int) (count int, err error) {
	o := orm.NewOrm()
	sql := `SELECT COUNT(1) AS count FROM cygx_permission_mapping WHERE category_id = ? `
	err = o.Raw(sql, categoryId).QueryRow(&count)
	return
}

func GetReportMappingById(categoryId int) (count int, err error) {
	o := orm.NewOrm()
	sql := `SELECT COUNT(1) AS count FROM cygx_report_mapping WHERE category_id = ? `
	err = o.Raw(sql, categoryId).QueryRow(&count)
	return
}

type ReportArticle struct {
	ArticleId        int    `description:"文章id"`
	ReportId         int    `description:"文章id"`
	Title            string `description:"标题"`
	TitleEn          string `description:"英文标题 "`
	UpdateFrequency  string `description:"更新周期"`
	CreateDate       string `description:"创建时间"`
	PublishDate      string `description:"发布时间"`
	Body             string `description:"内容"`
	Abstract         string `description:"摘要"`
	CategoryName     string `description:"一级分类"`
	SubCategoryName  string `description:"二级分类"`
	ExpertBackground string `description:"专家背景"`
	IsRed            bool   `description:"是否标记红点"`
	Readnum          int    `description:"阅读数量"`
	VideoUrl         string `description:"链接"`
	IsHaveVideo      bool   `description:"是否含有音频文件"`
	ImgUrlPc         string `description:"图片链接"`
	CategoryId       string `description:"文章分类"`
	Annotation       string `description:"核心观点"`
	Resource         int    `description:"来源类型，1：文章、2：产品内测"`
	MyCollectNum     int    `description:"本人是否收藏"`
	IsCollect        bool   `description:"本人是否收藏"`
	Pv               int    `description:"PV"`
	CollectNum       int    `description:"收藏人数"`
	IsShowAbstract   bool   `description:"是否展示摘要"`
}

type ReportMappingCategoryRep struct {
	CategoryId int `description:"文章分类id"`
}

func GetReportMappingCategoryID() (item []*ReportMappingCategoryRep, err error) {
	o := orm.NewOrm()
	sql := ` SELECT category_id FROM cygx_permission_mapping  GROUP BY category_id  `
	_, err = o.Raw(sql).QueryRows(&item)
	return
}

type PermissionMappingCategoryRep struct {
	CategoryId int `description:"文章分类id"`
}

func GetPermissionMappingCategoryID() (item []*PermissionMappingCategoryRep, err error) {
	o := orm.NewOrm()
	sql := ` SELECT category_id FROM cygx_report_mapping  GROUP BY category_id `
	_, err = o.Raw(sql).QueryRows(&item)
	return
}

// 检查用户是否阅读某一分类最新文章
func GetUserIsReadThisNewCategoryArticleCount(categoryId, uid int) (count int, err error) {
	sqlCount := `SELECT
	COUNT( 1 ) AS count 
FROM
	cygx_article_history_record 
WHERE
	article_id = ( SELECT article_id FROM cygx_article WHERE category_id IN ( SELECT category_id_celue FROM cygx_report_mapping_group WHERE id_cygx = ? ) ORDER BY publish_date DESC LIMIT 0, 1 ) 
	AND user_id = ?`
	o := orm.NewOrm()
	err = o.Raw(sqlCount, categoryId, uid).QueryRow(&count)
	return
}

type ArticleId struct {
	ArticleId int `description:"文章id"`
}

type ArticleIdAndTitle struct {
	Title     string `description:"标题"`
	ArticleId int    `description:"文章id"`
}

// 获取自定义分类的文章ID
func GetCustomArticleId() (item []*ArticleId, err error) {
	o := orm.NewOrm()
	sql := ` SELECT article_id  FROM cygx_article WHERE is_custom = 1 `
	_, err = o.Raw(sql).QueryRows(&item)
	return
}

type ArticleFollowDetail struct {
	DNum   int `description:"作者被关注的数量"`
	MdNum  int `description:"本人是否关注这个作者"`
	AcNum  int `description:"文章被收藏的数量"`
	MacNum int `description:"本人是否收藏这个文章"`
}

// 获取文章被关注被收藏的详情
func GetArticleFollowDetail(articleId, uid int) (item *ArticleFollowDetail, err error) {
	//d_num 作者被关注的数量 、 md_num 本人是否关注这个作者 、ac_num 文章被收藏的数量 、 mac_num 本人是否收藏这个文章
	o := orm.NewOrm()
	sql := ` SELECT
	( SELECT count( 1 ) FROM cygx_article_department_follow AS af  WHERE af.department_id = art.department_id AND af.type = 1 ) AS d_num,
	( SELECT count( 1 ) FROM cygx_article_department_follow AS af WHERE af.department_id = art.department_id AND af.type = 1 AND af.user_id = ? ) AS md_num,
	( SELECT count( 1 ) FROM cygx_article_collect AS ac   WHERE ac.article_id = art.article_id  ) AS ac_num,
	( SELECT count( 1 ) FROM cygx_article_collect AS ac WHERE ac.article_id = art.article_id  AND ac.user_id = ? ) AS mac_num
FROM
	cygx_article AS art
	LEFT JOIN cygx_article_department_follow AS af ON af.department_id = art.department_id
	LEFT JOIN cygx_article_collect AS ac ON ac.article_id = art.article_id 
WHERE
	art.article_id = ?
	GROUP BY art.article_id `
	err = o.Raw(sql, uid, uid, articleId).QueryRow(&item)
	return
}

// 日度点评的数据同步
type ReportDetail struct {
	Id                 int    `orm:"column(id)" description:"报告Id"`
	AddType            int    `description:"新增方式：1:新增报告，2:继承报告"`
	ClassifyIdFirst    int    `description:"一级分类id"`
	ClassifyNameFirst  string `description:"一级分类名称"`
	ClassifyIdSecond   int    `description:"二级分类id"`
	ClassifyNameSecond string `description:"二级分类名称"`
	Title              string `description:"标题"`
	Abstract           string `description:"摘要"`
	Author             string `description:"作者"`
	Frequency          string `description:"频度"`
	CreateTime         string `description:"创建时间"`
	ModifyTime         string `description:"修改时间"`
	State              int    `description:"1:未发布，2:已发布"`
	PublishTime        string `description:"发布时间"`
	Stage              int    `description:"期数"`
	MsgIsSend          int    `description:"消息是否已发送，0:否，1:是"`
	Content            string `description:"内容"`
	VideoUrl           string `description:"音频文件URL"`
	VideoName          string `description:"音频文件名称"`
	VideoPlaySeconds   string `description:"音频播放时长"`
	ContentSub         string `description:"内容前两个章节"`
}

func GetReportList() (items []*ReportDetail, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT * FROM report WHERE  classify_id_second = '57'`
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

func GetMaxArticleIdInfo() (item *ArticleDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_article   ORDER BY article_id desc  LIMIT 1`
	err = o.Raw(sql).QueryRow(&item)
	return
}

type ArticleResultApi struct {
	Data []ArticleResultApidate `json:"data"`
	Code int                    `json:"code"`
	Msg  string                 `json:"msg"`
}

type ArticleDetailResultApi struct {
	Data ArticleResultApidate `json:"data"`
	Code int                  `json:"code"`
	Msg  string               `json:"msg"`
}

type ArticleResultApidate struct {
	ArticleId     int                      `json:"id"`
	Title         string                   `json:"title"`
	File          string                   `json:"file"`
	TitleEn       string                   `json:"title_en"`
	Frequency     string                   `json:"frequency"`
	CreateDate    string                   `json:"create_date"`
	UpdateDate    string                   `json:"update_date"`
	PublishDate   time.Time                `json:"publish_date"`
	PublishStatus int                      `json:"publish_status"`
	IndustrId     int                      `json:"industry_id"`
	SeriesId      int                      `json:"series_id"`
	Series        ArticleSeries            `json:"series"`
	Content       ArticleResultApiContent  `json:"content"`
	Author        ArticleResultApiAuthor   `json:"author"`
	Industry      ArticleResultApiIndustry `json:"industry"`
	Type          ArticleResultApiType     `json:"type"`
	Stock         []string                 `json:"stock"`
	Field         ArticleField             `json:"field"`
	Corpus        Corpus                   `json:"corpus"`
	Cover         string                   `json:"cover"`
	TypeId        int                      `json:"type_id"`
	IsActive      bool                     `json:"is_active"`
	PublishArea   string                   `json:"publish_area"`
}

type ArticleField struct {
	Id          int    `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	IndustryId  int    `json:"industry_id"`
}

type Corpus struct {
	Id        int    `json:"id"`
	ArticleId int    `json:"article_id"`
	Corpus    string `json:"corpus"`
}

type ArticleSeries struct {
	Name string `json:"name"`
}
type ArticleResultApiContent struct {
	ArticleId  int    `json:"id"`
	Body       string `json:"body"`
	Abstract   string `json:"abstract"`
	Annotation string `json:"annotation"`
}

type ArticleResultApiAuthor struct {
	PhoneNumber string `json:"phone_number"`
	Name        string `json:"name"`
}

type ArticleResultApiIndustry struct {
	Name string `json:"name"`
}

type ArticleResultApiType struct {
	Name string `json:"name"`
}

type ArticleIndustryApi struct {
	Data []ArticleResultApiIndustrdate `json:"data"`
	Code int                           `json:"code"`
	Msg  string                        `json:"msg"`
}

type ArticleResultApiIndustrdate struct {
	Id     int                          `json:"id"`
	Name   string                       `json:"name"`
	Series []ArticleResultApiSeriesdate `json:"series"`
}

type ArticleResultApiSeriesdate struct {
	Id   int    `json:"id"`
	Name string `json:"name"`
}

type ArticleApiMap struct {
	Id        int `description:"新ID"`
	OldId     int `description:"旧Id"`
	IsClass   int `description:"是否自动归类，1是，0否"`
	IsReport  int `description:"是否属于报告，1是，0否"`
	IsSummary int `description:"是否属于纪要，1是，0否"`
	SeriesId  int `description:"策略平台那边的报告分类ID"`
	OldIdMap  int `description:"策略平台老的分类ID样式map映射"`
}

func GetArticleApiMap() (item []*ArticleApiMap, err error) {
	o := orm.NewOrm()
	sql := ` SELECT *  FROM	cygx_article_api_map WHERE	old_id > 0  AND is_update = 1 ORDER BY old_id ASC  `
	_, err = o.Raw(sql).QueryRows(&item)
	return
}

func GetArticleIdSubjectGroup(keyWord string) (articleid string, err error) {
	o := orm.NewOrm()
	sql := ` SELECT
	GROUP_CONCAT(DISTINCT art.article_id   SEPARATOR ',') AS articleid
FROM
	cygx_article AS art
	INNER JOIN cygx_industrial_article_group_subject AS sg ON sg.article_id = art.article_id
	INNER JOIN cygx_industrial_subject AS s ON s.industrial_subject_id = sg.industrial_subject_id 
WHERE
	s.subject_name  LIKE '%` + keyWord + `%'  `
	err = o.Raw(sql).QueryRow(&articleid)
	return
}

func GetArticleIndustrialIdGroup(keyWord string) (articleid string, err error) {
	o := orm.NewOrm()
	sql := ` SELECT
	GROUP_CONCAT(DISTINCT art.article_id   SEPARATOR ',') AS article_id
FROM
	cygx_article AS art
	INNER JOIN cygx_industrial_article_group_management AS mg ON mg.article_id = art.article_id
	INNER JOIN cygx_industrial_management AS m ON m.industrial_management_id = mg.industrial_management_id 
WHERE
	m.industry_name LIKE  '%` + keyWord + `%'  `
	err = o.Raw(sql).QueryRow(&articleid)
	return
}

// 通过文章ID获取文章所关联的标的ID
func GetSubjectIds(articleId int) (subjects string, err error) {
	sql := ` SELECT
			GROUP_CONCAT( DISTINCT industrial_subject_id ORDER BY id ASC SEPARATOR ',' ) AS subjects 
			FROM
			cygx_industrial_article_group_subject WHERE article_id = ?`
	o := orm.NewOrm()
	err = o.Raw(sql, articleId).QueryRow(&subjects)
	return
}

// 修改发布状态
func UpdateIsClassFail(articleId int) (err error) {
	sql := `UPDATE cygx_article SET  is_class_fail=1  WHERE article_id=? `
	o := orm.NewOrm()
	_, err = o.Raw(sql, articleId).Exec()
	return
}

type SummaryArticleStock struct {
	Id        int    `description:"新ID"`
	ArticleId int    `description:"文章id"`
	Stock     string `description:"个股标签"`
}

// 综述报告
func GetSummaryArticle(chartPermissionId int) (items []*SummaryArticleStock, err error) {
	o := orm.NewOrm()
	sql := `SELECT
	* 
FROM
	cygx_article AS c
	INNER JOIN cygx_report_mapping AS m 
WHERE
	c.type_name = '综述报告' 
	AND m.category_id = c.category_id_two 
	AND m.chart_permission_id = ? ORDER BY modify_time_by_cl DESC `

	_, err = o.Raw(sql, chartPermissionId).QueryRows(&items)
	return
}

type SummaryArticleStockResp struct {
	List []*SummaryArticleStock
}

// 综述报告
func GetArticleStock() (items []*SummaryArticleStock, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			stock,article_id
		FROM
			cygx_article AS art 
		WHERE
			1 = 1 
			AND type_name = '综述报告' `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 列表
func GetCygxCygxArticleList(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxArticle, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_article as art WHERE 1= 1 `
	if condition != "" {
		sql += condition
	}
	sql += ` LIMIT ?,?  `
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

func ModifyArticleTitleByarticleId(articleId int, title string) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE cygx_article SET title= ?  WHERE article_id=? `
	_, err = o.Raw(sql, title, articleId).Exec()
	return
}

func ModifyArticleFiccBodyByreport_id(report_id int, body string) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE cygx_article SET body= ?  WHERE report_id=? `
	_, err = o.Raw(sql, body, report_id).Exec()
	return
}

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

// 列表
func GetCygxCygxArticleListByCondition(articleTypesCond, activityTypesCond, industryStr, subjectNameStr, articleTypeStr string) (artIds, actIds, mmIds string, err error) {
	o := orm.NewOrm()
	artSql := `SELECT GROUP_CONCAT(DISTINCT art.article_id SEPARATOR ',') AS art_ids FROM cygx_article as art `

	actSql := ` SELECT GROUP_CONCAT(DISTINCT act.activity_id SEPARATOR ',') AS act_ids FROM cygx_activity as act `

	mmSql := ` SELECT GROUP_CONCAT(DISTINCT mmc.id SEPARATOR ',') AS mm_ids FROM cygx_morning_meeting_review_chapter as mmc `

	if industryStr != "" {
		artSql += ` INNER JOIN cygx_industrial_article_group_management  AS iam ON iam.article_id = art.article_id 
				INNER JOIN cygx_industrial_management AS im ON im.industrial_management_id=iam.industrial_management_id  `
		actSql += ` INNER JOIN cygx_industrial_activity_group_management  AS iam ON iam.activity_id = act.activity_id 
				INNER JOIN cygx_industrial_management AS im ON im.industrial_management_id=iam.industrial_management_id  `
		mmSql += ` INNER JOIN cygx_morning_meeting_reviews  AS mm ON mmc.meeting_id = mm.id 
				INNER JOIN cygx_industrial_management AS im ON im.industrial_management_id=mmc.industry_id  `
	}
	if subjectNameStr != "" {
		artSql += ` INNER JOIN cygx_industrial_article_group_subject  AS ias ON ias.article_id = art.article_id 
				INNER JOIN cygx_industrial_subject AS cis ON cis.industrial_subject_id=ias.industrial_subject_id  `
		actSql += ` INNER JOIN cygx_industrial_activity_group_subject  AS ias ON ias.activity_id = act.activity_id 
				INNER JOIN cygx_industrial_subject AS cis ON cis.industrial_subject_id=ias.industrial_subject_id  `
		mmSql += ` IINNER JOIN cygx_morning_meeting_reviews  AS mm ON mmc.meeting_id = mm.id 
				INNER JOIN cygx_industrial_subject AS cis ON cis.industrial_subject_id=mmc.industrial_subject_ids  `
	}
	artSql += ` WHERE 1=1 `
	if articleTypesCond != "" || (articleTypesCond == "" && activityTypesCond == "") {
		if industryStr != "" && subjectNameStr != "" {
			artSql += articleTypesCond + ` AND (im.industry_name In (` + industryStr + `) OR cis.subject_name In (` + subjectNameStr + `) )`
		} else if industryStr == "" && subjectNameStr != "" {
			artSql += articleTypesCond + ` AND  cis.subject_name In (` + subjectNameStr + `) `
		} else if industryStr != "" && subjectNameStr == "" {
			artSql += articleTypesCond + ` AND im.industry_name In (` + industryStr + `) `
		} else {
			artSql += articleTypesCond
		}
		err = o.Raw(artSql).QueryRow(&artIds)
	}

	actSql += ` WHERE 1=1 `
	if activityTypesCond != "" || (articleTypesCond == "" && activityTypesCond == "") {
		if industryStr != "" && subjectNameStr != "" {
			actSql += activityTypesCond + ` AND (im.industry_name In (` + industryStr + `) OR cis.subject_name In (` + subjectNameStr + `) )`
		} else if industryStr == "" && subjectNameStr != "" {
			actSql += activityTypesCond + ` AND  cis.subject_name In (` + subjectNameStr + `) `
		} else if industryStr != "" && subjectNameStr == "" {
			actSql += activityTypesCond + ` AND im.industry_name In (` + industryStr + `) `
		} else {
			actSql += activityTypesCond
		}
		err = o.Raw(actSql).QueryRow(&actIds)
	}

	if strings.Contains(articleTypeStr, "晨会精华") {
		mmSql += ` WHERE 1=1 `
		if industryStr != "" && subjectNameStr != "" {
			mmSql += ` AND (im.industry_name In (` + industryStr + `) OR cis.subject_name In (` + subjectNameStr + `) )`
		} else if industryStr == "" && subjectNameStr != "" {
			mmSql += ` AND  cis.subject_name In (` + subjectNameStr + `) `
		} else if industryStr != "" && subjectNameStr == "" {
			mmSql += ` AND im.industry_name In (` + industryStr + `) `
		}
		err = o.Raw(mmSql).QueryRow(&mmIds)
	}

	return
}

// 单个tag时用，取合集
func GetCygxCygxArticleListByConditionSoloTag(articleTypeCondSlice, activityTypesCondSlice, industriesCondSlice, subjectNamesSlice, articleTypeSlice []string) (artIds, actIds, mmIds string, err error) {
	o := orm.NewOrm()
	artSql := `SELECT GROUP_CONCAT(DISTINCT art.article_id SEPARATOR ',') AS art_ids FROM cygx_article as art `

	actSql := ` SELECT GROUP_CONCAT(DISTINCT act.activity_id SEPARATOR ',') AS act_ids FROM cygx_activity as act `

	mmSql := ` SELECT GROUP_CONCAT(DISTINCT mmc.id SEPARATOR ',') AS mm_ids FROM cygx_morning_meeting_review_chapter as mmc `

	for _, s := range industriesCondSlice {
		if s != "" {
			artSql += ` INNER JOIN cygx_industrial_article_group_management  AS iam ON iam.article_id = art.article_id 
				INNER JOIN cygx_industrial_management AS im ON im.industrial_management_id=iam.industrial_management_id  `
			actSql += ` INNER JOIN cygx_industrial_activity_group_management  AS iam ON iam.activity_id = act.activity_id 
				INNER JOIN cygx_industrial_management AS im ON im.industrial_management_id=iam.industrial_management_id  `
			mmSql += ` INNER JOIN cygx_morning_meeting_reviews  AS mm ON mmc.meeting_id = mm.id 
				INNER JOIN cygx_industrial_management AS im ON im.industrial_management_id=mmc.industry_id  `

			break
		}
	}
	for _, s := range subjectNamesSlice {
		if s != "" {
			artSql += ` INNER JOIN cygx_industrial_article_group_subject  AS ias ON ias.article_id = art.article_id 
				INNER JOIN cygx_industrial_subject AS cis ON cis.industrial_subject_id=ias.industrial_subject_id  `
			actSql += ` INNER JOIN cygx_industrial_activity_group_subject  AS ias ON ias.activity_id = act.activity_id 
				INNER JOIN cygx_industrial_subject AS cis ON cis.industrial_subject_id=ias.industrial_subject_id  `
			mmSql += ` IINNER JOIN cygx_morning_meeting_reviews  AS mm ON mmc.meeting_id = mm.id 
				INNER JOIN cygx_industrial_subject AS cis ON cis.industrial_subject_id=mmc.industrial_subject_ids  `

			break
		}
	}
	artSql += ` WHERE 1=1 AND ((1=1 `
	actSql += ` WHERE 1=1 AND ((1=1 `
	mmSql += ` WHERE 1=1 AND ((1=1 `
	var isNeedArt, isNeedAct, isNeedMm bool
	for i, _ := range articleTypeCondSlice {
		articleTypesCond := articleTypeCondSlice[i]
		activityTypesCond := activityTypesCondSlice[i]
		industryStr := industriesCondSlice[i]
		subjectNameStr := subjectNamesSlice[i]
		articleTypeStr := articleTypeSlice[i]

		if articleTypesCond != "" || (articleTypesCond == "" && activityTypesCond == "") {
			if industryStr != "" && subjectNameStr != "" {
				artSql += articleTypesCond + ` AND (im.industry_name In (` + industryStr + `) OR cis.subject_name In (` + subjectNameStr + `) )`
			} else if industryStr == "" && subjectNameStr != "" {
				artSql += articleTypesCond + ` AND  cis.subject_name In (` + subjectNameStr + `) `
			} else if industryStr != "" && subjectNameStr == "" {
				artSql += articleTypesCond + ` AND im.industry_name In (` + industryStr + `) `
			} else {
				artSql += articleTypesCond
			}

			if i == len(articleTypeCondSlice)-1 {
				artSql += `)) `
			} else {
				artSql += `) OR (1=1 `
			}

			isNeedArt = true
		}

		if activityTypesCond != "" || (articleTypesCond == "" && activityTypesCond == "") {
			if industryStr != "" && subjectNameStr != "" {
				actSql += activityTypesCond + ` AND (im.industry_name In (` + industryStr + `) OR cis.subject_name In (` + subjectNameStr + `) )`
			} else if industryStr == "" && subjectNameStr != "" {
				actSql += activityTypesCond + ` AND  cis.subject_name In (` + subjectNameStr + `) `
			} else if industryStr != "" && subjectNameStr == "" {
				actSql += activityTypesCond + ` AND im.industry_name In (` + industryStr + `) `
			} else {
				actSql += activityTypesCond
			}

			if i == len(articleTypeCondSlice)-1 {
				actSql += `)) `
			} else {
				actSql += `) OR (1=1 `
			}

			isNeedAct = true
		}

		if strings.Contains(articleTypeStr, "晨会精华") {
			if industryStr != "" && subjectNameStr != "" {
				mmSql += ` AND (im.industry_name In (` + industryStr + `) OR cis.subject_name In (` + subjectNameStr + `) )`
			} else if industryStr == "" && subjectNameStr != "" {
				mmSql += ` AND  cis.subject_name In (` + subjectNameStr + `) `
			} else if industryStr != "" && subjectNameStr == "" {
				mmSql += ` AND im.industry_name In (` + industryStr + `) `
			}

			if i == len(articleTypeCondSlice)-1 {
				mmSql += `)) `
			} else {
				mmSql += `) OR (1=1 `
			}

			isNeedMm = true
		}
	}

	if isNeedArt {
		err = o.Raw(artSql).QueryRow(&artIds)
		if err != nil {
			return
		}
	}
	if isNeedAct {
		err = o.Raw(actSql).QueryRow(&actIds)
		if err != nil {
			return
		}
	}
	if isNeedMm {
		err = o.Raw(mmSql).QueryRow(&mmIds)
		if err != nil {
			return
		}
	}

	return
}

// 获取文章列表
func GetArticleInit13_5() (items []*ArticleDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT
	art.title,
	art.article_id,
	art.category_id,
	art.publish_date,
	art.is_class,
	art.publish_status,
	art.is_filter,
	art.stock,
	art.field_name,
	art.id,
	art.article_id_md5,
	re.chart_permission_name,
	re.match_type_name,
	art.sub_category_name,
	re.chart_permission_id 
FROM
	cygx_article AS art
	LEFT JOIN cygx_report_mapping AS ret ON ret.category_id = art.category_id_two
	LEFT JOIN cygx_report_mapping AS re ON re.category_id = art.category_id
	LEFT JOIN cygx_industrial_article_group_management AS man ON man.article_id = art.article_id 
WHERE
	1 = 1 
	
	AND art.category_id IN ( SELECT category_id FROM cygx_report_mapping WHERE match_type_name = '热点问答' ) 
	AND re.chart_permission_id = 22   	GROUP BY  art.article_id `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 获取文章列表
func GetArticleInit13_5GuSHou() (items []*ArticleDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT
	art.title,
	art.article_id
FROM
	cygx_article AS art

WHERE
	1 = 1  AND category_id  IN (10070,10082)  `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 列表
func GetCygxCygxArticleListByReportIds(reportIds []int) (items []*CygxArticle, err error) {
	lenArr := len(reportIds)
	if lenArr == 0 {
		return
	}
	var pars []interface{}
	o := orm.NewOrm()
	sql := `SELECT article_id ,report_id FROM cygx_article as art WHERE report_id IN  (` + utils.GetOrmInReplace(lenArr) + `) `
	pars = append(pars, reportIds)
	sql += ` LIMIT ?,?  `
	_, err = o.Raw(sql, pars, 0, lenArr).QueryRows(&items)
	return
}

// 已经同步到查研的FICC研报列表
func GetCygxCygxArticleFiccReportList() (items []*CygxArticle, err error) {
	o := orm.NewOrm()
	sql := `SELECT article_id ,report_id,publish_status FROM cygx_article as art WHERE report_id > 0 `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// UpdateCygxCygxArticleBillMulti  批量修改文章搜索内容字段
func UpdateCygxCygxArticleBillMulti(items []*CygxArticle) (err error) {
	o := orm.NewOrm()
	p, err := o.Raw("UPDATE cygx_article SET article_search_content = ? WHERE article_id = ?  ").Prepare()
	if err != nil {
		return
	}
	defer func() {
		_ = p.Close() // 别忘记关闭 statement
	}()
	for _, v := range items {
		_, err = p.Exec(v.ArticleSearchContent, v.ArticleId)
		if err != nil {
			return
		}
	}
	return
}
