package models

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

type IndustrialManagementRep struct {
	IndustryName           string `description:"产业名称"`
	IndustrialManagementId int    `description:"产业id"`
	ChartPermissionId      int    `description:"权限id"`
	RecommendedIndex       int    `description:"推荐指数"`
	LayoutTime             string `description:"布局时间"`
	ArticleReadNum         int    `description:"文章阅读数量"`
	IsResearch             bool   `description:"是否属于研选"`
	IsJump                 bool   `description:"是否跳转"`
	IndustryNewLabel       bool   `description:"是否产业新标签"`
	IsFllow                bool   `description:"是否关注"`
}

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

type IndustrialManagementCount struct {
	IndustrialManagementId int `orm:"column(industrial_management_id);pk" description:"产业id"`
}

// 获取产业置顶数量分类列表
func GetIndustrialManagemenCountTop(sqlChartPermissionId string, uid int, condition string) (items []*IndustrialManagementCount, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			man_g.industrial_management_id 
			FROM
			cygx_industrial_article_group_management AS man_g
			INNER JOIN cygx_industrial_management as man ON man.industrial_management_id = man_g.industrial_management_id
			WHERE 1=1 ` + sqlChartPermissionId + `
			AND man_g.industrial_management_id IN ( SELECT industrial_management_id FROM cygx_industry_top WHERE user_id = ? ) ` + condition + `
			GROUP BY
			man_g.industrial_management_id`
	_, err = o.Raw(sql, uid).QueryRows(&items)
	return
}

// 获取产业不置顶数量
func GetIndustrialManagemenCountNoTop(sqlChartPermissionId string, uid int, condition string) (items []*IndustrialManagementCount, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			man_g.industrial_management_id 
			FROM
			cygx_industrial_article_group_management AS man_g
			INNER JOIN cygx_industrial_management as man ON man.industrial_management_id = man_g.industrial_management_id
			WHERE 1=1 ` + sqlChartPermissionId + `
			AND man_g.industrial_management_id NOT IN ( SELECT industrial_management_id FROM cygx_industry_top WHERE user_id = ? ) ` + condition + `
			GROUP BY
			man_g.industrial_management_id`
	_, err = o.Raw(sql, uid).QueryRows(&items)
	return
}

// 产业列表
func GetIndustrialManagementAll(uid int, condition, orderSrt string, startSize, pageSize int) (items []*IndustrialManagement, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			man.*,re.chart_permission_name as permission_name,
			MAX(art.article_id ) AS article_id, 
           	man.new_art_publish_date AS update_time , MIN(art.publish_date) AS min_report_time,
			IFNULL( f.follow_type_order, 0 ) AS follow_type_order 
			FROM
			cygx_industrial_management AS man
			INNER JOIN cygx_report_mapping AS re ON re.chart_permission_id = man.chart_permission_id
			INNER JOIN cygx_industrial_article_group_management AS man_g ON man_g.industrial_management_id = man.industrial_management_id
			INNER JOIN cygx_article AS art ON art.article_id = man_g.article_id 
			LEFT JOIN cygx_industry_fllow AS f ON f.industrial_management_id = man.industrial_management_id	AND f.user_id = ? 
			WHERE 1= 1
			AND re.report_type = 2 
			AND art.is_report = 1
			AND art.is_class = 1 ` + condition + `
			GROUP BY
			man.industry_name 
			ORDER BY  follow_type_order DESC ,  ` + orderSrt + ` LIMIT ?,?`
	//AND man.industrial_management_id NOT IN ( SELECT industrial_management_id FROM cygx_industry_top WHERE user_id = ` + strconv.Itoa(uid) + ` )
	_, err = o.Raw(sql, uid, startSize, pageSize).QueryRows(&items)
	return
}

// 产业列表
func GetIndustrialManagementAllCount(condition string) (count int, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			COUNT(*) as count 
		FROM
			(SELECT
			COUNT(*) 
		FROM
			cygx_industrial_management AS man
			INNER JOIN cygx_report_mapping AS re ON re.chart_permission_id = man.chart_permission_id
			INNER JOIN cygx_industrial_article_group_management AS man_g ON man_g.industrial_management_id = man.industrial_management_id
			INNER JOIN cygx_article AS art ON art.article_id = man_g.article_id 
		WHERE
			1 = 1 
			AND re.report_type = 2 
			AND art.is_report = 1 
			AND art.is_class = 1 ` + condition + ` GROUP BY man.industrial_management_id) AS num `
	err = o.Raw(sql).QueryRow(&count)
	return
}

// 产业列表 -置顶
func GetIndustrialManagementTopAll(uid int, condition string, startSize, pageSize int) (items []*IndustrialManagement, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			man.*
			FROM
			cygx_industrial_management AS man
            INNER  JOIN cygx_industry_top as top ON man.industrial_management_id = top.industrial_management_id 
			INNER JOIN cygx_report_mapping AS re ON re.chart_permission_id = man.chart_permission_id
			INNER JOIN cygx_industrial_article_group_management AS man_g ON man_g.industrial_management_id = man.industrial_management_id
			INNER JOIN cygx_article AS art ON art.article_id = man_g.article_id 
			WHERE 1=1
	
			AND top.user_id = ` + strconv.Itoa(uid) + `
			AND re.report_type = 2 
			AND art.is_report = 1
			AND art.is_class = 1 ` + condition + `
			GROUP BY
			man.industry_name 
			ORDER BY
			top.create_time DESC 	LIMIT ?,?`
	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&items)
	return
}

// 标的列表
func GetIndustrialSubjectAll(IndustrialManagementId int) (items []*IndustrialSubject, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_industrial_subject WHERE industrial_management_id = ? `
	_, err = o.Raw(sql, IndustrialManagementId).QueryRows(&items)
	return
}

// 标的列表
func GetIndustrialSubjectAllByIndustrialId(industrialIdArr []int) (items []*IndustrialSubject, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_industrial_subject WHERE industrial_management_id IN  (` + utils.GetOrmInReplace(len(industrialIdArr)) + `)   `
	_, err = o.Raw(sql, industrialIdArr).QueryRows(&items)
	return
}

// GetTopOneMonthArtReadNumIndustry 获取近一个月报告阅读数量最多的产业信息 根据行业分组
func GetTopOneMonthArtReadNumIndustryAll(condition string, pars []interface{}) (items []*IndustrialManagement, err error) {
	sql := `SELECT * FROM cygx_industrial_management WHERE 1 = 1 `
	if condition != `` {
		sql += condition
	}
	sql += ` ORDER BY article_read_num DESC `
	_, err = orm.NewOrm().Raw(sql, pars).QueryRows(&items)
	return
}

// 分析师列表
func GetIndustrialAnalystAll(IndustrialManagementId int) (items []*IndustrialAnalyst, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_industrial_analyst where industrial_management_id = ? `
	_, err = o.Raw(sql, IndustrialManagementId).QueryRows(&items)
	return
}

// 获取产业数量
func GetIndustrialManagementCount(IndustrialManagementId int) (count int, err error) {
	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_industrial_management WHERE industrial_management_id=? `
	o := orm.NewOrm()
	err = o.Raw(sqlCount, IndustrialManagementId).QueryRow(&count)
	return
}

func GetIndustrialManagementDetail(industrialManagementId int) (items *IndustrialManagementRep, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_industrial_management WHERE industrial_management_id = ?`
	err = o.Raw(sql, industrialManagementId).QueryRow(&items)
	return
}

// 获取该产业下最新的文章详情
func GetIndustrialNewArticleDetail(industrialManagementId 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 is_class = 1 AND is_report = 1
			ORDER BY
				is_report DESC,
				publish_date DESC
			LIMIT 0,1`
	err = o.Raw(sql, industrialManagementId).QueryRow(&item)
	return
}

// 修改产业是否属于新标签
func UpdateIndustrialIsNewLabel() (err error) {
	o := orm.NewOrm()
	resultTime := time.Now().AddDate(0, -2, 0).Format(utils.FormatDateTime)
	var condition string
	condition += ` AND is_hand_new_label = 0 AND  create_time < ` + "'" + resultTime + "'"
	msql := " UPDATE cygx_industrial_management SET is_new_label = 0 WHERE 1 = 1 " + condition
	_, err = o.Raw(msql).Exec()
	return
}

type IndustrialManagementId struct {
	IndustrialManagementId string `description:"产业Id"`
}

type IndustrialManagementName struct {
	IndustryName string `description:"产业名称"`
}

// 获取归类产业报告数量大于10的
func GetIndustrialMorethan10() (items []*IndustrialManagementId, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM
			( SELECT industrial_management_id, COUNT( 1 ) AS ca FROM cygx_industrial_article_group_management GROUP BY industrial_management_id ) AS na 
			WHERE ca > 10 `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 修改产业是否属于深度标签
func UpdateIndustrialIsDeepLabel(idStr string) (err error) {
	o := orm.NewOrm()
	msql := `UPDATE cygx_industrial_management
	SET is_deep_label = 1
	WHERE
	industrial_management_id IN (
		SELECT
	a.industrial_management_id
	FROM
	cygx_industrial_article_group_management AS a
	INNER JOIN cygx_article AS b ON b.id = a.cygx_article_id
	WHERE
	1 = 1
	AND b.match_type_name = '行业深度'
	AND a.industrial_management_id IN ( ` + idStr + `)
	GROUP BY
	a.industrial_management_id)`
	_, err = o.Raw(msql).Exec()
	return
}

type IndustrialManagementIdInt struct {
	IndustrialManagementId int    `description:"产业Id"`
	IndustryName           string `description:"产业名称"`
	SubjectName            string `description:"标的名称"`
	ArticleId              int    `description:"文章ID"`
	IsResearch             bool   `description:"是否属于研选"`
	ChartPermissionId      int    `description:"权限id"`
}

type IndustrialManagementIdInts struct {
	IndustrialManagementId  int    `description:"产业Id"`
	IndustryName            string `description:"产业名称"`
	SubjectNames            string `description:"标的名称"`
	ArticleId               int    `description:"文章ID"`
	IndustrialAndSubjectIds string `description:"关联标的以及产业ID"`
}

type IndustrialManagementIdName struct {
	DepartmentId int    `description:"作者ID"`
	ArticleId    int    `description:"文章id"`
	IndustryName string `description:"产业名称"`
	SubjectName  string `description:"标的名称"`
	IsReport     string `description:"1观点，0纪要"`
}

// 获取归类产业报告数量大于10的
func GetIndustrialManagementIds() (items []*IndustrialManagementIdInt, err error) {
	o := orm.NewOrm()
	//sql := `SELECT a.industrial_management_id FROM
	//		cygx_industrial_management AS a
	//		INNER JOIN cygx_industrial_subject as b ON b.industrial_management_id=a.industrial_management_id
	//		WHERE b.industrial_subject_id > 0
	//		GROUP BY a.industrial_management_id `

	sql := `SELECT industrial_management_id,industry_name FROM cygx_industrial_management `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

func GetcygxIndustrialSubject(industrialManagementId int) (items []*IndustrialSubject, err error) {
	o := orm.NewOrm()
	sql := `SELECT subject_name,industrial_subject_id FROM cygx_industrial_subject  WHERE industrial_management_id = ?`
	_, err = o.Raw(sql, industrialManagementId).QueryRows(&items)
	return
}

// 通过名称获取
func GetcygxIndustrialSubjectByName(name string) (industrial_management_id string, err error) {
	o := orm.NewOrm()
	sql := `	SELECT industrial_subject_id FROM cygx_industrial_subject  WHERE subject_name = ?`
	err = o.Raw(sql, name).QueryRow(&industrial_management_id)
	return
}

func UpdateIndustrialManagementSubjectNames(nameStr string, industrialManagementId int) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE cygx_industrial_management SET subject_names = ? WHERE industrial_management_id = ?`
	_, err = o.Raw(sql, nameStr, industrialManagementId).Exec()
	return
}

// 处理每个产业下所关联的文章的阅读量  start
func IndustrialManagementAll() (items []*IndustrialManagement, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_industrial_management `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

func GetIndustrialManagementArtCount(industrialManagementId int) (count int, err error) {
	sqlCount := ` SELECT COUNT(1) AS count  
	 			FROM  cygx_article_history_record_newpv AS h
				INNER JOIN cygx_industrial_article_group_management as mg ON  mg.article_id = h.article_id
				WHERE mg.industrial_management_id = ?  AND DATE_SUB( CURDATE(), INTERVAL 30 DAY ) <= date( h.create_time ) `
	o := orm.NewOrm()
	err = o.Raw(sqlCount, industrialManagementId).QueryRow(&count)
	return
}

type IndustrialManagementArtHistoryCount struct {
	IndustrialManagementId int `description:"产业id"`
	Count                  int `description:"数量"`
}

func GetIndustrialManagementArtHistoryCount(condition string) (items []*IndustrialManagementArtHistoryCount, err error) {
	sql := `SELECT
				COUNT( 1 ) AS count,
				mg.industrial_management_id 
			FROM
				cygx_article_history_record_newpv AS h
				INNER JOIN cygx_industrial_article_group_management AS mg ON mg.article_id = h.article_id
				INNER JOIN cygx_article AS a ON a.article_id = h.article_id 
			WHERE
				1 = 1 
				AND DATE_SUB( CURDATE(), INTERVAL 30 DAY ) <= date( h.create_time )  ` + condition + `
			GROUP BY
				mg.industrial_management_id `
	o := orm.NewOrm()
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

func GetIndustrialManagementActivityHistoryCount() (items []*IndustrialManagementArtHistoryCount, err error) {
	sql := `SELECT
			COUNT( 1 ) AS count,
			mg.industrial_management_id 
		FROM
			cygx_activity_meet_detail_log AS h
			INNER JOIN cygx_industrial_activity_group_management AS mg ON mg.activity_id = h.activity_id
			INNER JOIN cygx_activity AS a ON a.activity_id = h.activity_id 
		WHERE
			1 = 1 
			AND DATE_SUB( CURDATE(), INTERVAL 30 DAY ) <= date( a.activity_time ) 
		GROUP BY
			mg.industrial_management_id `
	o := orm.NewOrm()
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

func UpdateIndustrialManagementArtticleReadNum() (err error) {
	o := orm.NewOrm()
	sql := `UPDATE cygx_industrial_management SET article_read_num = 0 ,yanxuan_article_read_num = 0 ,activity_num = 0  `
	_, err = o.Raw(sql).Exec()
	return
}

func UpdateIndustrialManagementArtReadNum(num, industrialManagementId int) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE cygx_industrial_management SET article_read_num = ? WHERE industrial_management_id = ?`
	_, err = o.Raw(sql, num, industrialManagementId).Exec()
	return
}

func UpdateIndustrialManagementArtYanXuanReadNum(num, industrialManagementId int) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE cygx_industrial_management SET yanxuan_article_read_num = ? WHERE industrial_management_id = ?`
	_, err = o.Raw(sql, num, industrialManagementId).Exec()
	return
}

func UpdateIndustrialManagementActivityNum(num, industrialManagementId int) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE cygx_industrial_management SET activity_num = ? WHERE industrial_management_id = ?`
	_, err = o.Raw(sql, num, industrialManagementId).Exec()
	return
}

// 更新产业布局时间
func UpdateIndustrialManagementLayoutTime(layoutTime string, industrialManagementId int) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE cygx_industrial_management SET layout_time = ? WHERE industrial_management_id = ?`
	_, err = o.Raw(sql, layoutTime, industrialManagementId).Exec()
	return
}

// 获取产业下阅读数量第三的产业详情
func GetIndustrialManagementHot3(chartPermissionId int) (item *IndustrialManagementRep, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_industrial_management WHERE chart_permission_id = ? ORDER BY article_read_num DESC LIMIT 2,1`
	err = o.Raw(sql, chartPermissionId).QueryRow(&item)
	return
}

// 获取产业关联标的的数量
func GetIndustrialManagementSubjectCount(industrialManagementId int) (count int, err error) {
	sqlCount := ` SELECT COUNT(1) AS count FROM
				cygx_industrial_subject AS s 
				INNER JOIN cygx_industrial_article_group_subject as sg ON sg.industrial_subject_id = s.industrial_subject_id
				INNER JOIN cygx_article as a ON a.article_id = sg.article_id
				WHERE a.industrial_management_id = ?
				AND a.publish_status = 1`
	o := orm.NewOrm()
	err = o.Raw(sqlCount, industrialManagementId).QueryRow(&count)
	return
}

// 获取产业关联标的列表
func GetIndustrialManagementSubjectList(articleId int) (items []*IndustrialSubject, err error) {
	o := orm.NewOrm()
	sql := `SELECT
	s.subject_name 
FROM
	cygx_industrial_subject AS s
	INNER JOIN cygx_industrial_article_group_subject AS sg ON sg.industrial_subject_id = s.industrial_subject_id
	INNER JOIN cygx_article AS a 
WHERE
	sg.article_id = ? 
	AND a.publish_status = 1 
GROUP BY
	s.industrial_subject_id 
ORDER BY
	sg.id ASC 
	LIMIT 4`
	_, err = o.Raw(sql, articleId).QueryRows(&items)
	return
}

type IndustrialManagementNewResp struct {
	IndustrialManagementId int    `description:"产业Id"`
	IndustryName           string `description:"产业名称"`
	IsHot                  bool   `description:"是否是热门"`
	ArticleReadNum         int    `description:"文章阅读数量"`
}

type IndustrialManagementNewList struct {
	List []*IndustrialManagementNewResp
}

// 近期更新主题列表
func GetIndustrialManagementNewList(condition string) (items []*IndustrialManagementNewResp, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			m.industrial_management_id,
			m.industry_name,
			m.article_read_num,
			MAX( a.publish_date ) AS publish_date 
		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 
		WHERE
			1 = 1
			AND a.article_type_id > 0
			AND publish_status = 1 ` + condition + `
		GROUP BY
			m.industrial_management_id 
		ORDER BY
			publish_date DESC LIMIT 12`
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 获取产业关联标的列表
func GetIndustrialManagementForSubjecName(subjectName string, chartPermissionId int) (items []*IndustrialSubject, err error) {
	o := orm.NewOrm()
	sql := `SELECT s.subject_name,s.industrial_subject_id,m.industrial_management_id,m.industry_name,layout_time
			FROM cygx_industrial_subject as s 
			INNER JOIN cygx_industrial_management as m ON m.industrial_management_id = s.industrial_management_id
			WHERE subject_name IN (` + subjectName + `) AND m.chart_permission_id = ? `
	_, err = o.Raw(sql, chartPermissionId).QueryRows(&items)
	return
}

// 报告分类的新增与修改
func ReportArticleClassificationEditNew(reportId int, industrialManagementIdStr string, articleId int, ndustrialSubjectIdStr string) (err error) {
	to, err := orm.NewOrm().Begin()
	if err != nil {
		return
	}
	defer func() {
		fmt.Println(err)
		if err == nil {
			to.Commit()
		} else {
			to.Rollback()
		}
	}()
	//修改文章是否过滤字段
	sql := `UPDATE cygx_article SET is_filter=0,  is_class=1 WHERE article_id=? `
	_, err = to.Raw(sql, articleId).Exec()
	if err != nil {
		return
	}
	//删除文章关联标的
	sql = `	DELETE FROM cygx_industrial_article_group_subject WHERE article_id = ?`
	fmt.Println(articleId)
	_, err = to.Raw(sql, articleId).Exec()
	if err != nil {
		return
	}
	//添加文章关联标的
	if ndustrialSubjectIdStr != "0" && ndustrialSubjectIdStr != "" {
		strList := strings.Split(ndustrialSubjectIdStr, ",")
		for _, v := range strList {
			sql := `INSERT INTO cygx_industrial_article_group_subject ( cygx_article_id, article_id, industrial_subject_id, create_time ) VALUES ( ?, ?, ?, ? )`
			_, err = to.Raw(sql, reportId, articleId, v, time.Now()).Exec()
			if err != nil {
				return
			}
		}
	}
	//删除文章关联行业 （避免截断表时产生的脏数据，故不用update而是先删除再增加）
	sql = `	DELETE FROM cygx_industrial_article_group_management WHERE article_id = ?`
	_, err = to.Raw(sql, articleId).Exec()
	if err != nil {
		return
	}
	//添加文章关联行业
	industrialStrList := strings.Split(industrialManagementIdStr, ",")
	for _, v := range industrialStrList {
		sql = `	INSERT INTO cygx_industrial_article_group_management ( cygx_article_id, article_id, industrial_management_id, create_time ) VALUES ( ?, ?, ?, ? )`
		_, err = to.Raw(sql, reportId, articleId, v, time.Now()).Exec()
		if err != nil {
			return
		}
	}
	return
}

// 通过标的名称获取相关联的活动ID
func GetActivityIdListBySubjecName(subjectName string) (items []*ActivityIdRep, err error) {
	o := orm.NewOrm()
	sql := `SELECT  * FROM cygx_industrial_activity_group_subject WHERE industrial_subject_id	 IN (SELECT industrial_subject_id FROM cygx_industrial_subject WHERE subject_name IN(` + subjectName + `) ) GROUP BY activity_id`
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 产业关注榜
func GetIndustrialManagementFllowBillboard(pars []interface{}, condition, orderSrt string, startSize, pageSize int) (items []*IndustrialManagement, err error) {
	o := orm.NewOrm()
	sql := `SELECT
				man.* 
			FROM
				cygx_industrial_management AS man
				INNER JOIN cygx_report_mapping AS re ON re.chart_permission_id = man.chart_permission_id
				INNER JOIN cygx_industrial_article_group_management AS man_g ON man_g.industrial_management_id = man.industrial_management_id
				INNER JOIN cygx_article AS art ON art.article_id = man_g.article_id 
			WHERE
				1 = 1 
				AND re.report_type = 2 
				AND art.is_report = 1 
				AND art.is_class = 1 
				AND art.publish_status = 1 ` + condition + ` GROUP BY man.industrial_management_id  ORDER BY ` + orderSrt + ` LIMIT ?,?`
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

// 获取标的列表
func GetSubjectList(pars []interface{}, condition string) (items []*IndustrialManagementIdInt, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			subject_name,
			s.industrial_management_id 
		FROM
			cygx_industrial_subject AS s
			INNER JOIN cygx_industrial_article_group_subject AS sg ON sg.industrial_subject_id = s.industrial_subject_id 
		WHERE
			1 = 1 ` + condition + `
		GROUP BY
			s.industrial_subject_id`
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

// 获取标的列表
func GetIndustrialListByarticleId(pars []interface{}, condition string) (items []*IndustrialManagementIdInt, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			mg.article_id,
			m.industry_name,
			mg.industrial_management_id 
		FROM
			cygx_industrial_management AS m
			INNER JOIN cygx_industrial_article_group_management AS mg ON mg.industrial_management_id = m.industrial_management_id 
		WHERE
			1 = 1  ` + condition + ` GROUP BY  mg.article_id,	mg.industrial_management_id `
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

// 修改产业关注数量
func UpdateIndustrialManagementFllowNum(num, industrialManagementId int) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE cygx_industrial_management SET user_fllow_num = ? WHERE industrial_management_id = ?`
	_, err = o.Raw(sql, num, industrialManagementId).Exec()
	return
}

// 通过id 获取详情
func GetIndustrialManagemenDetailByAaticleID(articleId int) (items []*IndustrialManagementRep, err error) {
	o := orm.NewOrm()
	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 = ?  GROUP BY mg.industrial_management_id `
	_, err = o.Raw(sql, articleId).QueryRows(&items)
	return
}

// 获取所有的产业
func GetindustrialManagement() (items []*IndustrialManagementRep, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			i.* 
		FROM
			cygx_industrial_management AS i
			INNER JOIN cygx_industrial_article_group_management AS m ON m.industrial_management_id = i.industrial_management_id 
		GROUP BY
			i.industrial_management_id `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// GetActiveArticleIndustryIds 获取有已归类行业报告的行业IDs
func GetActiveArticleIndustryIds() (ids []int, err error) {
	sql := `SELECT
				man.industrial_management_id
			FROM
				cygx_industrial_management AS man
			JOIN cygx_report_mapping AS re ON re.chart_permission_id = man.chart_permission_id
			JOIN cygx_industrial_article_group_management AS man_g ON man_g.industrial_management_id = man.industrial_management_id
			JOIN cygx_article AS art ON art.article_id = man_g.article_id
			WHERE
				1 = 1 AND re.report_type = 2 AND art.is_report = 1 AND art.is_class = 1 AND art.publish_status = 1
			GROUP BY
				man.industrial_management_id`
	_, err = orm.NewOrm().Raw(sql).QueryRows(&ids)
	return
}

// GetTopOneMonthArtReadNumIndustry 获取近一个月报告阅读数量最多的产业信息
func GetTopOneMonthArtReadNumIndustry(condition string, pars []interface{}) (item *IndustrialManagement, err error) {
	sql := `SELECT * FROM cygx_industrial_management WHERE 1 = 1 `
	if condition != `` {
		sql += condition
	}
	sql += ` ORDER BY article_read_num DESC LIMIT 1`
	err = orm.NewOrm().Raw(sql, pars).QueryRow(&item)
	return
}

// GetSourceIndustryByName 通过名称获取资源包产业
func GetSourceIndustryByName(industryName string) (item *IndustrialManagement, err error) {
	sql := `SELECT
				m.industry_name,
				m.industrial_management_id,
				m.chart_permission_id
			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 m.industry_name = ? AND a.publish_status = 1 AND a.article_id < 1000000
			GROUP BY
				m.industrial_management_id`
	err = orm.NewOrm().Raw(sql, industryName).QueryRow(&item)
	return
}

// GetIndustryByName 通过名称获取产业
func GetIndustryByName(industryName string) (item *IndustrialManagement, err error) {
	sql := `SELECT * FROM cygx_industrial_management WHERE industry_name = ? LIMIT 1`
	err = orm.NewOrm().Raw(sql, industryName).QueryRow(&item)
	return
}

type IndustrialManagementArticle struct {
	IndustrialManagementId int    `description:"产业Id"`
	IndustryName           string `description:"产业名称"`
	ArticleId              int    `description:"文章ID"`
	PublishDate            string `description:"发布时间"`
}

// 时间线的更新时间
func GetTimeLineReportIndustrialPublishdateList(industrialIdArr []int) (items []*IndustrialManagementArticle, err error) {
	if len(industrialIdArr) == 0 {
		return
	}
	o := orm.NewOrm()
	sql := `SELECT	
			mmc.id,
			0,
			mmc.industry_id AS industrial_management_id,			
			mmc.content AS title,
			MAX( mm.meeting_time ) AS publish_date 
		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 IN (` + utils.GetOrmInReplace(len(industrialIdArr)) + `)
		GROUP BY industrial_management_id ORDER BY publish_date DESC  `
	_, err = o.Raw(sql, industrialIdArr).QueryRows(&items)
	return
}

// 获取该产业下最新的文章详情
func GetNewArticleDetailByIndustrialIds(industrialIdArr []int) (items []*IndustrialManagementArticle, err error) {
	arrLen := len(industrialIdArr)
	if arrLen == 0 {
		return
	}
	o := orm.NewOrm()
	sql := `SELECT
			mg.industrial_management_id,
			MAX( a.article_id ) AS article_id,
			a.title,
			MAX( a.publish_date ) AS publish_date 
		FROM
			cygx_industrial_article_group_management AS mg
			INNER JOIN cygx_article AS a ON mg.article_id = a.article_id 
		WHERE
			1 = 1
			AND a.is_report = 1
			AND a.is_class = 1
			AND mg.industrial_management_id IN(` + utils.GetOrmInReplace(len(industrialIdArr)) + `)   
		GROUP BY
			mg.industrial_management_id `
	_, err = o.Raw(sql, industrialIdArr).QueryRows(&items)
	return
}

// 获取该产业下最新的产品内测详情
func GetNewProductInteriorByIndustrialIds(industrialIdArr []int) (items []*IndustrialManagementArticle, err error) {
	arrLen := len(industrialIdArr)
	if arrLen == 0 {
		return
	}
	o := orm.NewOrm()
	sql := `SELECT
			mg.industrial_management_id,
			MAX( a.product_interior_id ) AS article_id,
			a.title,
			MAX( a.publish_time ) AS publish_date 
		FROM
			cygx_product_interior_industrial_group_management AS mg
			INNER JOIN cygx_product_interior AS a ON mg.product_interior_id = a.product_interior_id 
		WHERE
			1 = 1 
			AND a.STATUS = 1 
			AND a.visible_range = 1 
			AND mg.industrial_management_id IN(` + utils.GetOrmInReplace(len(industrialIdArr)) + `)   
		GROUP BY
			mg.industrial_management_id`
	_, err = o.Raw(sql, industrialIdArr).QueryRows(&items)
	return
}

// GetIndustrialManagementArticleNewPublishData 获取产业关联文章的最新发布时间
func GetIndustrialManagementArticleNewPublishData() (items []*IndustrialManagement, err error) {
	o := orm.NewOrm()
	sql := `SELECT
			man.industrial_management_id,
			MAX( art.publish_date ) AS update_time 
		FROM
			cygx_industrial_management AS man
			INNER JOIN cygx_report_mapping AS re ON re.chart_permission_id = man.chart_permission_id
			INNER JOIN cygx_industrial_article_group_management AS man_g ON man_g.industrial_management_id = man.industrial_management_id
			INNER JOIN cygx_article AS art ON art.article_id = man_g.article_id 
		WHERE
			1 = 1 
			AND re.report_type = 2 
			AND art.is_report = 1 
			AND art.is_class = 1 
		GROUP BY
			man.industry_name 
		ORDER BY
			update_time DESC`
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// UpdateIndustrialManagementArticleNewPublishData 批量修改获取产业关联文章的最新发布时间
func UpdateIndustrialManagementArticleNewPublishData(items map[int]string) (err error) {
	o := orm.NewOrm()
	p, err := o.Raw("UPDATE cygx_industrial_management SET new_art_publish_date = ? WHERE industrial_management_id = ?").Prepare()
	if err != nil {
		return
	}
	defer func() {
		_ = p.Close() // 别忘记关闭 statement
	}()
	for k, v := range items {
		_, err = p.Exec(v, k)
		if err != nil {
			return
		}
	}
	return
}

// UpdateIndustrialManagementInit 初始化每月产业用户关注数量
func UpdateIndustrialManagementInit() (err error) {
	o := orm.NewOrm()
	sql := `UPDATE cygx_industrial_management SET one_month_follow_num = 0 `
	_, err = o.Raw(sql).Exec()
	return
}

// UpdateIndustrialManagementOneMonthFollowNumMulti  批量修改每月产业用户关注数量
func UpdateIndustrialManagementOneMonthFollowNumMulti(items []*CygxIndustryFllowNumResp) (err error) {
	o := orm.NewOrm()
	p, err := o.Raw(` UPDATE cygx_industrial_management SET one_month_follow_num = ? WHERE industrial_management_id = ?  `).Prepare()
	if err != nil {
		return
	}
	defer func() {
		_ = p.Close() // 别忘记关闭 statement
	}()
	for _, v := range items {
		_, err = p.Exec(
			v.Total,
			v.IndustrialManagementId)
		if err != nil {
			return
		}
	}
	return
}

// 标的列表
func GetIndustrialSubjectAllByIndustrialIdcondition(pars []interface{}, 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
			AND a.publish_status = 1  ` + condition + `
		GROUP BY
			m.industrial_subject_id 
ORDER BY
	a.publish_date DESC  `
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

// 获取该产业下最新的文章详情
func GetNewArticleDetailByIndustrialIdscondition(pars []interface{}, condition string) (items []*IndustrialManagementArticle, err error) {
	//arrLen := len(industrialIdArr)
	//if arrLen == 0 {
	//	return
	//}
	o := orm.NewOrm()
	sql := `SELECT
			mg.industrial_management_id,
			MAX( a.article_id ) AS article_id,
			a.title,
			MAX( a.publish_date ) AS publish_date 
		FROM
			cygx_industrial_article_group_management AS mg
			INNER JOIN cygx_article AS a ON mg.article_id = a.article_id 
		WHERE
			1 = 1   ` + condition + `
		GROUP BY
			mg.industrial_management_id `
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

// UpdateIndustrialManagementTimeLineData   更新时间线关联对应最新文章的数据信息
func UpdateIndustrialManagementTimeLineData(industrialManagementId int, timeLineData string) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE cygx_industrial_management SET time_line_data = ? WHERE  industrial_management_id = ?   `
	_, err = o.Raw(sql, timeLineData, industrialManagementId).Exec()
	return
}

// GetIndustryListByCondition 获取产业列表
func GetIndustryListByConditionByIds(industrialManagementIds []int) (list []*IndustrialManagementRep, err error) {
	lenArr := len(industrialManagementIds)
	if lenArr == 0 {
		return
	}
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_industrial_management WHERE  industrial_management_id IN (` + utils.GetOrmInReplace(lenArr) + `) `
	_, err = o.Raw(sql, industrialManagementIds).QueryRows(&list)
	return
}
