package models

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

type IndustrialManagementList struct {
	Paging       *paging.PagingItem
	List         []*IndustrialManagement
	IsShowOpen   bool `description:"是否展示展开字段"`
	IsInterested bool `description:"是否属于感兴趣部分"`
}

type IndustrialManagement struct {
	IndustrialManagementId int                  `orm:"column(industrial_management_id);pk" description:"产业id"`
	IndustryName           string               `description:"产业名称"`
	RecommendedIndex       int                  `description:"推荐指数"`
	CategoryId             int                  `description:"文章分类ID"`
	LayoutTime             string               `description:"布局时间"`
	UpdateTime             string               `description:"更新时间"`
	PublishDate            string               `description:"更新时间"`
	MinReportTime          string               `description:"报告最早发布时间"`
	IsRed                  bool                 `description:"是否标记红点"`
	IsTop                  bool                 `description:"是否置顶"`
	IsHot                  bool                 `description:"是否是热门-近一个月内，产业下关联的报告阅读次数最多的"`
	IsFollow               int                  `description:"是否关注"`
	FollowType             int                  `description:"1,重点关注，3不感兴趣，0默认接受推送"`
	IsNew                  bool                 `description:"是否为新-关联报告的发布时间，均在3个月以内的"`
	Analyst                string               `description:"分析师"`
	ArticleReadNum         int                  `description:"文章阅读数量"`
	OneMonFollowNum        int                  `description:"近一个月关注增量"`
	AnalystList            []*IndustrialAnalyst `description:"分析师列表"`
	IndustrialSubjectList  []*IndustrialSubject `description:"标的列表"`
	ChartPermissionId      int                  `description:"行业ID"`
	PermissionName         string               `description:"行业名称"`
	TimeLineData           string               `description:"时间线所关联最新三篇文章的json数据"`
	ListTimeLine           []TimeLineReportResp `description:"时间线所关联最新三篇文章列表"`
	IndustryVideo          *MicroVideoSimpleInfo
	AuthInfo               *UserPermissionAuthInfo
	ArticleId              int `description:"文章id"`
	Source                 int `description:"来源 1:弘则资源包（报告）、2：研选主题（报告）"`
}

type TimeLineReportResp struct {
	Title       string `description:"标题"`
	PublishDate string `description:"发布时间"`
}

type MicroVideoSimpleInfo struct {
	Id                  int    `description:"视频ID"`
	Title               string `description:"标题"`
	ResourceUrl         string `description:"链接"`
	BackgroundImg       string `description:"背景图"`
	PlaySeconds         int    `description:"音视频时长"`
	DetailImgUrl        string `description:"产业详情页背景图"`
	ChartPermissionId   int    `description:"行业ID"`
	ChartPermissionName string `description:"行业名称"`
}

type IndustrialAnalyst struct {
	AnalystName            string `description:"分析师名称"`
	IndustrialManagementId int    `description:"产业id"`
}

type IndustrialSubject struct {
	IndustrialSubjectId    int    `orm:"column(industrial_subject_id);pk" description:"标的id"`
	IndustrialManagementId int    `description:"产业id"`
	SubjectName            string `description:"标的名称"`
	IndustryName           string `description:"产业名称"`
	LayoutTime             string `description:"产业布局时间"`
}

// 获取产业报告数量
func GetReportIndustrialCount(categoryId, industrialManagementId int) (count int, err error) {
	o := orm.NewOrm()
	sql := `SELECT COUNT(1) count 
FROM
	cygx_article AS a 
	INNER JOIN cygx_industrial_article_group_management as man_g ON man_g.article_id = a.article_id
WHERE
	a.publish_status = 1 
	AND category_id IN (SELECT
	category_id 
FROM
	cygx_report_mapping 
WHERE
	chart_permission_id = any( SELECT chart_permission_id FROM cygx_report_mapping WHERE category_id = ` + strconv.Itoa(categoryId) + ` ) 
	AND match_type_name = any( SELECT match_type_name FROM cygx_report_mapping WHERE category_id = ` + strconv.Itoa(categoryId) + ` ) )
	AND a.is_class = 1
	AND man_g.industrial_management_id = ?  `
	err = o.Raw(sql, industrialManagementId).QueryRow(&count)
	return
}

// 获取产业报告列表
func GetReportIndustrialList(pars []interface{}, categoryId, industrialManagementId, userId, startSize, pageSize int) (items []*ReportArticle, err error) {
	o := orm.NewOrm()
	sql := `SELECT *,( SELECT COUNT( 1 ) FROM cygx_article_history_record AS rec WHERE rec.user_id = ` + strconv.Itoa(userId) + ` AND rec.article_id = a.article_id ) AS readnum 
FROM
	cygx_article AS a 
	INNER JOIN cygx_industrial_article_group_management as man_g ON man_g.article_id = a.article_id
WHERE
	a.publish_status = 1 
	AND category_id  IN (SELECT
	category_id 
FROM
	cygx_report_mapping 
WHERE
	chart_permission_id = any( SELECT chart_permission_id FROM cygx_report_mapping WHERE category_id = ` + strconv.Itoa(categoryId) + ` ) 
	AND match_type_name = any( SELECT match_type_name FROM cygx_report_mapping WHERE category_id = ` + strconv.Itoa(categoryId) + ` ) )
    AND a.is_class = 1
	AND man_g.industrial_management_id = ?`
	sql += `   GROUP BY a.article_id ORDER BY publish_date DESC LIMIT ?,? `
	_, err = o.Raw(sql, pars, industrialManagementId, startSize, pageSize).QueryRows(&items)
	return
}

// 获取产业报告列表
func GetReportAndproductInteriorIndustrialList(pars []interface{}, categoryId, industrialManagementId, userId, startSize, pageSize int) (items []*ReportArticle, total int, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			art.article_id,
			art.title,
			art.publish_date,
			( SELECT COUNT( 1 ) FROM cygx_article_history_record AS rec WHERE rec.user_id = ` + strconv.Itoa(userId) + ` AND rec.article_id = art.article_id ) AS readnum , 
			1 AS resource 
		FROM
			cygx_article AS art
			INNER JOIN cygx_industrial_article_group_management AS man_g ON man_g.article_id = art.article_id 
		WHERE
			art.publish_status = 1 
			AND art.article_id IN ( SELECT article_id FROM cygx_report_mapping_category_group WHERE id_cygx = ` + strconv.Itoa(categoryId) + ` ) 
			AND art.is_class = 1 
			AND man_g.industrial_management_id =` + strconv.Itoa(industrialManagementId) + ` 
		GROUP BY
			art.article_id UNION ALL
		SELECT
			art.product_interior_id AS article_id,
			art.title,
			art.publish_time AS publish_date,
			( SELECT COUNT( 1 ) FROM cygx_product_interior_history AS rec WHERE rec.user_id = ` + strconv.Itoa(userId) + ` AND rec.product_interior_id = art.product_interior_id ) AS readnum ,
			2 AS resource 
		FROM
			cygx_product_interior AS art
			INNER JOIN cygx_product_interior_industrial_group_management AS man_g ON man_g.product_interior_id = art.product_interior_id 
		WHERE
			art.STATUS = 1 
			AND art.visible_range = 1 
			AND art.match_type_id = ` + strconv.Itoa(categoryId) + ` 
			AND man_g.industrial_management_id = ` + strconv.Itoa(industrialManagementId) + ` 
		GROUP BY
			art.product_interior_id `

	totalSql := `SELECT COUNT(1) total FROM (` + sql + `) z `
	err = o.Raw(totalSql, pars).QueryRow(&total)
	sql += `    ORDER BY publish_date DESC LIMIT ?,? `
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

// 获取行业报告列表
func GetReportAndproductIndustrylList(categoryId, startSize, pageSize int) (items []*ReportArticle, total int, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			art.article_id,
			art.report_id,
			art.title,
			art.abstract,
			art.publish_date,
			1 AS resource 
		FROM
			cygx_article AS art 
		WHERE
			art.publish_status = 1 
			AND art.article_id IN ( SELECT article_id FROM cygx_report_mapping_category_group WHERE id_cygx = ` + strconv.Itoa(categoryId) + ` ) UNION ALL
		SELECT
			art.product_interior_id AS article_id,
			0 AS report_id,
			art.title,
			"" as abstract,
			art.publish_time AS publish_date,
			2 AS resource 
		FROM
			cygx_product_interior AS art 
		WHERE
			art.STATUS = 1 
			AND art.visible_range = 1 
			AND art.match_type_id = ` + strconv.Itoa(categoryId)
	totalSql := `SELECT COUNT(1) total FROM (` + sql + `) z `
	err = o.Raw(totalSql).QueryRow(&total)
	sql += `    ORDER BY publish_date DESC LIMIT ?,? `
	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&items)
	return
}

// 产业下所关联的文章分类列表
func IndustrialToArticleCategory(industrialManagementId, chartPermissionId int) (items []*IndustrialToArticleCategoryRep, err error) {
	o := orm.NewOrm()
	sql := `SELECT map.match_type_name,map.category_id
    FROM cygx_report_mapping AS map
	INNER JOIN cygx_article AS art ON art.category_id = map.category_id
	INNER JOIN cygx_industrial_article_group_management AS man_g ON man_g.article_id = art.article_id
	WHERE map.report_type = 2
	AND map.is_report = 1
    AND art.is_report = 1
    AND art.publish_status = 1
	AND man_g.industrial_management_id =?
	AND map.chart_permission_id = ?
	GROUP BY map.match_type_name`
	_, err = o.Raw(sql, industrialManagementId, chartPermissionId).QueryRows(&items)
	return
}

// 产业下所关联的文章分类列表 2022-10-13
func IndustrialToArticleCategoryNew(industrialManagementId int) (items []*IndustrialToArticleCategoryRep, err error) {
	o := orm.NewOrm()
	sql := `SELECT map.match_type_name,map.category_id
    FROM cygx_report_mapping AS map
	INNER JOIN cygx_article AS art ON art.category_id = map.category_id
	INNER JOIN cygx_industrial_article_group_management AS man_g ON man_g.article_id = art.article_id
	WHERE map.report_type = 2
	AND map.is_report = 1
    AND art.is_report = 1
    AND art.publish_status = 1
	AND man_g.industrial_management_id =?
	GROUP BY map.match_type_name`
	_, err = o.Raw(sql, industrialManagementId).QueryRows(&items)
	return
}

// 产业下所关联的文章、产品内测分类列表 2023-04-14
func IndustrialToArticleAndProductInteriorCategoryNew(industrialManagementId int) (items []*IndustrialToArticleCategoryRep, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			map.match_type_name,
			map.sort,
			map.id,
			map.id AS category_id 
		FROM
			cygx_report_mapping_cygx AS map
			INNER JOIN cygx_report_mapping_group AS g ON g.id_cygx = map.id
			INNER JOIN cygx_report_mapping_celue AS cl ON cl.category_id = g.category_id_celue
			INNER JOIN cygx_article AS art ON art.category_id = cl.category_id
			INNER JOIN cygx_industrial_article_group_management AS man_g ON man_g.article_id = art.article_id 
		WHERE
			1 = 1 
			AND map.report_type = 2 
			AND map.is_report = 1 
			AND art.is_report = 1 
			AND art.publish_status = 1 
			AND man_g.industrial_management_id = ?
		GROUP BY
			map.match_type_name UNION ALL
		SELECT
			map.match_type_name,
			map.sort,
			map.id,
			map.id AS category_id 
		FROM
			cygx_report_mapping_cygx AS map
			INNER JOIN cygx_industrial_management AS im ON im.chart_permission_id = map.chart_permission_id
			INNER JOIN cygx_product_interior AS art ON art.match_type_id = map.id
			INNER JOIN cygx_product_interior_industrial_group_management AS man_g ON man_g.product_interior_id = art.product_interior_id 
		WHERE
			1 = 1 
			AND art.STATUS = 1 
			AND art.visible_range = 1 
			AND man_g.industrial_management_id = ? 
		GROUP BY
				map.match_type_name  	ORDER BY  id ASC ,  sort DESC   `
	_, err = o.Raw(sql, industrialManagementId, industrialManagementId).QueryRows(&items)
	return
}

// 判断用户是否阅读该产业下，某一分类的文章
func IndustrialUserRecordArticleCount(userId, industrialManagementId, categoryId int) (count int, err error) {
	o := orm.NewOrm()
	sql := `SELECT
	COUNT(1) count
FROM
	cygx_article_history_record 
WHERE
	article_id = ( SELECT article_id FROM cygx_article WHERE article_id IN (SELECT article_id FROM cygx_industrial_article_group_management WHERE industrial_management_id = ? ) AND category_id  IN (SELECT
	category_id 
FROM
	cygx_report_mapping 
WHERE
	chart_permission_id = any( SELECT chart_permission_id FROM cygx_report_mapping WHERE category_id = ? ) 
	AND match_type_name = any( SELECT match_type_name FROM cygx_report_mapping WHERE category_id = ? ) ) ORDER BY publish_date DESC LIMIT 0, 1 ) 
	AND user_id = ? `
	err = o.Raw(sql, industrialManagementId, categoryId, categoryId, userId).QueryRow(&count)
	return
}

// 获取最新文章
func GetNewIndustrialUserRecordArticle(industrialManagementId, categoryId int) (item *ArticleDetail, err error) {
	o := orm.NewOrm()
	//sql := ` SELECT * FROM cygx_article WHERE article_id IN (SELECT article_id FROM cygx_industrial_article_group_management WHERE industrial_management_id = ? ) AND match_type_name = any( SELECT match_type_name FROM cygx_report_mapping WHERE category_id = ? ) ORDER BY publish_date DESC LIMIT 0, 1`
	sql := ` SELECT * FROM cygx_article WHERE article_id IN (SELECT article_id FROM cygx_industrial_article_group_management WHERE industrial_management_id = ? ) AND category_id  IN (SELECT
	category_id 
FROM
	cygx_report_mapping 
WHERE
	chart_permission_id = any( SELECT chart_permission_id FROM cygx_report_mapping WHERE category_id = ? ) 
	AND match_type_name = any( SELECT match_type_name FROM cygx_report_mapping WHERE category_id = ? ) ) ORDER BY publish_date DESC LIMIT 0, 1`
	err = o.Raw(sql, industrialManagementId, categoryId, categoryId).QueryRow(&item)
	return
}

// 获取最新文章
func GetNewArticleByCategoryId(categoryId int) (item *ArticleDetail, err error) {
	o := orm.NewOrm()
	sql := ` SELECT * 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 `
	err = o.Raw(sql, categoryId).QueryRow(&item)
	return
}

func GetIndustrialManagementIdsBykeyWord(condition string) (industrialManagementIds string, err error) {
	sql := `SELECT GROUP_CONCAT(DISTINCT industrial_management_id  SEPARATOR ',') AS industrial_management_ids FROM cygx_industrial_management WHERE` + condition
	o := orm.NewOrm()
	err = o.Raw(sql).QueryRow(&industrialManagementIds)
	return
}

type ReportArticleWhichIndustrial struct {
	ArticleId    int    `description:"文章id"`
	Title        string `description:"标题"`
	PublishDate  string `description:"发布时间"`
	IndustryName string `description:"产业名称"`
	SubjectName  string `description:"标的名称"`
	NickName     string `description:"作者昵称"`
	IsRed        bool   `description:"是否标记红点"`
	Readnum      int    `description:"阅读数量"`
	IsResearch   bool   `description:"是否属于研选"`
	Pv           int    `description:"PV"`
	ImgUrlPc     string `description:"图片链接"`
}

type ReportArticleWhichIndustrialRepList struct {
	HaveResearch bool               `description:"是否有研选权限"`
	Paging       *paging.PagingItem `description:"分页数据"`
	NickName     string             `description:"作者昵称"`
	IndustryName string             `description:"产业名称"`
	List         []*ReportArticleWhichIndustrial
}

// 列表
func IndustrialToArticleWhichDepartment(condition string, pars []interface{}, uid, startSize, pageSize int) (items []*ReportArticleWhichIndustrial, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			art.* ,m.industry_name,d.nick_name,
			(SELECT count(1) FROM cygx_article_history_record_newpv as h WHERE h.article_id = art.article_id ) as pv,
			( SELECT COUNT( 1 ) FROM cygx_article_history_record_newpv AS rec WHERE rec.user_id =  ` + strconv.Itoa(uid) + ` AND rec.article_id = art.article_id ) AS readnum 
			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
			INNER JOIN cygx_article_department as d ON d.department_id = art.department_id
			WHERE 1 = 1 
			AND art.publish_status = 1`
	if condition != "" {
		sql += condition
	}
	sql += ` LIMIT ?,?`
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

func GetWhichDepartmentCount(condition string) (count int, err error) {
	o := orm.NewOrm()
	sql := `SELECT COUNT(1) count 
			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
			INNER JOIN cygx_article_department as d ON d.department_id = art.department_id
			WHERE 1 = 1 
			AND art.publish_status = 1`
	if condition != "" {
		sql += condition
	}
	err = o.Raw(sql).QueryRow(&count)
	return
}

type IsShow struct {
	IsShow                     bool      `description:"绝密内参按钮是否展示"`
	IsShowFreeButton           bool      `description:"免费送月卡按钮是否展示"`
	IsShowResearch             bool      `description:"研选是否展示限免"`
	IsShowChart                bool      `description:"图表是否展示限免"`
	IsShowList                 bool      `description:"榜单是否展示"`
	LinkWxExplain              string    `description:"关注微信公众号链接说明地址"`
	YanXuan_Explain            bool      `description:"研选说明"`
	ActivitySpecialExplain     string    `description:"专项调研活动"`
	SearchTxtList              SearchTxt `description:"搜索栏回显内容说明"`
	IsBelongRai                bool      `description:"是否属于权益内部人员"`
	IsShowResearchPoints       bool      `description:"是否展示研选扣点搜索"`
	IsShowQuestionnaire        bool      `description:"是否展示研选问卷调查"`
	IsShowAboutVideo           bool      `description:"是否展示关于我们的视频"`
	IsShowMobileAndEmailButton bool      `description:"是否展示手机号跟邮箱按钮"`
	IsShowTerminateButton      bool      `description:"是否弹到期提醒的弹窗"`
	EndData                    string    `description:"结束时间"`
}

type SearchTxt struct {
	SummarySearch  string `description:"素材库搜索说明"`
	ReportSearch   string `description:"报告搜索说明"`
	YanXuanSearch  string `description:"研选搜索说明"`
	ActivitySearch string `description:"活动搜索说明"`
	TabSearch      string `description:"素材库搜索说明"`
}

// 获取用户是否有查看权限
func GetUserIsAdminCount(mobile string) (count int, err error) {
	o := orm.NewOrm()
	sql := `SELECT COUNT(1) count  FROM admin 
			WHERE
 			mobile = ?
			AND (group_id IN (11, 13, 14, 15, 16, 17) OR department_id = 3 )   AND  enabled = 1`
	err = o.Raw(sql, mobile).QueryRow(&count)
	return
}

type ReportDetailRoadshow struct {
	ArticleId        int    `description:"报告Id"`
	Title            string `description:"标题"`
	Department       string `orm:"column(seller_and_mobile)"description:"作者"`
	PublishDate      string `description:"发布时间"`
	VideoUrl         string `description:"链接"`
	VideoPlaySeconds string `description:"时长"`
	VideoName        string `description:"音频名称"`
	Abstract         string `description:"摘要"`
	Body             string `description:"内容"`
	CategoryName     string `description:"行业名称"`
	ReportLink       string `orm:"column(link_article_id)"description:"报告链接"`
	IsCollect        bool   `description:"是否收藏:true，已收藏，false:未收藏"`
	IsRoadShow       bool   `description:"是否是路演精华"`
	VisibleRange     int    `description:"设置可见范围1全部，0内部"`
	CategoryId       int    `description:"文章分类ID"`
}

type RoadshowDetailResp struct {
	Detail        *ReportDetailRoadshow
	HasPermission int  `description:"1:有该行业权限,正常展示，2：无该行业权限，不存在权益客户下，3:无该品类权限,已提交过申请，4：无该行业权限,未提交过申请，5：潜在客户，未提交过申请，6：潜在客户,已提交过申请"`
	HasFree       int  `description:"1:已付费(至少包含一个品类的权限)，2:未付费(没有任何品类权限)"`
	IsShow        bool `description:"是否展示"`
}

func GetReportRoadshowDetailById(articleId int) (item *ReportDetailRoadshow, 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
}

type CygxIndustryAndArticleList struct {
	ArticleId    int    `orm:"column(article_id);pk"description:"报告id"`
	Title        string `description:"标题"`
	PublishDate  string `description:"发布时间"`
	IndustryName string `description:"产业名称"`
	SubjectName  string `description:"标的名称"`
}

type CygxIndustrySearchList struct {
	ArtList []*CygxIndustryAndArticleList `description:"文章列表"`
	IndList []*IndustrialManagement       `description:"产业列表"`
}

type CygxIndustrySearchListPc struct {
	DepartmentList []*CygxArticleDepartmentRepPc
	IndList        []*IndustrialManagement `description:"产业列表"`
}

// 列表
func GetCygxIndustryAndArticleList(keyWord string) (items []*CygxIndustryAndArticleList, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			art.title,
			art.article_id,
			art.publish_date
		FROM
			cygx_article AS art
			LEFT JOIN cygx_industrial_article_group_subject AS sg ON sg.article_id = art.article_id
			LEFT JOIN cygx_industrial_article_group_management AS mg ON mg.article_id = mg.article_id
			LEFT JOIN cygx_industrial_management AS m ON m.industrial_management_id = mg.industrial_management_id 
		WHERE
		category_name LIKE '%研选%'
		AND art.article_id IN ( SELECT article_id FROM cygx_industrial_article_group_subject AS sg WHERE sg.industrial_subject_id IN ( SELECT industrial_subject_id FROM cygx_industrial_subject WHERE subject_name LIKE '%` + keyWord + `%' ) GROUP BY sg.article_id ) 
		OR ( art.article_id IN ( SELECT article_id FROM cygx_industrial_article_group_management AS mg WHERE mg.industrial_management_id IN ( SELECT industrial_management_id FROM cygx_industrial_management WHERE industry_name LIKE '%` + keyWord + `%' ) GROUP BY mg.article_id ) AND category_name LIKE '%研选%' )
		GROUP BY
			art.article_id`
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

func GetArticleIdsBySubId(subjectId string) (articleIds string, err error) {
	o := orm.NewOrm()
	sql := `SELECT	GROUP_CONCAT( DISTINCT a.article_id  SEPARATOR ',' ) AS articleIds 
            FROM cygx_article AS a 
			WHERE subject_ids  LIKE '%` + subjectId + `%'`
	err = o.Raw(sql).QueryRow(&articleIds)
	return
} //end

// 用户收藏榜start
type ArticleCollectionResp struct {
	ArticleId              int                         `description:"文章id"`
	Title                  string                      `description:"标题"`
	PublishDate            string                      `description:"发布日期"`
	PublishTime            time.Time                   `description:"发布时间"`
	IndustrialManagementId int                         `description:"产业Id"`
	IndustryName           string                      `description:"产业名称"`
	DepartmentId           int                         `description:"作者Id"`
	NickName               string                      `description:"作者昵称"`
	MyCollectNum           int                         `description:"本人是否收藏"`
	IsCollect              bool                        `description:"本人是否收藏"`
	Pv                     int                         `description:"PV"`
	CollectNum             int                         `description:"收藏人数"`
	Source                 int                         `description:"来源 1:弘则资源包（报告）、2：研选主题（报告）"`
	ArticleTypeId          int                         `description:"文章类型ID"`
	List                   []*IndustrialManagementResp `description:"产业列表"`
	IsSpecial              int                         `description:"是否为研选专栏"`
	SpecialTags            string                      `description:"研选专栏标签"`
	UserId                 int                         `description:"作者id"`
	SpecialType            int                         `description:"专栏类型 1:笔记，2:观点"`
	IndustryTags           string                      `description:"研选专栏行业标签"`
	CompanyTags            string                      `description:"研选专栏公司标签"`
	ArticleTypeName        string                      `description:"文章类型名称"`
	TopTime                int                         `description:"置顶时间"`
	ReportId               int                         `description:"FICC研报ID"`
	Resource               int                         `description:"来源类型，1：文章、2：产品内测、3：FICC研报"`
	ResourceObj            string                      `description:"articleficc:FICC研报、articlevmp:上海策略平台报告、articleyx:研选报告、articlespecial:研选专栏"`
}

type IndustrialManagementResp struct {
	IndustrialManagementId int    `description:"产业Id"`
	IndustryName           string `description:"产业名称"`
	ChartPermissionId      int    `description:"权限id"`
}

type ArticleCollectionLIstResp struct {
	List []*ArticleCollectionResp
}

// 研选报告收藏榜单列表
func GetReportCollectionBillboardListYx(limit int, pars []interface{}, condition string) (items []*ArticleCollectionResp, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			ac.id,
			a.category_id,
			a.article_id,
			a.title,
			a.body,
			a.annotation,
			a.abstract,
			a.publish_date,
			a.article_type_id,
			d.nick_name,
			d.department_id,
			( SELECT count( 1 ) FROM cygx_article_collect AS ac   WHERE ac.article_id = a.article_id  ) AS collect_num, 
			( SELECT count( 1 ) FROM cygx_article_collect AS ac   WHERE ac.article_id = a.article_id AND DATE_SUB( CURDATE(), INTERVAL 30 DAY ) <= date( ac.create_time )  ) AS collection_num
		FROM
			cygx_article AS a
			INNER JOIN cygx_article_collect AS ac ON ac.article_id = a.article_id 
			INNER JOIN cygx_industrial_article_group_management AS mg ON mg.article_id = a.article_id
			INNER JOIN cygx_industrial_management AS m ON m.industrial_management_id = mg.industrial_management_id
			INNER JOIN cygx_article_department AS d ON d.department_id = a.department_id 
		WHERE
			1 = 1 
			AND a.publish_status = 1  `
	if condition != "" {
		sql += condition
	}
	sql += ` GROUP BY a.article_id ORDER BY collection_num DESC,  a.publish_date DESC`
	sql += ` LIMIT ?`
	_, err = o.Raw(sql, pars, limit).QueryRows(&items)
	return
}

// 列表
func GetArticleCollectionList(condition string, userId int) (items []*ArticleCollectionResp, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			a.article_id,
			a.title,
			date_format( a.publish_date, '%Y-%m-%d' ) AS publish_date,
			m.industry_name,
			m.industrial_management_id,
			d.nick_name,
			d.department_id,
			( SELECT count( 1 ) FROM cygx_article_history_record_newpv AS h WHERE h.article_id = a.article_id ) AS pv,
			( SELECT count( 1 ) FROM cygx_article_collect AS ac  WHERE ac.article_id = a.article_id  ) AS collect_num, 
			( SELECT count( 1 ) FROM cygx_article_collect AS ac  WHERE ac.article_id = a.article_id AND DATE_SUB( CURDATE(), INTERVAL 30 DAY ) <= date( ac.create_time )  ) AS collect_num_order, 
			( SELECT count( 1 ) FROM cygx_article_collect AS ac WHERE ac.article_id = a.article_id  AND user_id = ? ) AS my_collect_num
		FROM
			cygx_article AS a
			LEFT JOIN cygx_industrial_article_group_management AS mg ON mg.article_id = a.article_id
			LEFT  JOIN cygx_industrial_management AS m ON m.industrial_management_id = mg.industrial_management_id
			LEFT JOIN cygx_article_department AS d ON d.department_id = a.department_id 
		WHERE
			1 = 1  AND a.publish_status = 1  `
	if condition != "" {
		sql += condition
	}
	_, err = o.Raw(sql, userId).QueryRows(&items)
	return
} //end

// 资源包研选跟研选专栏的搜索
//func GetArticleAndYxSpecialList(condition, conditionSpecial string, userId int) (items []*ArticleCollectionResp, err error) {
//	o := orm.NewOrm()
//	sql := `SELECT
//			a.article_id,
//			a.title,
//			date_format( a.publish_date, '%Y-%m-%d' ) AS publish_date,
//			d.nick_name,
//			d.department_id,
//			a.article_type_id,
//			0 AS is_special,
//			"" AS special_tags,
//			"" AS company_tags,
//			"" AS industry_tags,
//			( SELECT count( 1 ) FROM cygx_article_history_record_newpv AS h WHERE h.article_id = a.article_id ) AS pv,
//			( SELECT count( 1 ) FROM cygx_article_collect AS ac WHERE ac.article_id = a.article_id ) AS collect_num,
//			( SELECT count( 1 ) FROM cygx_article_collect AS ac WHERE ac.article_id = a.article_id AND user_id = ? ) AS my_collect_num,
//			'' AS special_type,
//			'' AS user_id,
//			'' AS create_time
//		FROM
//			cygx_article AS a
//			INNER JOIN cygx_industrial_article_group_management AS mg ON mg.article_id = a.article_id
//			INNER JOIN cygx_industrial_management AS m ON m.industrial_management_id = mg.industrial_management_id
//			INNER JOIN cygx_article_department AS d ON d.department_id = a.department_id
//		WHERE
//			1 = 1
//			AND a.publish_status = 1 ` + condition + `  GROUP BY article_id
//			UNION ALL
//		SELECT
//			a.id AS article_id,
//			a.title AS title,
//			date_format( a.publish_time, '%Y-%m-%d' ) AS publish_date,
//			"" AS nick_name,
//			0 AS department_id,
//			- 1 AS article_type_id,
//			1 AS is_special,
//			a.tags AS special_tags,
//			a.company_tags,
//			a.industry_tags,
//			( SELECT count( 1 ) FROM cygx_yanxuan_special_record AS h WHERE h.yanxuan_special_id = a.id ) AS pv,
//			( SELECT count( 1 ) FROM cygx_yanxuan_special_collect AS ac WHERE ac.yanxuan_special_id = a.id ) AS collect_num,
//			( SELECT count( 1 ) FROM cygx_yanxuan_special_collect AS ac WHERE ac.yanxuan_special_id = a.id AND user_id = ? ) AS my_collect_num,
//			a.type AS special_type,
//			a.user_id AS user_id,
//			a.create_time AS create_time
//		FROM
//			cygx_yanxuan_special AS a
//			JOIN cygx_yanxuan_special_author AS b ON a.user_id = b.user_id
//		WHERE
//			1 = 1
//			AND a.STATUS = 3 ` + conditionSpecial + ` ORDER BY publish_date DESC  LIMIT 30`
//
//	_, err = o.Raw(sql, userId, userId).QueryRows(&items)
//	return
//} //end

// 资源包研选跟研选专栏的搜索
func GetArticleAndYxSpecialList(condition, conditionSpecial string, userId int) (items []*ArticleCollectionResp, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			a.article_id,
			a.title,
			date_format( a.publish_date, '%Y-%m-%d' ) AS publish_date,
			d.nick_name,
			d.department_id,
			a.article_type_id,
			0 AS is_special,
			0 AS pv,
			0 AS collect_num,
			"" AS special_tags,
			"" AS company_tags,
			"" AS industry_tags,
			'' AS special_type,
			'' AS user_id,
			'' AS create_time 
		FROM
			cygx_article AS a
			LEFT  JOIN cygx_article_department AS d ON d.department_id = a.department_id 
		WHERE
			1 = 1 
			AND a.publish_status = 1 ` + condition + `  GROUP BY article_id 
			UNION ALL
		SELECT
			a.id AS article_id,
			a.title AS title,
			date_format( a.publish_time, '%Y-%m-%d' ) AS publish_date,
			"" AS nick_name,
			0 AS department_id,
			- 1 AS article_type_id,
			1 AS is_special,
			a.pv,
			a.article_collect_num as collect_num,
			a.tags AS special_tags,
			a.company_tags,
			a.industry_tags,
			a.type AS special_type,
			a.user_id AS user_id,
			a.create_time AS create_time 
		FROM
			cygx_yanxuan_special AS a
			JOIN cygx_yanxuan_special_author AS b ON a.user_id = b.user_id
		WHERE
			1 = 1 
			AND a.STATUS = 3 ` + conditionSpecial + ` ORDER BY publish_date DESC  LIMIT 30`

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

type ArticleResearchListResp struct {
	Paging *paging.PagingItem
	List   []*ArticleResearchResp
}

type ArticleResearchResp struct {
	ArticleId       int                         `description:"文章id"`
	Title           string                      `description:"标题"`
	PublishDate     string                      `description:"发布时间"`
	DepartmentId    int                         `description:"作者Id"`
	NickName        string                      `description:"作者昵称"`
	IsCollect       bool                        `description:"本人是否收藏"`
	Pv              int                         `description:"PV"`
	CollectNum      int                         `description:"收藏人数"`
	Source          int                         `description:"来源 1:弘则资源包（报告）、2：研选主题（报告）"`
	ArticleTypeId   int                         `description:"文章类型ID"`
	ArticleTypeName string                      `description:"类型名称"`
	ButtonStyle     string                      `description:"按钮展示样式"`
	IsSpecial       int                         `description:"是否为研选专栏"`
	SpecialTags     string                      `description:"研选专栏标签"`
	UserId          int                         `description:"作者id"`
	List            []*IndustrialManagementResp `description:"产业列表"`
	TopTime         int                         `description:"置顶时间"`
}

// 获取我的日程数量
func GetArticleResearchCount(condition string, pars []interface{}, needYanxuanSpecial bool) (count int, err error) {
	o := orm.NewOrm()
	sqlCount := `SELECT COUNT( 1 ) AS count FROM
			cygx_article AS a
		WHERE
			1 = 1  AND a.publish_status = 1` + condition
	if needYanxuanSpecial {
		sqlCount = `SELECT SUM(count) AS count FROM (` + sqlCount + `
		UNION ALL
	SELECT COUNT( 1 ) AS count FROM
		cygx_yanxuan_special AS a WHERE
	1 = 1  AND a.status = 3) AS c`
	}
	err = o.Raw(sqlCount, pars).QueryRow(&count)
	return
}

//func GetArticleResearchList(condition string, pars []interface{}, startSize, pageSize, userId int, needYanxuanSpecial bool) (items []*ArticleCollectionResp, err error) {
//	o := orm.NewOrm()
//	sql := `SELECT
//			a.article_id,
//			a.title,
//			a.publish_date AS publish_time,
//			a.article_type_id,
//			d.nick_name,
//			d.department_id,
//			( SELECT count( 1 ) FROM cygx_article_history_record_newpv AS h WHERE h.article_id = a.article_id ) AS pv,
//			( SELECT count( 1 ) FROM cygx_article_collect AS ac    WHERE ac.article_id = a.article_id  ) AS collect_num,
//			( SELECT count( 1 ) FROM cygx_article_collect AS ac   WHERE ac.article_id = a.article_id AND DATE_SUB( CURDATE(), INTERVAL 30 DAY ) <= date( ac.create_time )  ) AS collect_num_order,
//			( SELECT count( 1 ) FROM cygx_article_collect AS ac WHERE ac.article_id = a.article_id  AND user_id = ? ) AS my_collect_num,
//			0 AS is_special,
//			0 AS special_type,
//			0 AS user_id,
//			'' AS company_tags,
//			'' AS industry_tags
//		FROM
//			cygx_article AS a
//			INNER JOIN cygx_industrial_article_group_management AS mg ON mg.article_id = a.article_id
//			INNER JOIN cygx_industrial_management AS m ON m.industrial_management_id = mg.industrial_management_id
//			INNER JOIN cygx_article_department AS d ON d.department_id = a.department_id
//		WHERE
//			1 = 1  AND a.publish_status = 1
//		  `
//	if condition != "" {
//		sql += condition
//	}
//	sql += ` GROUP BY a.article_id  `
//	if needYanxuanSpecial {
//		sql += `UNION ALL
//	SELECT
//		a.id AS article_id,
//		a.title AS title,
//		a.publish_time AS publish_time,
//		-1 AS article_type_id,
//		b.nick_name AS nick_name,
//		a.user_id AS department_id,
//		( SELECT count( 1 ) FROM cygx_yanxuan_special_record AS h WHERE h.yanxuan_special_id = a.id ) AS pv,
//		( SELECT count( 1 ) FROM cygx_yanxuan_special_collect AS ac  WHERE ac.yanxuan_special_id = a.id  ) AS collect_num,
//		0 AS collect_num_order,
//		( SELECT count( 1 ) FROM cygx_yanxuan_special_collect AS ac WHERE ac.yanxuan_special_id = a.id  AND user_id = ? ) AS my_collect_num,
//		1 AS is_special,
//		a.type AS special_type,
//		a.user_id AS user_id,
//		a.company_tags AS company_tags,
//		a.industry_tags AS industry_tags
//	FROM
//	cygx_yanxuan_special AS a
//	JOIN cygx_yanxuan_special_author AS b ON a.user_id = b.user_id
//	WHERE
//	1 = 1  AND a.status = 3 `
//		sql += ` ORDER  BY publish_time DESC  LIMIT ?,? `
//		_, err = o.Raw(sql, userId, userId, pars, startSize, pageSize).QueryRows(&items)
//	} else {
//		sql += ` ORDER  BY publish_time DESC  LIMIT ?,? `
//		_, err = o.Raw(sql, userId, pars, startSize, pageSize).QueryRows(&items)
//	}
//
//	return
//}

func GetArticleResearchList(condition string, pars []interface{}, startSize, pageSize, userId int, needYanxuanSpecial bool) (items []*ArticleCollectionResp, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			a.article_id,
			a.title,
			a.publish_date AS publish_time,
			a.article_type_id,
			d.nick_name,
			d.department_id,
			0 AS is_special,
			0 as pv,
			0 as collect_num,
			0 AS special_type,
			0 AS user_id,
			'' AS company_tags, 
			'' AS industry_tags,
			a.top_time
		FROM
			cygx_article AS a
			INNER JOIN cygx_article_department AS d ON d.department_id = a.department_id 
		WHERE
			1 = 1  AND a.publish_status = 1
		  `
	if condition != "" {
		sql += condition
	}
	sql += ` GROUP BY a.article_id  `
	if needYanxuanSpecial {
		sql += `UNION ALL
	SELECT
		a.id AS article_id,
		a.title AS title,
		a.publish_time AS publish_time,
		-1 AS article_type_id,
		b.nick_name AS nick_name,
		a.user_id AS department_id,
		1 AS is_special,
		a.pv,
		a.article_collect_num as collect_num,
		a.type AS special_type,
		a.user_id AS user_id,
		a.company_tags AS company_tags, 
		a.industry_tags AS industry_tags,
		0 as top_time
	FROM
	cygx_yanxuan_special AS a
	JOIN cygx_yanxuan_special_author AS b ON a.user_id = b.user_id
	WHERE
	1 = 1  AND a.status = 3 `
	}

	sql += ` ORDER  BY top_time DESC, publish_time DESC  LIMIT ?,? `
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)

	return
}

// 用户收藏榜start
type IndustrialManagementHotResp struct {
	IndustrialManagementId int                   `orm:"column(industrial_management_id);pk" description:"产业id"`
	IndustryName           string                `description:"产业名称"`
	IsFollw                bool                  `description:"是否关注"`
	FollowType             int                   `description:"1,重点关注，3不感兴趣，0默认接受推送"`
	FllowNum               int                   `description:"关注数量"`
	IsNew                  bool                  `description:"是否新标签"`
	IsHot                  bool                  `description:"是否新标签"`
	IsRed                  bool                  `description:"是否标记红点"`
	Readnum                int                   `description:"阅读数量"`
	PublishDate            string                `description:"发布时间"`
	MinReportTime          string                `description:"报告最早发布时间"`
	ArticleReadNum         int                   `description:"文章阅读数量"`
	Source                 int                   `description:"来源 1:弘则资源包（报告）、2：研选主题（报告）"`
	TimeLineData           string                `description:"时间线所关联最新三篇文章的json数据"`
	ListTimeLine           []TimeLineReportResp  `description:"时间线所关联最新三篇文章列表"`
	IndustrialSubjectList  []*IndustrialSubject  `description:"标的列表"`
	IndustryVideo          *MicroVideoSimpleInfo `description:"产业视频"`
	AuthInfo               *UserPermissionAuthInfo
}

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

// 产业列表
func GetThemeHeatList(userId int, condition, conditionOrder string, startSize, pageSize int) (items []*IndustrialManagementHotResp, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			m.industry_name,
			m.industrial_management_id,
			m.article_read_num,
          	MAX( a.publish_date ) AS publish_date,
			MIN(a.publish_date) AS min_report_time,
			( SELECT count( 1 ) FROM cygx_industry_fllow AS f  WHERE f.industrial_management_id = m.industrial_management_id  AND user_id =? AND f.type = 1  ) AS fllow_num,
			m.yanxuan_article_read_num + m.activity_num AS sum_num
		FROM
			cygx_industrial_management AS m
			LEFT JOIN cygx_industrial_article_group_management AS mg ON mg.industrial_management_id = m.industrial_management_id
			LEFT JOIN cygx_article AS a ON a.article_id = mg.article_id 
			LEFT JOIN cygx_industrial_activity_group_management as ag ON ag.industrial_management_id = mg.industrial_management_id
		WHERE
			1 = 1
			AND publish_status = 1  ` + condition + `  GROUP BY m.industrial_management_id ` + conditionOrder + ` , last_updated_time  DESC LIMIT ?,?`
	_, err = o.Raw(sql, userId, startSize, pageSize).QueryRows(&items)
	return
}

// 获取数量
func GetThemeHeatListCount(condition string) (count int, err error) {
	o := orm.NewOrm()
	sql := `SELECT   COUNT( DISTINCT m.industrial_management_id ) FROM
			cygx_industrial_management AS m
			LEFT JOIN cygx_industrial_article_group_management AS mg ON mg.industrial_management_id = m.industrial_management_id
			LEFT JOIN cygx_article AS a ON a.article_id = mg.article_id 
			LEFT JOIN cygx_industrial_activity_group_management as ag ON ag.industrial_management_id = mg.industrial_management_id
		WHERE
			1 = 1
            AND a.publish_status = 1  ` + condition
	err = o.Raw(sql).QueryRow(&count)
	return
}

// 标的列表
func GetThemeHeatSubjectList(condition string) (items []*IndustrialSubject, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			m.subject_name,
			m.industrial_management_id,
			m.industrial_subject_id 
		FROM
			cygx_article AS a
			INNER JOIN cygx_industrial_article_group_subject AS mg ON mg.article_id = a.article_id
			INNER JOIN cygx_industrial_subject AS m ON m.industrial_subject_id = mg.industrial_subject_id 
		WHERE
			1 = 1`
	if condition != "" {
		sql += condition
	}
	sql += ` AND publish_status = 1 
		GROUP BY
			m.industrial_subject_id 
		ORDER BY
			publish_date DESC`
	_, err = o.Raw(sql).QueryRows(&items)
	return
} //end

// Kol sratr
type DepartmentResp struct {
	DepartmentId int    `description:"作者Id"`
	NickName     string `description:"作者昵称"`
	ImgUrl       string `description:"图片链接"`
	IsFollw      bool   `description:"是否关注"`
	IsHot        bool   `description:"是否关注"`
	FllowNum     int    `description:"关注数量"`
	List         []*IndustrialDepartmentListResp
}

type DepartmentListResp struct {
	Paging *paging.PagingItem `description:"分页数据"`
	List   []*DepartmentResp
}
type IndustrialDepartmentListResp struct {
	IndustrialManagementId int    `description:"产业Id"`
	IndustryName           string `description:"产业名称"`
	DepartmentId           int    `description:"作者Id"`
}

// 作者列表
func GetDepartmentList(condition, conditionOrder string, userId, startSize, pageSize int) (items []*DepartmentResp, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			d.nick_name,
			d.department_id,
			d.img_url,
			MAX( a.publish_date ) AS publish_date,
			( SELECT count( 1 ) FROM cygx_article_department_follow AS f  WHERE f.department_id = d.department_id  AND user_id =?  AND f.type= 1  ) AS fllow_num,
			( SELECT count( 1 ) FROM cygx_article_department_follow AS f  WHERE f.department_id = d.department_id  AND  f.type= 1  ) AS sum_num
		FROM
		cygx_article_department AS d
			INNER JOIN cygx_article AS a ON d.department_id = a.department_id
		WHERE
			1 = 1
			AND publish_status = 1  ` + condition + `
		GROUP BY
				d.department_id ` + conditionOrder + ` , last_updated_time  DESC LIMIT ?,?`
	_, err = o.Raw(sql, userId, startSize, pageSize).QueryRows(&items)
	return
}

// 获取数量
func GetDepartmentlistCount(condition string) (count int, err error) {
	o := orm.NewOrm()
	sql := `SELECT
	count(*) AS count 
FROM
	(
	SELECT
		COUNT( 1 ) AS count 
	FROM
		cygx_article_department AS d
		INNER JOIN cygx_article AS a ON d.department_id = a.department_id 
	WHERE
		1 = 1 
		AND a.article_type_id > 0 
		AND publish_status = 1 
	GROUP BY
	d.department_id 
	) c `
	err = o.Raw(sql).QueryRow(&count)
	return
}

// 作者文章所关联的产业列表
func GetIndustrialDepartmentList() (items []*IndustrialDepartmentListResp, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			m.industrial_management_id,
			m.industry_name,
			d.department_id 
		FROM
			cygx_article_department AS d
			INNER JOIN cygx_article AS a ON d.department_id = a.department_id
			INNER JOIN cygx_industrial_article_group_management AS mg ON mg.article_id = a.article_id
			INNER JOIN cygx_industrial_management AS m ON m.industrial_management_id = mg.industrial_management_id 
		WHERE
			1 = 1
			AND a.article_type_id > 0
			AND publish_status = 1
		ORDER BY
			a.publish_date DESC`
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 主题详情start
type GetThemeDetailListResp struct {
	ArticleId              int    `description:"文章id"`
	Title                  string `description:"标题"`
	PublishDate            string `description:"发布时间"`
	SubjectName            string `description:"标的名称"`
	IndustrialSubjectId    int    `description:"标的id"`
	DepartmentId           int    `description:"作者Id"`
	NickName               string `description:"作者昵称"`
	Pv                     int    `description:"PV"`
	CollectNum             int    `description:"收藏人数"`
	IndustrialManagementId int    `description:"产业Id"`
	IndustryName           string `description:"产业名称"`
	FllowNum               int    `description:"关注数量"`
	MyCollectNum           int    `description:"本人是否收藏"`
	IsCollect              bool   `description:"本人是否收藏"`
}

type GetThemeAericleListResp struct {
	ArticleId           int    `description:"文章id"`
	Title               string `description:"标题"`
	PublishDate         string `description:"发布时间"`
	SubjectName         string `description:"标的名称"`
	IndustrialSubjectId int    `description:"标的ID"`
	DepartmentId        int    `description:"作者Id"`
	NickName            string `description:"作者昵称"`
	Pv                  int    `description:"PV"`
	CollectNum          int    `description:"收藏人数"`
	FllowNum            int    `description:"关注数量"`
	MyCollectNum        int    `description:"本人是否收藏"`
	IsCollect           bool   `description:"本人是否收藏"`
}

type GetThemeAericleListBuSubjectResp struct {
	SubjectName string `description:"标的名称"`
	List        []*GetThemeAericleListResp
}

// 主题详情start
type GetThemeDetailResp struct {
	IndustrialManagementId int                  `description:"产业Id"`
	IndustryName           string               `description:"产业名称"`
	IsFollw                bool                 `description:"是否关注"`
	FollowType             int                  `description:"1,重点关注，3不感兴趣，0默认接受推送"`
	ListSubject            []*IndustrialSubject `description:"标的列表"`
	List                   []*GetThemeAericleListResp
}

// 列表
func GetThemeDetail(userId, industrialManagementId int, condition string) (items []*GetThemeDetailListResp, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			a.article_id,
			a.title,
			date_format( a.publish_date, '%Y-%m-%d' ) AS publish_date,
			m.industry_name,
			m.industrial_management_id,
			d.nick_name,
			d.department_id,
			s.industrial_subject_id,
			s.subject_name,
			( SELECT count( 1 ) FROM cygx_article_history_record_newpv AS h WHERE h.article_id = a.article_id ) AS pv,
			( SELECT count( 1 ) FROM cygx_article_collect AS ac WHERE ac.article_id = a.article_id ) AS collect_num,
			( SELECT count( 1 ) FROM cygx_article_collect AS ac WHERE ac.article_id = a.article_id and user_id = ? ) AS my_collect_num,
			( SELECT count( 1 ) FROM cygx_industry_fllow AS ac WHERE user_id = ?  AND ac.industrial_management_id = m.industrial_management_id  AND ac.type= 1) AS fllow_num 
		FROM
			cygx_article AS a
			INNER JOIN cygx_industrial_article_group_management AS mg ON mg.article_id = a.article_id
			LEFT JOIN cygx_industrial_management AS m ON m.industrial_management_id = mg.industrial_management_id
			LEFT JOIN cygx_article_department AS d ON d.department_id = a.department_id
			LEFT JOIN cygx_industrial_article_group_subject AS sg ON sg.article_id = a.article_id
			LEFT JOIN cygx_industrial_subject AS s ON s.industrial_subject_id = sg.industrial_subject_id 
		WHERE
			1 = 1
			AND m.industrial_management_id = ? 
			AND publish_status = 1 ` + condition + ` GROUP BY article_id
		ORDER BY
			publish_date DESC`
	_, err = o.Raw(sql, userId, userId, industrialManagementId).QueryRows(&items)
	return
} //end

// 用户收藏榜start
type DepartmentDetailResp struct {
	DepartmentId   int    `description:"作者Id"`
	NickName       string `description:"作者昵称"`
	ImgUrl         string `description:"图片链接"`
	FllowNum       int    `description:"多少人关注"`
	ArticleNum     int    `description:"文章数量"`
	CollectNum     int    `description:"收藏人数"`
	IsFllow        bool   `description:"是否关注"`
	List           []*ArticleCollectionResp
	ListIndustrial []*IndustrialManagementNewResp
}

type DepartmentDetail struct {
	DepartmentId int    `description:"作者Id"`
	NickName     string `description:"作者昵称"`
	ImgUrl       string `description:"图片链接"`
	FllowNum     int    `description:"多少人关注"`
	ArticleNum   int    `description:"文章数量"`
	CollectNum   int    `description:"收藏人数"`
	IsFllow      bool   `description:"是否关注"`
	MyFllowNum   int    `description:"本人是否关注"`
}

// 列表
func GetDepartmentDetail(userId, departmentId int, condition string) (item DepartmentDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			d.department_id,
			d.nick_name,
			d.img_url,
			( SELECT count( 1 ) FROM cygx_article_department_follow AS af WHERE af.user_id = ? AND af.department_id = d.department_id AND af.type= 1 ) AS my_fllow_num,
			( SELECT count( 1 ) FROM cygx_article_department_follow AS f    WHERE f.department_id = d.department_id  AND f.type= 1 ) AS fllow_num,
			( SELECT count( 1 ) FROM cygx_article AS a WHERE a.department_id = d.department_id ` + condition + `  ) AS article_num,
			( SELECT count( 1 ) FROM cygx_article_collect  AS c    WHERE c.article_id IN (SELECT  article_id FROM cygx_article AS a WHERE a.department_id = d.department_id  ` + condition + ` )) AS collect_num
		FROM
			cygx_article_department AS d 
		WHERE
			d.department_id = ?`
	err = o.Raw(sql, userId, departmentId).QueryRow(&item)
	return
} //end

// 报告搜索start
type ReoprtSearchResp struct {
	ListYx []*ArticleCollectionResp `description:"研选报告"`
	ListHz []*ArticleCollectionResp `description:"弘则报告"`
}

//// 列表
//func GetReoprtSearchList(condition string, userId int) (items []*ArticleCollectionResp, err error) {
//	o := orm.NewOrm()
//	sql := `SELECT
//			a.article_id,
//			a.title,
//			date_format( a.publish_date, '%Y-%m-%d' ) AS publish_date,
//			m.industry_name,
//			m.industrial_management_id,
//			( SELECT count( 1 ) FROM cygx_article_history_record_newpv AS h WHERE h.article_id = a.article_id ) AS pv,
//			( SELECT count( 1 ) FROM cygx_article_collect AS ac WHERE ac.article_id = a.article_id ) AS collect_num,
//			( SELECT count( 1 ) FROM cygx_article_collect AS ac WHERE ac.article_id = a.article_id  AND user_id = ?) AS my_collect_num
//		FROM
//			cygx_article AS a
//			LEFT JOIN cygx_industrial_article_group_management AS mg ON mg.article_id = a.article_id
//			LEFT JOIN cygx_industrial_management AS m ON m.industrial_management_id = mg.industrial_management_id
//		WHERE
//			1 = 1 `
//	if condition != "" {
//		sql += condition
//	}
//	_, err = o.Raw(sql, userId).QueryRows(&items)
//	return
//} //end

// 列表
func GetReoprtSearchList(condition string, userId int) (items []*ArticleCollectionResp, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			a.article_id,
			a.report_id,
			a.title,
			date_format( a.publish_date, '%Y-%m-%d' ) AS publish_date,
			m.industry_name,
			m.industrial_management_id
		FROM
			cygx_article AS a
			LEFT JOIN cygx_industrial_article_group_management AS mg ON mg.article_id = a.article_id
			LEFT JOIN cygx_industrial_management AS m ON m.industrial_management_id = mg.industrial_management_id
		WHERE
			1 = 1 `
	if condition != "" {
		sql += condition
	}
	_, err = o.Raw(sql).QueryRows(&items)
	return
} //end

// 搜索资源包 start
type SearchResourceResp struct {
	ListHz []*IndustrialManagementHotResp `description:"弘则"`
	ListYx []*IndustrialManagementHotResp `description:"研选"`
}

// 搜索资源包 start
type SearchReportAndResourceResp struct {
	ListHzResource []*IndustrialManagement        `description:"弘则资源包"`
	ListYxResource []*IndustrialManagementHotResp `description:"研选资源包"`
	ListYxReport   []*ArticleCollectionResp       `description:"研选报告"`
	ListHzReport   []*ArticleCollectionResp       `description:"弘则报告"`
}

// 产业列表
func GetSearchResourceList(userId int, condition string, startSize, pageSize int) (items []*IndustrialManagementHotResp, err error) {
	o := orm.NewOrm()
	sql := `SELECT
   			m.time_line_data,
			m.industry_name,
			m.industrial_management_id,
 			MAX( a.publish_date ) as publish_date_order,
			MIN(a.publish_date) AS min_report_time,
			date_format( MAX( a.publish_date ), '%Y-%m-%d' ) AS publish_date,
			(SELECT COUNT(1) FROM cygx_article_history_record AS rec WHERE rec.user_id = ` + strconv.Itoa(userId) + ` AND  rec.article_id=a.article_id) AS readnum 
		FROM
			cygx_industrial_management AS m
			INNER JOIN cygx_industrial_article_group_management AS mg ON mg.industrial_management_id = m.industrial_management_id
			INNER JOIN cygx_article AS a ON a.article_id = mg.article_id  AND  a.article_type != 'lyjh'
		WHERE
			1 = 1
			AND publish_status = 1 ` + condition + `  GROUP BY m.industrial_management_id  ORDER BY publish_date_order DESC `

	if startSize > 0 || pageSize > 0 {
		sql += ` LIMIT ` + strconv.Itoa(startSize) + "," + strconv.Itoa(pageSize)
	}
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 列表
func GetSearchResourceListcondition(condition string, startSize, pageSize int) (items []*IndustrialManagement, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			m.time_line_data,
			m.industry_name,
			m.chart_permission_id,
			m.industrial_management_id,
 			MAX( a.publish_date ) as publish_date_order,
			MIN( a.publish_date ) AS min_report_time,
			date_format( MAX( a.publish_date ), '%Y-%m-%d' ) AS publish_date 
		FROM
			cygx_industrial_management AS m
			INNER JOIN cygx_industrial_article_group_management AS mg ON mg.industrial_management_id = m.industrial_management_id
			INNER JOIN cygx_article AS a ON a.article_id = mg.article_id  AND  a.article_type != 'lyjh'
		WHERE
			1 = 1
			AND publish_status = 1 ` + condition + `  GROUP BY m.industrial_management_id  ORDER BY publish_date_order DESC `

	if startSize > 0 || pageSize > 0 {
		sql += ` LIMIT ` + strconv.Itoa(startSize) + "," + strconv.Itoa(pageSize)
	}
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 切换列表
type ReportBillboardTableResp struct {
	Name   string `description:"名称"`
	Source int    `description:"类型"`
	List   []*ChartPermission
}

// 切换列表
type ReportBillboardTableListResp struct {
	List []*ReportBillboardTableResp
}

// 报告榜单start
type ArticleReportBillboardResp struct {
	ArticleId       int    `description:"文章id"`
	Title           string `description:"标题"`
	PublishDate     string `description:"发布时间"`
	PermissionName  string `description:"行业名称"`
	DepartmentId    int    `description:"作者Id"`
	NickName        string `description:"作者昵称"`
	IsCollect       bool   `description:"本人是否收藏"`
	Pv              int    `description:"PV"`
	CollectNum      int    `description:"收藏人数"`
	Source          int    `description:"来源 1:弘则资源包（报告）、2：研选主题（报告）"`
	IsRoadShow      bool   `description:"是否是路演精华"`
	CategoryId      int    `description:"分类ID"`
	IsResearch      bool   `description:"是否属于研选"`
	ArticleTypeId   int    `description:"文章类型ID"`
	ArticleTypeName string `description:"文章类型名称"`
	IsSpecial       int    `description:"是否为研选专栏"`
	SpecialTags     string `description:"研选专栏标签"`
	MyCollectNum    int    `description:"本人是否收藏"`
	SpecialType     int    `description:"专栏类型 1:笔记，2:观点"`
	UserId          int    `description:"作者id"`
	List            []*IndustrialManagementIdInt
}

type ArticleReportBillboardLIstResp struct {
	List []*ArticleReportBillboardResp
}

type ArticleReportBillboardLIstPageResp struct {
	List   []*ArticleReportBillboardResp
	Paging *paging.PagingItem
}

// 报告收藏榜单列表
func GetReportCollectionBillboardList(limit int, pars []interface{}, condition string) (items []*ArticleReportBillboardResp, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			ac.id,
			a.article_id,
			a.title,
			date_format(a.publish_date, '%Y-%m-%d') AS publish_date,
			m.chart_permission_name AS permission_name,
			COUNT(ac.id) AS collection_num
		FROM
			cygx_article AS a
			INNER JOIN cygx_report_mapping AS m ON m.category_id = a.category_id
			INNER JOIN cygx_article_collect AS ac ON ac.article_id = a.article_id 
		WHERE
			1 = 1 
			AND a.publish_status = 1 `
	if condition != "" {
		sql += condition
	}
	sql += ` GROUP BY a.article_id ORDER BY collection_num DESC, ac.id DESC, a.publish_date DESC`
	sql += ` LIMIT ?`
	_, err = o.Raw(sql, pars, limit).QueryRows(&items)
	return
}

// 报告阅读榜单列表
func GetReportPvBillboardList(pars []interface{}, condition string) (items []*ArticleReportBillboardResp, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			a.article_id,
			a.title,
			date_format( a.publish_date, '%Y-%m-%d' ) AS publish_date 
		FROM
			cygx_article AS a
			INNER JOIN cygx_report_mapping AS m ON m.category_id = a.category_id
		WHERE
			1 = 1 
			AND a.publish_status = 1 `
	if condition != "" {
		sql += condition
	}
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

// 获取产业报告+晨会点评数量
func GetTimeLineReportIndustrialCount(industrialManagementId int) (count int, err error) {
	o := orm.NewOrm()
	sql := `SELECT SUM(count) AS count FROM (
SELECT
	COUNT( 1 ) count 
FROM
	cygx_article AS a
	INNER JOIN cygx_industrial_article_group_management AS man_g ON man_g.article_id = a.article_id 
WHERE
	a.publish_status = 1 
	AND a.is_class = 1 
	AND man_g.industrial_management_id = ?
	UNION ALL
	SELECT
	COUNT( 1 ) count 
	FROM
	cygx_morning_meeting_review_chapter AS mmc
	INNER JOIN cygx_morning_meeting_reviews AS mm
	WHERE
	mm.id = mmc.meeting_id
	AND mm.status = 1
	AND mmc.industry_id = ? UNION ALL
	SELECT
		COUNT( 1 ) count 
	FROM
		cygx_product_interior AS p
		INNER JOIN cygx_product_interior_industrial_group_management AS pm 
	WHERE
		p.product_interior_id = pm.product_interior_id 
		AND p.visible_range = 1 
	AND pm.industrial_management_id = ?  ) AS t `
	err = o.Raw(sql, industrialManagementId, industrialManagementId, industrialManagementId).QueryRow(&count)
	return
}

type TimeLineReportItem struct {
	Id               int                      `description:"文章或晨报点评id"`
	Title            string                   `description:"标题"`
	PublishTime      string                   `description:"发布时间"`
	Content          string                   `description:"内容"`
	VideoUrl         string                   `description:"视频链接"`
	VoiceUrl         string                   `description:"音频链接"`
	VoicePlaySeconds string                   `description:"音频时长"`
	IsHaveVideo      bool                     `description:"是否包含视频"`
	ImgUrlPc         string                   `description:"pc图片"`
	SubCategoryName  string                   `description:"二级分类"`
	IsRed            bool                     `description:"是否标红"`
	Readnum          int                      `description:"阅读数量"`
	Resource         int                      `description:"来源类型，1：文章、2：产品内测、3：晨报点评 4:活动回放视频 5:活动回放音频 "`
	LinkArticleId    int                      `description:"晨会精华报告ID链接"`
	ListSubject      []*CygxIndustrialSubject `description:"标的列表"`
}

// 获取产业报告+晨会点评列表
func GetTimeLineReportIndustrialList(userId, industrialManagementId, startSize, pageSize int) (items []*TimeLineReportItem, err error) {
	o := orm.NewOrm()
	sql := `SELECT
	* 
FROM
	(
		SELECT
		a.article_id AS id,
		a.title,
		a.publish_date AS publish_time,
		a.video_url,
		'' AS voice_url,
		a.sub_category_name,
		'' AS content,
		1 AS resource,
		'' AS voice_play_seconds,
		( SELECT COUNT( 1 ) FROM cygx_article_history_record AS rec WHERE rec.user_id = ` + strconv.Itoa(userId) + ` AND rec.article_id = a.article_id ) AS readnum 
	FROM
		cygx_article AS a
		INNER JOIN cygx_industrial_article_group_management AS man_g ON man_g.article_id = a.article_id 
	WHERE
		a.publish_status = 1 
		AND a.is_class = 1 
		AND man_g.industrial_management_id = ? GROUP BY id UNION ALL
	SELECT
		mmc.id,
		mmc.title,
		mm.publish_time AS publish_time,
		'' AS video_url,
		'' AS voice_url,
		'时间线' AS sub_category_name,
		mmc.content,
		3 AS resource,
	'' AS voice_play_seconds,
		0  AS readnum 
	FROM
		cygx_morning_meeting_review_chapter AS mmc
		INNER JOIN cygx_morning_meeting_reviews AS mm 
	WHERE
		mm.id = mmc.meeting_id 
		AND mm.STATUS = 1 
		AND mmc.industry_id = ? UNION ALL
	SELECT
		p.product_interior_id AS id,
		p.title,
		p.publish_time,
		'' AS video_url,
		'' AS voice_url,
		'' AS sub_category_name,
		'' AS content,
		2 AS resource,
		'' AS voice_play_seconds,
		0 AS readnum 
	FROM
		cygx_product_interior AS p
		INNER JOIN cygx_product_interior_industrial_group_management AS pm 
	WHERE
		p.product_interior_id = pm.product_interior_id 
		AND p.visible_range = 1 
	AND pm.industrial_management_id = ? UNION ALL
 	SELECT 
		ca.activity_id AS id,
		cav.video_name AS title,
		ca.activity_time AS publish_time,
		cav.video_url AS video_url,
		'' AS voice_url,
		'' AS sub_category_name,
		'' AS content,
		4 AS resource,
		'' AS voice_play_seconds,
		( SELECT COUNT( 1 ) FROM cygx_activity_video_history AS rec WHERE rec.user_id = ` + strconv.Itoa(userId) + ` AND rec.activity_id = ca.activity_id ) AS readnum 
	FROM 
		cygx_activity AS ca 
		INNER JOIN cygx_activity_video AS cav ON ca.activity_id = cav.activity_id 
		INNER JOIN cygx_industrial_activity_group_management AS cam ON ca.activity_id=cam.activity_id
	WHERE 
		cam.industrial_management_id = ? AND cam.source = 1  UNION ALL
 	SELECT 
		ca.activity_id AS id,
		cavo.voice_name AS title,
		ca.activity_time AS publish_time,
		'' AS video_url,
		cavo.voice_url AS voice_url,
		'' AS sub_category_name,
		'' AS content,
		5 AS resource,
		cavo.voice_play_seconds AS voice_play_seconds,
		( SELECT COUNT( 1 ) FROM cygx_activity_voice_history AS rec WHERE rec.user_id = ` + strconv.Itoa(userId) + ` AND rec.activity_id = ca.activity_id ) AS readnum 
	FROM 
		cygx_activity AS ca 
		INNER JOIN cygx_activity_voice AS cavo ON ca.activity_id = cavo.activity_id 
		INNER JOIN cygx_industrial_activity_group_management AS cam ON ca.activity_id=cam.activity_id
	WHERE 
		cam.industrial_management_id = ? AND cam.source = 1 
	) AS t 
`
	sql += ` ORDER BY 
	t.publish_time DESC LIMIT ?,? `
	_, err = o.Raw(sql, industrialManagementId, industrialManagementId, industrialManagementId, industrialManagementId, industrialManagementId, startSize, pageSize).QueryRows(&items)
	return
}

type ArticleIdReq struct {
	ArticleId   int    `description:"文章id"`
	PlaySeconds int    `description:"播放时长"`
	PageRouter  string `description:"页面路径"`
}

type IndustrialReadNum struct {
	IndustrialManagementId int `description:"产业id"`
	Readnum                int `description:"阅读次数"`
}

// 获取该产业下文章的用户阅读次数-小红点用
func GetReportIndustrialReadNumList(userId int, industrialIds string, createtime time.Time) (items []*IndustrialReadNum, err error) {
	o := orm.NewOrm()
	sql := `SELECT a.industrial_management_id, MIN(a.readnum) AS readnum FROM (
SELECT man_g.industrial_management_id,( SELECT COUNT( 1 ) FROM cygx_article_history_record AS rec WHERE rec.user_id = ` + strconv.Itoa(userId) + ` AND rec.article_id = a.article_id ) AS readnum 
FROM
	cygx_article AS a 
	INNER JOIN cygx_industrial_article_group_management as man_g ON man_g.article_id = a.article_id
WHERE
	a.publish_status = 1 
	AND a.is_class = 1
	AND man_g.industrial_management_id IN (` + industrialIds + `)  
	AND a.publish_date > ? 
GROUP BY a.article_id ORDER BY publish_date DESC
) AS a GROUP BY industrial_management_id`
	_, err = o.Raw(sql, createtime).QueryRows(&items)
	return
}

// 获取行业报告列表
func GetReportAndproductIndustrylListimgZhouqi(condition string, startSize, pageSize int) (items []*HomeArticle, total int, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			art.article_id,
			art.report_id,
			art.body,
			art.annotation,
			art.abstract,
			art.category_id,
			art.title,
			art.publish_date,
			art.sub_category_name,
			1 AS resource 
		FROM
			cygx_article AS art 
		WHERE
			art.publish_status = 1 	AND category_name = '周期'  ` + condition
	totalSql := `SELECT COUNT(1) total FROM (` + sql + `) z `
	err = o.Raw(totalSql).QueryRow(&total)
	sql += `    ORDER BY publish_date DESC LIMIT ?,? `
	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&items)
	return
}
