package cygx

import (
	"github.com/beego/beego/v2/client/orm"
	"hongze/hz_crm_api/utils"
	"strconv"
	"time"
)

type CygxIndustrialArticleGroupManagement struct {
	Id                     int       `orm:"column(id);pk" description:"主键ID"`
	CygxArticleId          int       `description:"cygx_article表的主键ID"`
	ArticleId              int       `description:"cygx_article表的文章ID"`
	IndustrialManagementId int       `description:"cygx_industrial_management表的主键ID"`
	CreateTime             time.Time `description:"创建时间"`
}

// 新增
func AddCygxIndustrialArticleGroupManagement(item *CygxIndustrialArticleGroupManagement) (newId int64, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	_, err = o.Insert(item)
	if err != nil {
		return
	}
	return
}

// 列表
func GetIndustrialArticleGroupManagementList(articleId int) (items []*IndustrialActivityGroupManagementRep, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
			m.chart_permission_id,
			m.industrial_management_id,
			m.industry_name 
			FROM
			cygx_industrial_article_group_management AS am
			INNER JOIN cygx_industrial_management AS m ON m.industrial_management_id = am.industrial_management_id
			WHERE
			am.article_id = ?`
	_, err = o.Raw(sql, articleId).QueryRows(&items)
	return
}

type IndustrialArticleGroupManagementRep struct {
	IndustrialManagementId int    `description:"cygx_industrial_management表的主键ID"`
	IndustryName           string `description:"产业名称"`
	ChartPermissionId      int    `description:"权限id"`
	PermissionName         string `description:"行业名称"`
	ArticleId              int    `description:"cygx_article表的文章ID"`
}

// 列表
func GetIndustrialArticleGroupManagementListByindustrialId(articleId int) (items []*IndustrialArticleGroupManagementRep, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
			am.article_id
			FROM
			cygx_industrial_article_group_management AS am
			INNER JOIN cygx_industrial_management AS m ON m.industrial_management_id = am.industrial_management_id
			WHERE
			am.industrial_management_id = ?`
	_, err = o.Raw(sql, articleId).QueryRows(&items)
	return
}

// 通过名称获取详情
func GetIndustrialManagemenDetailByAaticle(articleId int) (item *CygxIndustrialArticleGroupManagement, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_industrial_article_group_management WHERE article_id = ? `
	err = o.Raw(sql, articleId).QueryRow(&item)
	return
}

func GetArticleIdsByIndustrialManagementId(industrialManagementId string) (articleId string, err error) {
	sql := ` SELECT
			GROUP_CONCAT( DISTINCT article_id ORDER BY id ASC SEPARATOR ',' ) AS articleId 
			FROM
			cygx_industrial_article_group_management WHERE industrial_management_id IN (` + industrialManagementId + `)`
	o := orm.NewOrmUsingDB("hz_cygx")
	err = o.Raw(sql).QueryRow(&articleId)
	return
}

type ArticleIndustrialSubjectNameResp struct {
	ArticleId              int    `description:"文章id"`
	IndustryName           string `description:"产业名称"`
	SubjectNameStr         string `description:"关联标的"`
	IndustrialManagementId int    `description:"产业id"`
}

// 通过文章ID获取所关联的产业与标的
func GetCygxArticleIndustrialSubjectName(articleIds string) (items []*ArticleIndustrialSubjectNameResp, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := ` SELECT
			art.article_id,
			(
			SELECT
				GROUP_CONCAT( DISTINCT s.subject_name SEPARATOR '/' ) 
			FROM
				cygx_industrial_subject AS s 
			WHERE
				s.industrial_subject_id IN ( SELECT industrial_subject_id FROM cygx_industrial_article_group_subject AS sg WHERE sg.article_id = art.article_id ) 
			) AS subject_name_str,
			(
			SELECT
				GROUP_CONCAT( DISTINCT man.industry_name SEPARATOR '/' ) 
			FROM
				cygx_industrial_management AS man 
			WHERE
				man.industrial_management_id IN ( SELECT industrial_management_id FROM cygx_industrial_article_group_management AS man_g WHERE man_g.article_id = art.article_id ) 
			) AS industry_name 
		FROM
			cygx_article AS art   
		WHERE art.article_id IN(` + articleIds + `)`

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

type IndustrialArticleGroupResp struct {
	ArticleId              int    `description:"活动ID"`
	IndustrialManagementId int    `description:"cygx_industrial_management表的主键ID"`
	IndustryName           string `description:"产业名称"`
}

// 通过id 获取详情
func GetIndustrialManagemenDetailByAaticleID(articleId int) (items []*ArticleIndustrialSubjectNameResp, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
			article_id,
			m.industrial_management_id,
			industry_name 
		FROM
			cygx_industrial_article_group_management AS mg
			INNER JOIN cygx_industrial_management AS m ON mg.industrial_management_id = m.industrial_management_id 
		WHERE
			mg.article_id = ? `
	_, err = o.Raw(sql, articleId).QueryRows(&items)
	return
}

// 列表
func GetIndustrialArticleGroupListByarticleIds(articleIds string) (items []*IndustrialArticleGroupResp, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT  mg.*,m.industry_name  FROM
	        cygx_industrial_article_group_management AS mg
	      	 INNER JOIN cygx_industrial_management AS m ON m.industrial_management_id = mg.industrial_management_id 
			WHERE 1 = 1 
			AND mg.article_id IN (` + articleIds + `) GROUP BY  mg.article_id,mg.industrial_management_id`
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 根据文章ID数组获取关联的产业列表
func GetIndustrialArticleGroupListByarticleIdsArr(articleIds []int) (items []*IndustrialArticleGroupResp, err error) {
	lenArr := len(articleIds)
	if lenArr == 0 {
		return
	}
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT  mg.*,m.industry_name  FROM
	        cygx_industrial_article_group_management AS mg
			INNER JOIN cygx_industrial_management AS m ON m.industrial_management_id = mg.industrial_management_id 
			WHERE 1 = 1 
			AND mg.article_id IN  (` + utils.GetOrmInReplace(lenArr) + `)  GROUP BY  mg.article_id,mg.industrial_management_id`
	_, err = o.Raw(sql, articleIds).QueryRows(&items)
	return
}

// 用户收藏榜start
type IndustrialManagementHotResp struct {
	IndustrialManagementId int                      `orm:"column(industrial_management_id);pk" description:"产业id"`
	IndustryName           string                   `description:"产业名称"`
	IsFollw                bool                     `description:"是否关注"`
	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：研选主题（报告）"`
	IndustrialSubjectList  []*CygxIndustrialSubject `description:"标的列表"`
}

// 产业与文章关联列表
func GetSearchResourceList(userId int, condition string, startSize, pageSize int) (items []*IndustrialManagementHotResp, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
			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
}
