package cygx

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

type IndustrialManagementAdd struct {
	IndustryName      string `description:"产业名称"`
	PermissionName    string `description:"行业名称"`
	ChartPermissionId int    `description:"权限id"`
	RecommendedIndex  int    `description:"推荐指数"`
	LayoutTime        string `description:"布局时间"`
	IsNewLabel        int    `description:"是否属于新标签，1是，0否"`
	Source            int    `description:"来源,1正常添加，2：通过文章添加，3通过活动添加(默认为1)"`
}

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

type NewId struct {
	NewId             string `description:"新增一条数据产生的新的ID"`
	ChartPermissionId int    `description:"行业ID"`
}

type CygxIndustrialManagement struct {
	IndustrialManagementId int       `orm:"column(industrial_management_id);pk" description:"产业id"`
	IndustryName           string    `description:"产业名称"`
	ChartPermissionId      int       `description:"权限id"`
	RecommendedIndex       int       `description:"推荐指数"`
	CreateTime             time.Time `description:"创建时间"`
	LayoutTime             string    `description:"布局时间"`
	IsNewLabel             int       `description:"是否属于新标签，1是，0否"`
	IsHandNewLabel         int       `description:"是否手动修改新标签，1是，0否"`
	IsDeepLabel            int       `description:"是否属于深度标签，1是，0否"`
	IsHandDeepLabel        int       `description:"是否手动修改深度标签，1是，0否"`
	Source                 int       `description:"来源,1正常添加，2：通过文章添加，3通过活动添加(默认为1)"`
	NewArtPublishDate      string    `description:"关联的最新文章发布时间，排序使用"`
}

type CygxIndustrialManagementEdit struct {
	IndustrialManagementId int       `orm:"column(industrial_management_id);pk" description:"产业id"`
	IndustryName           string    `description:"产业名称"`
	ChartPermissionId      int       `description:"权限id"`
	RecommendedIndex       int       `description:"推荐指数"`
	CreateTime             time.Time `description:"创建时间"`
	LayoutTime             string    `description:"布局时间"`
	IsNewLabel             int       `description:"是否属于新标签，1是，0否"`
	IsDeepLabel            int       `description:"是否属于深度标签，1是，0否"`
}

type CygxIndustrialManagementDetail struct {
	IndustrialManagementId int       `orm:"column(industrial_management_id);pk" description:"产业id"`
	IndustryName           string    `description:"产业名称"`
	ChartPermissionId      int       `description:"权限id"`
	RecommendedIndex       int       `description:"推荐指数"`
	CreateTime             time.Time `description:"创建时间"`
	LayoutTime             string    `description:"布局时间"`
	IsNewLabel             int       `description:"是否属于新标签，1是，0否"`
	IsDeepLabel            int       `description:"是否属于新标签，1是，0否"`
}

type CygxIndustrialManagementDetailRep struct {
	IndustrialManagementId int       `orm:"column(industrial_management_id);pk" description:"产业id"`
	IndustryName           string    `description:"产业名称"`
	ChartPermissionId      int       `description:"权限id"`
	RecommendedIndex       int       `description:"推荐指数"`
	CreateTime             time.Time `description:"创建时间"`
	LayoutTime             string    `description:"布局时间"`
	IsNewLabel             int       `description:"是否属于新标签，1是，0否"`
	IsDeepLabel            int       `description:"是否属于新标签，1是，0否"`
	IsShowNewLabel         bool      `description:"是否展示新标签"`
	IsShowDeepLabel        bool      `description:"是否展示深度标签"`
}

type CygxIndustrialManagementNum struct {
	IndustrialManagementId int       `orm:"column(industrial_management_id);pk" description:"产业id"`
	IndustryName           string    `description:"产业名称"`
	ChartPermissionId      int       `description:"权限id"`
	RecommendedIndex       int       `description:"推荐指数"`
	CreateTime             time.Time `description:"创建时间"`
	LayoutTime             string    `description:"布局时间"`
	ArtNum                 int       `description:"文章数量"`
	ActNum                 int       `description:"活动数量"`
	IsRelevance            bool      `description:"是否存在关联文章"`
	HzCover                bool      `description:"是否弘则覆盖"`
}

type CygxIndustrialManagementNumCheckName struct {
	ChartPermissionId int       `orm:"column(industrial_management_id);pk" description:"产业id"`
	PermissionName    string    `orm:"column(industry_name)" description:"产业名称"`
	RecommendedIndex  int       `description:"推荐指数"`
	CreateTime        time.Time `description:"创建时间"`
	LayoutTime        string    `description:"布局时间"`
	ArtNum            int       `description:"文章数量"`
	IsRelevance       bool      `description:"是否存在关联文章"`
}

type GetIndustrialManagementList struct {
	List []*CygxIndustrialManagementNum
}

type GetCygxIndustrialManagementList struct {
	List []*ArtGroupIndustrialManagementRep
}

// 新增
func AddIndustrialManagement(item *CygxIndustrialManagement) (newId int64, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	newId, err = o.Insert(item)
	return
}

// 列表
func GetIndustrialManagementAll(condition, orderColumn string) (items []*CygxIndustrialManagementNum, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT *,
		( SELECT COUNT( 1 ) FROM cygx_industrial_article_group_management AS man_g WHERE man_g.industrial_management_id = man.industrial_management_id ) AS art_num,
		( SELECT COUNT( 1 ) FROM cygx_industrial_activity_group_management AS a_g  INNER JOIN cygx_activity AS a ON a.activity_id = a_g.activity_id  WHERE a_g.industrial_management_id = man.industrial_management_id AND a.publish_status = 1 ) AS act_num
		FROM
		cygx_industrial_management AS man 
		WHERE 1 =1 `
	if condition != "" {
		sql += condition
	}
	sql += `   ORDER BY ` + orderColumn + ` ASC`
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 列表
func GetIndustrialManagementAllCheckName(ChartPermissionId int, orderColumn string) (items []*CygxIndustrialManagementNumCheckName, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT *
		FROM
		cygx_industrial_management AS man 
		WHERE
		man.chart_permission_id = ?  ORDER BY ` + orderColumn + ` ASC`
	_, err = o.Raw(sql, ChartPermissionId).QueryRows(&items)
	return
}

func GetIndustrialManagementAllByReportTime(condition, orderSrt string) (items []*CygxIndustrialManagementNum, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
			man.*,art.publish_date,man_g.industrial_management_id as man_gid,
			MAX( art.publish_date ) AS update_time,
			( SELECT COUNT( 1 ) FROM cygx_industrial_article_group_management AS man_g WHERE man_g.industrial_management_id = man.industrial_management_id ) AS art_num ,
			( SELECT COUNT( 1 ) FROM cygx_industrial_activity_group_management AS a_g  INNER JOIN cygx_activity AS a ON a.activity_id = a_g.activity_id  WHERE a_g.industrial_management_id = man.industrial_management_id AND a.publish_status = 1 ) AS act_num
			FROM
			cygx_industrial_management AS man
			LEFT JOIN cygx_industrial_article_group_management AS man_g ON man_g.industrial_management_id = man.industrial_management_id 
			LEFT	JOIN cygx_article AS art ON art.article_id = man_g.article_id
			WHERE 1=1 `
	if condition != "" {
		sql += condition
	}
	sql += ` GROUP BY  industry_name  ORDER BY ` + orderSrt
	//fmt.Println(sql)
	//ORDER BY update_time DESC`
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 获取产业数量
func GetIndustrialManagementCount(condition string, pars []interface{}) (count int, err error) {
	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_industrial_management WHERE 1=1 `
	if condition != "" {
		sqlCount += condition
	}
	o := orm.NewOrmUsingDB("hz_cygx")
	err = o.Raw(sqlCount, pars).QueryRow(&count)
	return
}

// 修改
func EditIndustrialManagement(item *CygxIndustrialManagement) (err error) {
	sql := `UPDATE cygx_industrial_management SET chart_permission_id=?, industry_name=?, recommended_index=?, layout_time=?,is_new_label=?,is_deep_label=?,is_hand_new_label=?,is_hand_deep_label=?  WHERE industrial_management_id=? `
	o := orm.NewOrmUsingDB("hz_cygx")
	_, err = o.Raw(sql, item.ChartPermissionId, item.IndustryName, item.RecommendedIndex, item.LayoutTime, item.IsNewLabel, item.IsDeepLabel, item.IsHandNewLabel, item.IsHandDeepLabel, item.IndustrialManagementId).Exec()
	return
}

// 通过活动添加的标签产业添加的时候二次修改
func EditIndustrialManagementFromAct(item *CygxIndustrialManagement) (err error) {
	sql := `UPDATE cygx_industrial_management SET  recommended_index=?, layout_time=?,is_new_label=?,is_deep_label=?,is_hand_new_label=?,is_hand_deep_label=?, source = 1  WHERE industry_name=? AND chart_permission_id=?`
	o := orm.NewOrmUsingDB("hz_cygx")
	_, err = o.Raw(sql, item.RecommendedIndex, item.LayoutTime, item.IsNewLabel, item.IsDeepLabel, item.IsHandNewLabel, item.IsHandDeepLabel, item.IndustryName, item.ChartPermissionId).Exec()
	return
}

// 删除数据
func DeleteIndustrialManagement(industrialManagementId int) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	//删除产业
	sql := ` DELETE FROM cygx_industrial_management WHERE industrial_management_id = ?`
	_, err = to.Raw(sql, industrialManagementId).Exec()
	if err != nil {
		return
	}

	//删除产业关联的活动
	sql = ` DELETE FROM cygx_industrial_activity_group_management WHERE industrial_management_id = ?`
	_, err = to.Raw(sql, industrialManagementId).Exec()

	return
}

// 获取产业数量
func GetIndustrialManagementInfo(industrialManagementId int) (item *CygxIndustrialManagement, err error) {
	sqlCount := ` SELECT *  FROM cygx_industrial_management WHERE industrial_management_id= ? `
	o := orm.NewOrm()
	err = o.Raw(sqlCount, industrialManagementId).QueryRow(&item)
	return
}

// 获取产业关联的文章数量
func GetIndustrialManagementGroupArtCount(industrialManagementId int) (count int, err error) {
	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_industrial_article_group_management WHERE industrial_management_id=? `
	o := orm.NewOrmUsingDB("hz_cygx")
	err = o.Raw(sqlCount, industrialManagementId).QueryRow(&count)
	return
}

type CygxIndustrialManagementExport struct {
	IndustrialManagementId int    `orm:"column(industrial_management_id);pk" description:"产业id"`
	ChartPermissionName    string `description:"行业"`
	IndustryName           string `description:"产业名称"`
	RecommendedIndex       int    `description:"推荐指数"`
	SubjectName            string `description:"标的名称"`
	AnalystName            string `description:"分析师名称"`
}

func GetChartPermissionExport(chartPermissionId int) (items []*CygxIndustrialManagementExport, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
		mp.chart_permission_name,
		man.industry_name,
		man.industrial_management_id,
		man.recommended_index,
		sub.subject_name,
		ana.analyst_name
		FROM
			cygx_report_mapping AS mp
		LEFT  JOIN cygx_industrial_management as man ON man.chart_permission_id = mp.chart_permission_id
		LEFT JOIN cygx_industrial_subject as sub ON sub.industrial_management_id = man.industrial_management_id
		LEFT JOIN cygx_industrial_analyst as ana ON ana.industrial_management_id = man.industrial_management_id
		WHERE mp.chart_permission_id = 20`
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

type CygxIndustrialManagementIdStr struct {
	ChartPermissionId   int    `description:"行业ID"`
	ChartPermissionName string `description:"行业名称"`
	MatchTypeName       string `description:"匹配类型"`
}

func GetChartPermissionIdStr() (items []*CygxIndustrialManagementIdStr, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_report_mapping WHERE report_type = 1 AND chart_permission_id != 23 GROUP BY chart_permission_id  ORDER BY sort DESC `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

type IndustrialManagementExport struct {
	ChartPermissionName       string `description:"行业"`
	ChartPermissionReportName string `description:"行业报告数量"`
	IndustrialManagementId    int    `orm:"column(industrial_management_id);pk" description:"产业id"`
	IndustryName              string `description:"产业名称"`
	ChartPermissionId         int    `description:"权限id"`
	RecommendedIndex          int    `description:"推荐指数"`
	SubjectName               string `description:"标的名称"`
	AnalystName               string `description:"分析师名称"`
	ReportNum                 string `description:"产业报告数量"`
}

func GetIndustrialManagementIdStr(chartPermissionId int) (items []*IndustrialManagementExport, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_industrial_management WHERE chart_permission_id = ?`
	_, err = o.Raw(sql, chartPermissionId).QueryRows(&items)
	return
}

type GetReportNumLIstExport struct {
	MatchTypeName string `description:"权限id"`
	TypeNum       int    `description:"数量"`
}

func GetReportNumLIst(industrialManagementId int) (items []*GetReportNumLIstExport, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
		rep.match_type_name,
		COUNT(match_type_name) type_num 
		FROM
		  cygx_report_mapping AS rep
			LEFT  JOIN cygx_article AS art ON	art.category_id  = rep.category_id
			LEFT JOIN cygx_industrial_article_group_management AS map_g ON map_g.cygx_article_id =art.id 
		WHERE
			map_g.industrial_management_id = ?
			AND art.sub_category_name = rep.sub_category_name
			GROUP BY rep.match_type_name
`
	_, err = o.Raw(sql, industrialManagementId).QueryRows(&items)
	return
}

type GetMatchTypeListRep struct {
	ChartPermissionId int    `description:"行业ID"`
	MatchTypeName     string `description:"匹配类型"`
}

func GetMatchTypeList(chartPermissionId int) (items []*GetMatchTypeListRep, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_report_mapping WHERE chart_permission_id = ?  GROUP BY match_type_name `
	_, err = o.Raw(sql, chartPermissionId).QueryRows(&items)
	return
}

// 获取产业关联的文章数量
func GetchartPermissionReportNameCount(industrialManagementId int) (count int, err error) {
	sqlCount := ` SELECT COUNT(1) as count FROM cygx_article  as art 
	INNER JOIN cygx_report_mapping as re ON re.category_id = art.category_id
WHERE
	re.report_type = 1
	AND re.chart_permission_id = ?  `
	o := orm.NewOrmUsingDB("hz_cygx")
	err = o.Raw(sqlCount, industrialManagementId).QueryRow(&count)
	return
}

type IndustrialManagementDetial struct {
	LayoutTime  string `description:"布局时间"`
	ArtTotalNum int    `description:"文章总数量"`
	List        []*IndustrialManagementArtTypeList
}

// 通过产业ID获取详情
func GetindustrialManagemenById(industrialManagementId int) (item *CygxIndustrialManagementNum, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT man.layout_time, art.publish_date as create_time,
			( SELECT COUNT( 1 ) FROM cygx_industrial_article_group_management AS man_g INNER JOIN cygx_article AS art ON art.article_id = man_g.article_id  WHERE man_g.industrial_management_id = man.industrial_management_id AND art.publish_status = 1 ) AS art_num 
			FROM
			cygx_industrial_management AS man 
			LEFT JOIN cygx_industrial_article_group_management as mang ON mang.industrial_management_id = man.industrial_management_id
			LEFT JOIN cygx_article as art ON art.article_id = mang.article_id
			WHERE
			man.industrial_management_id = ?
			ORDER BY art.publish_date ASC LIMIT 1`
	err = o.Raw(sql, industrialManagementId).QueryRow(&item)
	return
}

type IndustrialManagementArtTypeList struct {
	MatchTypeName string `description:"匹配类型"`
	ArtNum        int    `description:"文章数量"`
}

func GetIndustrialManagementArtTypeList(industrialManagementId int) (items []*IndustrialManagementArtTypeList, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
				re.match_type_name,
				COUNT(*) AS art_num
			FROM
				cygx_industrial_management AS man
			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
			INNER JOIN cygx_report_mapping AS re ON re.category_id = art.category_id
			WHERE
				man.industrial_management_id = ? AND re.match_type_name <> '' AND re.report_type = 2 AND art.publish_status = 1
			GROUP BY
				re.match_type_name `
	sql += `  UNION ALL 
				SELECT
			map.match_type_name,
			COUNT(*) AS art_num 
		FROM
			cygx_industrial_management AS im
			INNER JOIN cygx_product_interior_industrial_group_management AS man_g ON man_g.industrial_management_id = im.industrial_management_id
			INNER JOIN cygx_product_interior AS art ON art.product_interior_id = man_g.product_interior_id
			INNER JOIN cygx_report_mapping_cygx AS map ON art.match_type_id = map.id 
		WHERE
			1 = 1 
			AND man_g.industrial_management_id = ? 
		GROUP BY
			map.match_type_name `
	sql += ` UNION ALL
			SELECT
				"研选报告",
				COUNT(*)
			FROM
				cygx_industrial_management AS man
			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
				man.industrial_management_id = ? AND art.publish_status = 1 AND  art.article_type_id IN  (1,2,12)`
	_, err = o.Raw(sql, industrialManagementId, industrialManagementId, industrialManagementId).QueryRows(&items)
	return
}

// 获取研选路演精华的数量
func GetIndustrialManagementArtYxLYJH(industrialManagementId int) (total int, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
			COUNT(*) AS art_num 
		FROM
			cygx_industrial_management AS man
			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
			man.industrial_management_id = ? 
			AND art.publish_status = 1 
			AND art.article_type_id IN (13)`
	err = o.Raw(sql, industrialManagementId).QueryRow(&total)
	return
}

type ArtGroupIndustrialManagementRep struct {
	IndustryName           string `description:"产业名称"`
	IndustrialManagementId int    `orm:"column(industrial_management_id);pk" description:"产业id"`
}

// 获取文章关联的产业列表
func GetArtGroupIndustrialManagement(reportId int) (item []*ArtGroupIndustrialManagementRep, err error) {
	sql := ` SELECT
		man.industry_name
		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
			man_g.cygx_article_id = ?`
	o := orm.NewOrmUsingDB("hz_cygx")
	_, err = o.Raw(sql, reportId).QueryRows(&item)
	return
}

// 通过ID获取详情
func GetIndustrialManagemenDetailById(industrialManagementId int) (item *CygxIndustrialManagementDetail, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_industrial_management WHERE industrial_management_id = ? `
	err = o.Raw(sql, industrialManagementId).QueryRow(&item)
	return
}

// 通过名称获取详情
func GetIndustrialManagemenDetailByName(industryName string) (item *CygxIndustrialManagementDetail, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_industrial_management WHERE industry_name = ? `
	err = o.Raw(sql, industryName).QueryRow(&item)
	return
}

// 获取行业深度，产业关联的文章数量
func GetIndustrialManagementGroupArtCountByDeep(industrialManagementId int) (count int, err error) {
	sqlCount := `SELECT COUNT(1) as conut FROM cygx_industrial_article_group_management AS a
				INNER JOIN cygx_article AS b ON b.id = a.cygx_article_id 
				WHERE
				a.industrial_management_id = ?
				AND b.match_type_name ='行业深度' `
	o := orm.NewOrmUsingDB("hz_cygx")
	err = o.Raw(sqlCount, industrialManagementId).QueryRow(&count)
	return
}

// 列表
func GetIndustrialManagement(condition string) (items []*ArtGroupIndustrialManagementRep, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_industrial_management as art WHERE 1= 1 `
	if condition != "" {
		sql += condition
	}
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 通过多个产业ID获取产业名称
func GetindustrialManagementNames(industrialManagementIds string) (names string, err error) {
	sql := ` SELECT
			GROUP_CONCAT( DISTINCT m.industry_name SEPARATOR '/' ) AS names 
			FROM
			cygx_industrial_management AS m 
			WHERE
			industrial_management_id IN ( ` + industrialManagementIds + `) `
	o := orm.NewOrmUsingDB("hz_cygx")
	err = o.Raw(sql).QueryRow(&names)
	return
}

// 通过多个产业ID获取产业名称
func GetindustrialManagementNamesBySubjectName(subjectnName string, chartPermissionId int) (names string, err error) {
	sql := `SELECT
			GROUP_CONCAT( DISTINCT m.industry_name SEPARATOR ',' ) AS sellerName 
			FROM
			cygx_industrial_management AS m 
			WHERE
			industrial_management_id IN (
			SELECT
			industrial_management_id 
			FROM
			cygx_industrial_subject 
			WHERE
			subject_name = ?) 	AND m.chart_permission_id	= ? `
	o := orm.NewOrmUsingDB("hz_cygx")
	err = o.Raw(sql, subjectnName, chartPermissionId).QueryRow(&names)
	return
}

type ReportMappingCategoryRep struct {
	CategoryId          int    `description:"文章分类id"`
	SubCategoryName     string `description:"产业名称"`
	ChartPermissionName string `description:"行业名称"`
}

func GetPermissionMappingCategoryAll() (item []*ReportMappingCategoryRep, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := ` SELECT * FROM cygx_report_mapping  GROUP BY category_id `
	_, err = o.Raw(sql).QueryRows(&item)
	return
}

type CompanyHistoryRecordNewPvRep struct {
	RealName       string `description:"姓名"`
	Mobile         string `description:"手机号"`
	Email          string `description:"邮箱"`
	Title          string `description:"标题"`
	CategoryId     int    `description:"文章分类id"`
	CreateTime     string `description:"创建时间"`
	StopTime       string `description:"阅读停留时间"`
	IndustryName   string `description:"产业名称"`
	PermissionName string `description:"行业名称"`
	SubjectNameStr string `description:"标的名称"`
	PublishDate    string `description:"发布时间"`
}

func GetCompanyHistoryRecordNewPv(mobiles, emails string) (item []*CompanyHistoryRecordNewPvRep, err error) {
	//var table string
	//table = "cygx_article_history_record_all"
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := ` SELECT
			h.real_name,
			h.mobile,
			h.email,
			a.title,
			a.category_id,
			h.create_time,
			a.publish_date,
			h.stop_time,
			(
			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 = a.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 = a.article_id ) 
			) AS industry_name
		FROM
			cygx_article_history_record_all AS h
			INNER JOIN cygx_article AS a ON a.article_id = h.article_id 
		WHERE
			h.mobile IN (` + mobiles + `) AND h.is_del = 0  OR( h.email IN (` + emails + `) AND h.email <>'' AND h.is_del = 0 )   ORDER BY h.create_time 	DESC `
	_, err = o.Raw(sql).QueryRows(&item)
	return
}

// 通过产业名称获取关联的ID
func GetManagementIdsByName(name string) (industrialManagementIds string, err error) {
	sql := ` SELECT
			GROUP_CONCAT( DISTINCT s.industrial_management_id SEPARATOR ',' ) AS industrial_management_ids 
			FROM
			cygx_industrial_management AS s
			WHERE
			industry_name =? `
	o := orm.NewOrmUsingDB("hz_cygx")
	err = o.Raw(sql, name).QueryRow(&industrialManagementIds)
	return
}

// 通过产业名称获取关联的ID（模糊查询）
func GetManagementIdsByNameLike(name string) (industrialManagementIds string, err error) {
	sql := ` SELECT
			GROUP_CONCAT( DISTINCT s.industrial_management_id SEPARATOR ',' ) AS industrial_management_ids 
			FROM
			cygx_industrial_management AS s
			WHERE
			industry_name LIKE '%` + name + `%'`
	o := orm.NewOrmUsingDB("hz_cygx")
	err = o.Raw(sql).QueryRow(&industrialManagementIds)
	return
}

type CygxReportMappingResp struct {
	CategoryId          int    `description:"行业分类ID"`
	ChartPermissionId   int    `description:"权限id"`
	ChartPermissionName string `description:"权限名称"`
	PermissionType      int    `description:"1主观，2客观"`
	SubCategoryName     string `description:"主题"`
}

// 通过ID获取详情
func GetCygxReportMappingRespByid(categoryId int) (item *CygxReportMappingResp, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_report_mapping WHERE category_id = ? LIMIT 1`
	err = o.Raw(sql, categoryId).QueryRow(&item)
	return
}

// IndustryMove 行业移动请求体
type IndustryMove struct {
	IndustrialManagementId int `description:"产业ID"`
	ChartPermissionId      int `description:"权限ID"`
}

// Update 更新产业
func (industryItem *CygxIndustrialManagement) Update(cols []string) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	_, err = o.Update(industryItem, cols...)
	return
}

// GetIndustryListByCondition 获取产业列表
func GetIndustryListByCondition(condition string, pars []interface{}) (list []*CygxIndustrialManagement, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_industrial_management WHERE 1 = 1 `
	if condition != "" {
		sql += condition
	}
	_, err = o.Raw(sql, pars).QueryRows(&list)
	return
}

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

// IndustriesEarliestLayoutTime 产业布局时间
type IndustriesEarliestLayoutTime struct {
	IndustrialManagementId int       `json:"industrial_management_id" description:"产业ID"`
	LayoutTime             string    `json:"layout_time" description:"布局时间"`
	MinArticleTime         string    `json:"min_article_time" description:"最早报告时间"`
	LayoutTime2            time.Time ` orm:"column(layout_time);"description:"布局时间"`
	MinArticleTime2        time.Time ` orm:"column(min_article_time);"description:"最早报告时间"`
}

// GetIndustriesEarliestLayoutTime 获取产业最早布局时间
func GetIndustriesEarliestLayoutTime(condition string, pars []interface{}) (list []*IndustriesEarliestLayoutTime, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
				idy.industrial_management_id,
				idy.layout_time,
				MIN(art.publish_date) AS min_article_time
			FROM
				cygx_industrial_management AS idy
			LEFT JOIN cygx_industrial_article_group_management AS argm ON idy.industrial_management_id = argm.industrial_management_id
			LEFT JOIN cygx_article AS art ON argm.article_id = art.article_id
			WHERE
				1 = 1 `
	if condition != "" {
		sql += condition
	}
	sql += ` GROUP BY idy.industrial_management_id`
	_, err = o.Raw(sql, pars).QueryRows(&list)
	return
}

// GetIndustriesEarliestLayoutTimeByMorningMeeting 根据晨会精华获取产业最早布局时间
func GetIndustriesEarliestLayoutTimeByMorningMeeting(condition string, pars []interface{}) (list []*IndustriesEarliestLayoutTime, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
			idy.industrial_management_id,
			idy.layout_time,
			MIN( mrc.meeting_time ) AS min_article_time 
		FROM
			cygx_industrial_management AS idy
			LEFT JOIN cygx_morning_meeting_review_chapter AS mrc ON idy.industrial_management_id = mrc.industry_id 
			WHERE
				1 = 1 `
	if condition != "" {
		sql += condition
	}
	sql += ` GROUP BY idy.industrial_management_id`
	_, err = o.Raw(sql, pars).QueryRows(&list)
	return
}

// UpdateIndustryLayoutTime 更新产业布局时间
func UpdateIndustryLayoutTime(industryId int, layoutTime string) (err error) {
	sql := `UPDATE cygx_industrial_management SET layout_time = ? WHERE industrial_management_id = ? LIMIT 1`
	o := orm.NewOrmUsingDB("hz_cygx")
	_, err = o.Raw(sql, layoutTime, industryId).Exec()
	return
}

// GetYxIndustryUseHzIndustryIds 获取研选产业的报告/活动所使用到的非研选产业IDs-即弘则覆盖
func GetYxIndustryUseHzIndustryIds() (ids []int, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT DISTINCT
				a.industrial_management_id
			FROM
				cygx_industrial_activity_group_management AS a
			JOIN cygx_industrial_management AS b ON a.industrial_management_id = b.industrial_management_id
			JOIN cygx_activity AS c ON a.activity_id = c.activity_id
			WHERE
				b.chart_permission_id != 31 AND c.chart_permission_id = 31 AND c.publish_status = 1
			UNION
			SELECT DISTINCT
				a.industrial_management_id
			FROM
				cygx_industrial_article_group_management AS a
			JOIN cygx_industrial_management AS b ON a.industrial_management_id = b.industrial_management_id
			JOIN cygx_article AS c ON a.article_id = c.article_id
			WHERE
				c.article_id > 1000000 AND c.article_type_id IN  (1,2,12) AND b.chart_permission_id != 31 AND c.publish_status = 1`
	_, err = o.Raw(sql).QueryRows(&ids)
	return
}

// GetIndustryListWithHzCover 获取产业列表-带弘则覆盖
func GetIndustryListWithHzCover(condition, conditionCover, orderRule string, isCover bool, pars []interface{}) (items []*CygxIndustrialManagementNum, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
				man.*, art.publish_date,
				man_g.industrial_management_id AS man_gid,
				MAX(art.publish_date) AS update_time,
				(
					SELECT
						COUNT(1)
					FROM
						cygx_industrial_article_group_management AS man_g
					WHERE
						man_g.industrial_management_id = man.industrial_management_id
				) AS art_num,
				(
					SELECT
						COUNT(1)
					FROM
						cygx_industrial_activity_group_management AS a_g
					INNER JOIN cygx_activity AS a ON a.activity_id = a_g.activity_id
					WHERE
						a_g.industrial_management_id = man.industrial_management_id
					AND a.publish_status = 1
				) AS act_num,
				"false" AS hz_cover
			FROM
				cygx_industrial_management AS man
			LEFT JOIN cygx_industrial_article_group_management AS man_g ON man_g.industrial_management_id = man.industrial_management_id
			LEFT JOIN cygx_article AS art ON art.article_id = man_g.article_id
			WHERE
				1 = 1 `
	sql += condition
	sql += ` GROUP BY industry_name`
	// 弘则覆盖
	if isCover {
		sql += ` UNION ALL
				SELECT
					man.*, art.publish_date,
					man_g.industrial_management_id AS man_gid,
					MAX(art.publish_date) AS update_time,
					(
						SELECT
							COUNT(1)
						FROM
							cygx_industrial_article_group_management AS man_g
						WHERE
							man_g.industrial_management_id = man.industrial_management_id
					) AS art_num,
					(
						SELECT
							COUNT(1)
						FROM
							cygx_industrial_activity_group_management AS a_g
						INNER JOIN cygx_activity AS a ON a.activity_id = a_g.activity_id
						WHERE
							a_g.industrial_management_id = man.industrial_management_id
						AND a.publish_status = 1
					) AS act_num,
					"true" AS hz_cover
				FROM
					cygx_industrial_management AS man
				LEFT JOIN cygx_industrial_article_group_management AS man_g ON man_g.industrial_management_id = man.industrial_management_id
				LEFT JOIN cygx_article AS art ON art.article_id = man_g.article_id
				WHERE
					1 = 1 `
		sql += conditionCover
		sql += ` GROUP BY industry_name`
	}

	if orderRule != "" {
		sql += ` ORDER BY ` + orderRule
	}

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

type IndustrialManagement struct {
	IndustrialManagementId int    `orm:"column(industrial_management_id);pk" description:"产业id"`
	UpdateTime             string `description:"更新时间"`
	PublishDate            string `description:"发布时间"`
	IndustryName           string `description:"产业名称"`
}

// GetIndustrialManagementArticleNewPublishData 获取产业关联文章的最新发布时间
func GetIndustrialManagementArticleNewPublishData() (items []*IndustrialManagement, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	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
}

// 时间线的更新时间
func GetTimeLineReportIndustrialPublishdateList(industrialIdArr []int) (items []*IndustrialManagement, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
			mmc.industry_id AS industrial_management_id,
			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
}

// UpdateIndustrialManagementArticleNewPublishData 批量修改获取产业关联文章的最新发布时间
func UpdateIndustrialManagementArticleNewPublishData(items map[int]string) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	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
}

// GetTopOneMonthArtReadNumIndustry 获取列表
func GetTopOneMonthArtReadNumIndustryAll(condition string, pars []interface{}) (items []*IndustrialManagement, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_industrial_management WHERE 1 = 1 `
	if condition != `` {
		sql += condition
	}
	sql += ` ORDER BY article_read_num DESC `
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}
