package cygx

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

type ShowButton struct {
	IsShowButton bool `description:"是否展示操作按钮"`
}

type ReportArticleAdd struct {
	SubjectName            string `description:"标的名称"`
	IndustrialManagementId int    `description:"产业id"`
}

// 报告归类入参
type ReportArticleClassificationResp struct {
	ReportId               int    `description:"报告id"`
	IndustrialManagementId string `description:"产业id"`
	//IndustrialManagementIdStr string `description:"产业id多个用 , 逗号隔开 1,2"`
	IndustrialSubjectIdStr string `description:"标的id多个用 , 逗号隔开 1,2"`
}

type CygxReportArticleID struct {
	ReportId int `orm:"column(id);pk"description:"报告id"`
}

type CygxReportArticle struct {
	ReportId          int    `orm:"column(id);pk"description:"报告id"`
	ArticleId         int    `description:"文章id"`
	Title             string `description:"标题"`
	PublishDate       string `description:"发布时间"`
	CreateDate        string `description:"创建时间"`
	LastUpdatedTime   string `description:"更新时间"`
	PermissionName    string `orm:"column(chart_permission_name);" description:"行业"`
	ChartPermissionId int    `description:"行业id"`
	SubCategoryName   string `description:"主题"`
	MatchTypeName     string `description:"匹配类型"`
	IndustryName      string `description:"产业名称"`
	IndustryIdStr     string `description:"产业ID"`
	SubjectNameStr    string `description:"关联标的"`
	SubjectIdStr      string `description:"关联Id"`
	IsClass           int    `description:"是否归类  1是、0否"`
	IsFilter          int    `description:"是否过滤 1是、0否"`
	ArticleIdMd5      string `description:"文章加密ID"`
	CategoryId        int    `description:"文章分类id"`
	ShowButton        bool   `description:"是否展示过滤归类按钮"`
	Pv                int    `description:"PV"`
	Uv                int    `description:"UV"`
	ClPv              int    `description:"策略平台PV"`
	ClUv              int    `description:"策略平台UV"`
	PublishStatus     int    `description:"发布状态，0未发布 ，1已发布"`
	CommentNum        int    `description:"留言数量"`
	NickName          string `description:"作者昵称"`
	CollectionNum     int    `description:"收藏"`
	Stock             string `description:"个股标签（上海策略品台同步）"`
	FieldName         string `description:"产业标签（上海策略品台同步）"`
	Label             string `description:"标签"`
	ListIndustrial    []*IndustrialActivityGroupManagementRep
	ListSubject       []*SubjectActivityGroupManagementRep
}

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

// 新增
func AddReportArticle(item *CygxReportArticle) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	_, err = o.Insert(item)
	return
}

// 列表
func GetReportArticleList(condition string, pars []interface{}, startSize, pageSize, isClass int) (items []*CygxReportArticle, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	//o := orm.NewOrm()
	sql := ``
	if isClass == 1 {
		sql = `SELECT
				art.title,
				art.article_id,
				art.category_id,
				art.publish_date,
				art.is_class,
				art.publish_status,
				art.is_filter,
				art.stock,
				art.field_name,
				art.id,
				art.article_id_md5,
				re.chart_permission_name,
				re.match_type_name,
				art.sub_category_name,
				re.chart_permission_id
			FROM
				cygx_article AS art
				LEFT JOIN cygx_report_mapping AS ret ON ret.category_id = art.category_id_two
				LEFT JOIN cygx_report_mapping AS re ON re.category_id = art.category_id
				LEFT JOIN cygx_industrial_article_group_management as man ON man.article_id = art.article_id
			WHERE 1 = 1 `
	} else {
		sql = `SELECT
				art.title,
				art.article_id,
				art.category_id,
				art.publish_date,
				art.is_class,
				art.is_filter,
				art.id,
				art.article_id_md5,
				art.stock,
				art.field_name,
				re.chart_permission_name,
				re.match_type_name,
				re.sub_category_name,
				re.chart_permission_id  FROM cygx_article as art
				LEFT JOIN cygx_report_mapping AS ret ON ret.category_id = art.category_id_two
				LEFT JOIN cygx_report_mapping AS re ON re.category_id = art.category_id
				WHERE 1=1 `
	}
	if condition != "" {
		sql += condition
	}

	sql += `LIMIT ?,?`
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

// 获取文章PV、UV
func GetReportArticleListPvUv(condition string) (items []*CygxReportArticle, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
				( SELECT COUNT( 1 ) FROM cygx_article_history_record_all AS h  WHERE h.article_id = art.article_id AND h.platfor = 1 AND h.company_id != ` + strconv.Itoa(utils.HZ_COMPANY_ID) + ` ) AS pv,
				(SELECT COUNT( DISTINCT h.user_id ) FROM cygx_article_history_record_all AS h WHERE h.article_id = art.article_id  AND h.platfor = 1  AND h.company_id != ` + strconv.Itoa(utils.HZ_COMPANY_ID) + ` ) AS uv,
				( SELECT COUNT( 1 ) FROM cygx_article_history_record_all AS h  WHERE h.article_id = art.article_id AND h.platfor = 2 AND is_del = 0  AND h.company_id != ` + strconv.Itoa(utils.HZ_COMPANY_ID) + ` ) AS cl_pv,
				(SELECT COUNT( DISTINCT h.user_id ) FROM cygx_article_history_record_all AS h   WHERE h.article_id = art.article_id  AND h.platfor = 2  AND is_del = 0  AND h.company_id != ` + strconv.Itoa(utils.HZ_COMPANY_ID) + ` ) AS cl_uv,
				( SELECT COUNT( 1 ) FROM cygx_article_collect AS c WHERE c.article_id = art.article_id ) AS collection_num,
				art.article_id
			FROM
				cygx_article AS art
				LEFT JOIN cygx_report_mapping AS re ON re.category_id = art.category_id_two
				LEFT JOIN cygx_industrial_article_group_management as man ON man.article_id = art.article_id
			WHERE 1 = 1 `

	if condition != "" {
		sql += condition
	}
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 获取数量
func GetReportArticleCount(condition string, pars []interface{}) (count int, err error) {
	sqlCount := ``
	sqlCount = ` SELECT COUNT(1)  as count FROM (SELECT art.article_id 
				FROM cygx_article AS art
				LEFT JOIN cygx_report_mapping AS ret ON ret.category_id = art.category_id_two
				LEFT JOIN cygx_report_mapping AS re ON re.category_id = art.category_id
				LEFT JOIN cygx_industrial_article_group_management AS man ON man.article_id = art.article_id  WHERE 1= 1 ` + condition + ` GROUP BY art.article_id) as a `
	o := orm.NewOrmUsingDB("hz_cygx")
	err = o.Raw(sqlCount, pars).QueryRow(&count)
	return
}

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

//修改
//func EditReportArticle(item *CygxReportArticle) (err error) {
//	sql := `UPDATE cygx_industrial_subject SET  subject_name=? WHERE industrial_subject_id=? `
//	o := orm.NewOrm()
//	_, err = o.Raw(sql, item.SubjectName, item.ReportArticleId).Exec()
//	return
//}

// 过滤
func FilterReportArticle(reportArticleId 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 := `UPDATE cygx_article SET  is_filter=1,  is_class=0 WHERE id=? `
	_, err = to.Raw(sql, reportArticleId).Exec()
	if err != nil {
		return
	}
	//删除关联产业
	sql = ` DELETE FROM cygx_industrial_article_group_management WHERE cygx_article_id = ?`
	_, err = to.Raw(sql, reportArticleId).Exec()
	if err != nil {
		return
	}
	//删除关联标的
	sql = ` DELETE FROM cygx_industrial_article_group_subject WHERE cygx_article_id = ?`
	_, err = to.Raw(sql, reportArticleId).Exec()
	if err != nil {
		return
	}
	return
}

type CygxReportArticleItems struct {
	ReportId    int    `orm:"column(id);pk"description:"报告主键id"`
	ArticleId   int    `description:"文章ID"`
	IsFilter    int    `description:"是否过滤"`
	IsClass     int    `description:"是否归类"`
	ReportType  int    `description:"报告类型，1行业报告，2产业报告"`
	Title       string `description:"标题"`
	PublishDate string `description:"发布时间"`
	Abstract    string `description:"摘要"`
}

func GetReportArticleId(reportArticleId int) (items *CygxReportArticleItems, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := ` SELECT * FROM cygx_article WHERE id=? `
	err = o.Raw(sql, reportArticleId).QueryRow(&items)
	return
}

// 报告分类第一次添加
func ReportArticleClassificationAdd(reportId, industrialManagementId, articleId int, ndustrialSubjectIdStr string) (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 := `UPDATE cygx_article SET is_filter=0,  is_class=1 WHERE id=? `
	_, err = to.Raw(sql, reportId).Exec()
	if err != nil {
		return
	}
	//添加文章关联标的
	if 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
			}
		}
	}
	//添加文章关联行业
	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, industrialManagementId, time.Now()).Exec()
	if err != nil {
		return
	}
	fmt.Println("新增关联")
	return
}

// 报告分类的新增与修改
func ReportArticleClassificationEdit(reportId, industrialManagementId, articleId int, ndustrialSubjectIdStr string) (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 := `UPDATE cygx_article SET is_filter=0 WHERE id=? `
	sql := `UPDATE cygx_article SET is_filter=0,  is_class=1 WHERE id=? `
	_, err = to.Raw(sql, reportId).Exec()
	if err != nil {
		return
	}
	//删除文章关联标的
	sql = `	DELETE FROM cygx_industrial_article_group_subject WHERE cygx_article_id = ?`
	_, err = to.Raw(sql, reportId).Exec()
	if err != nil {
		return
	}
	//添加文章关联标的
	if 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 cygx_article_id = ?`
	_, err = to.Raw(sql, reportId).Exec()
	if err != nil {
		return
	}
	//添加文章关联行业
	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, industrialManagementId, time.Now()).Exec()
	if err != nil {
		return
	}
	fmt.Println("修改关联")
	return
}

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

func GetPermissionMappingCategoryID() (item []*PermissionMappingCategoryRep, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := ` SELECT category_id FROM cygx_report_mapping WHERE report_type = 1 AND category_id  not IN (67)  GROUP BY category_id `
	_, err = o.Raw(sql).QueryRows(&item)
	return
}

// 报告分类的新增与修改
func ReportArticleClassificationEditNew(reportId int, industrialManagementIdStr string, articleId int, ndustrialSubjectIdStr string) (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 := `UPDATE cygx_article SET is_filter=0 WHERE id=? `
	sql := `UPDATE cygx_article SET is_filter=0,  is_class=1 WHERE id=? `
	_, err = to.Raw(sql, reportId).Exec()
	if err != nil {
		return
	}
	//删除文章关联标的
	sql = `	DELETE FROM cygx_industrial_article_group_subject WHERE cygx_article_id = ?`
	_, err = to.Raw(sql, reportId).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 cygx_article_id = ?`
	_, err = to.Raw(sql, reportId).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
}

// 报告阅读明细下载
type ReportExportRep struct {
	Id          string `description:"客户姓名"`
	RealName    string `description:"客户姓名"`
	CompanyName string `description:"公司名称"`
	CreateTime  string `description:"阅读时间"`
	SellerName  string `description:"销售名称"`
	StopTime    string `停留时间:"停留时间"`
}

func GetReportExportRep(article_id int, sqlStr string) (item []*ReportExportRep, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := ` SELECT h.*
			FROM
			cygx_article_history_record_newpv AS h
			LEFT JOIN cygx_article AS art ON art.article_id = h.article_id
			WHERE art.id  = ?` + sqlStr
	_, err = o.Raw(sql, article_id).QueryRows(&item)
	return
}

// 报告关联的匹配类型
type ReportMatchTypeName struct {
	MatchID       string `orm:"column(id);"description:"匹配ID"`
	MatchTypeName string `description:"匹配类型"`
}

type ReportMatchTypeNameList struct {
	List []*ReportMatchTypeName
}

func GetMatchTypeName(categoryId int) (items []*ReportMatchTypeName, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_report_mapping 
			WHERE
			chart_permission_id = (
			SELECT
			chart_permission_id
			FROM
				cygx_report_mapping 
			WHERE
			category_id = ?  LIMIT 1
			)
			AND match_type_name <>''
			GROUP BY match_type_name
			ORDER BY id ASC `
	_, err = o.Raw(sql, categoryId).QueryRows(&items)
	return
}

type ArticleDetail struct {
	ArticleId            int    `description:"报告id"`
	Title                string `description:"标题"`
	TitleEn              string `description:"英文标题 "`
	UpdateFrequency      string `description:"更新周期"`
	CreateDate           string `description:"创建时间"`
	PublishDate          string `description:"发布时间"`
	Body                 string `description:"内容"`
	Annotation           string `description:"核心观点"`
	Abstract             string `description:"摘要"`
	CategoryName         string `description:"一级分类"`
	SubCategoryName      string `description:"二级分类"`
	MatchTypeName        string `description:"匹配类型"`
	IsCollect            bool   `description:"是否收藏:true，已收藏，false:未收藏"`
	IsInterviewApply     bool   `description:"是否申请访谈:true，已申请，false:未申请"`
	BodyText             string `description:"内容"`
	InterviewApplyStatus string `description:"当前访谈申请状态：'待邀请','待访谈','已完成','已取消'"`
	InterviewDate        string `description:"访谈时间"`
	ExpertBackground     string `description:"专家背景"`
	ExpertNumber         string `description:"专家编号"`
	Department           string `description:"作者"`
	ArticleIdMd5         string `description:"纪要id"`
	IsClass              int    `description:"是否归类，1是，0否"`
	IsSummary            int    `description:"是否是纪要库，1是，0否"`
	CategoryId           int    `description:"分类ID"`
	CategoryIdTwo        int    `description:"分类ID"`
	FileLink             string `description:"下载预览链接"`
	ReportType           int    `description:"报告类型，2产业报告，1行业报告"`
	TypeName             string `description:"策略平台类型字段名称"`
	ArticleTypeId        int    `description:"文章类型ID"`
	ArticleTypeName      string `description:"文章类型名称"`
	Stock                string `description:"个股标签（上海策略品台同步）"`
	FieldName            string `description:"产业标签（上海策略品台同步）"`
}

func GetArticleDetailById(articleId int) (item *ArticleDetail, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_article WHERE id = ? `
	err = o.Raw(sql, articleId).QueryRow(&item)
	return
}

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

// 修改报告匹配类型
type UpdateReportMatchTypeNameRep struct {
	MatchID  int `orm:"column(id);"description:"匹配ID"`
	ReportId int `description:"报告id"`
}

// 手动修改匹配类型
func UpdateReportMatchTypeName(matchTypeName string, reportType, categoryId, reportId, isSummary, isClass int) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			fmt.Println(err)
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	sql := ""
	//fmt.Println(sql)
	if isSummary == 0 {
		//删除关联产业
		sql = ` DELETE FROM cygx_industrial_article_group_management WHERE cygx_article_id = ?`
		_, err = to.Raw(sql, reportId).Exec()
		if err != nil {
			return
		}
		//删除关联标的
		sql = ` DELETE FROM cygx_industrial_article_group_subject WHERE cygx_article_id = ?`
		_, err = to.Raw(sql, reportId).Exec()
		if err != nil {
			return
		}
	}
	//修改文章是否过滤字段
	if reportType == 1 {
		sql = `UPDATE cygx_article SET match_type_name=?, report_type=? ,category_id=?, is_class = 1,  is_custom = 1 WHERE id=? `
	} else {
		sql = `UPDATE cygx_article SET match_type_name=?, report_type=? ,category_id=?, is_class = 0, is_custom = 1 WHERE id=? `
	}
	if isSummary == 1 && isClass == 1 {
		sql = `UPDATE cygx_article SET match_type_name=?, report_type=? ,category_id=?, is_class = 1, is_custom = 1 WHERE id=? `
	}
	_, err = to.Raw(sql, matchTypeName, reportType, categoryId, reportId).Exec()

	return
}

func GetArticleDetailByMd5Id(md5Id string) (item *ArticleDetail, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT *FROM cygx_article WHERE article_id_md5 = ? `
	err = o.Raw(sql, md5Id).QueryRow(&item)
	return
}

type ReportAddRep struct {
	ArticleId               int    `description:"报告id"`
	Title                   string `description:"标题"`
	Abstract                string `description:"摘要"`
	Body                    string `description:"内容"`
	DoType                  int    `description:"操作类型 0，保存 、1，发布"`
	SellerAndMobile         string `description:"作者"`
	ChartPermissionId       int    `description:"行业id"`
	IndustrialManagementIds string `description:"产业id 多个用 , 隔开"`
	IndustrialSubjectIds    string `description:"标的id 多个用 , 隔开"`
	PublishDate             string `description:"发布时间 列如 2020-03-23"`
}

// 添加报告文章
func AddAReportrticle(item *CygxArticle, chartPermissionId int, industryName, subjectName string, itemDepartment *CygxArticleDepartment, industrialManagementIds, industrialSubjectIds string) (newId int64, err error) {
	var newDepartmentId int64
	var total int
	itemIndustrialManagementGroup := new(CygxIndustrialArticleGroupManagement)
	itemIndustrialSubjectGroup := new(CygxIndustrialArticleGroupSubject)
	o := orm.NewOrmUsingDB("hz_cygx")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	if itemDepartment.NickName != "" {
		//判断作者是否存在，如果没有则新增
		total, err = GetArticleDepartmentCount(itemDepartment.NickName, itemDepartment.Remarks)
		if err != nil {
			return
		}
		if total == 0 {
			newDepartmentId, err = to.Insert(itemDepartment)
			if err != nil {
				return
			}
		} else {
			departmentDetail := new(CygxArticleDepartmentRep)
			departmentDetail, err = GetArticleDepartmentDateil(itemDepartment.NickName, itemDepartment.Remarks)
			if err != nil {
				return
			}
			newDepartmentId = int64(departmentDetail.DepartmentId)
		}
		item.DepartmentId = int(newDepartmentId)
	}
	newId, err = to.Insert(item) // 新增文章
	if err != nil {
		return
	}
	//添加产业与文章的关联
	industrialManagementIdList := strings.Split(industrialManagementIds, ",")
	for _, v := range industrialManagementIdList {
		newIndustrialId, _ := strconv.Atoi(v)
		itemIndustrialManagementGroup.CreateTime = time.Now()
		itemIndustrialManagementGroup.CygxArticleId = int(newId)
		itemIndustrialManagementGroup.ArticleId = item.ArticleId
		itemIndustrialManagementGroup.IndustrialManagementId = newIndustrialId
		_, err = AddCygxIndustrialArticleGroupManagement(itemIndustrialManagementGroup)
		if err != nil {
			return
		}
	}
	//添加标的与文章的关联
	if industrialSubjectIds != "" {
		industrialSubjectIdList := strings.Split(industrialSubjectIds, ",")
		for _, v := range industrialSubjectIdList {
			industrialSubjectId, _ := strconv.Atoi(v)
			itemIndustrialSubjectGroup.CygxArticleId = int(newId)
			itemIndustrialSubjectGroup.ArticleId = item.ArticleId
			itemIndustrialSubjectGroup.IndustrialSubjectId = industrialSubjectId
			itemIndustrialSubjectGroup.CreateTime = time.Now()
			_, err = AddCygxIndustrialArticleGroupSubject(itemIndustrialSubjectGroup)
			if err != nil {
				return
			}
		}
	}
	return
}

// 修改报告文章
func EditReportrticle(item *CygxArticle, chartPermissionId int, industryName, subjectName string, oldPublishStatus int, itemDepartment *CygxArticleDepartment, industrialManagementIds, industrialSubjectIds string) (err error) {
	var sql string
	var newDepartmentId int64
	var total int
	newId := item.SummaryManageId
	itemIndustrialManagementGroup := new(CygxIndustrialArticleGroupManagement)
	itemIndustrialSubjectGroup := new(CygxIndustrialArticleGroupSubject)
	o := orm.NewOrmUsingDB("hz_cygx")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	if itemDepartment.NickName != "" {
		//判断作者是否存在，如果没有则新增
		total, err = GetArticleDepartmentCount(itemDepartment.NickName, itemDepartment.Remarks)
		if err != nil {
			return
		}
		if total == 0 {
			newDepartmentId, err = to.Insert(itemDepartment)
			if err != nil {
				return
			}
		} else {
			departmentDetail := new(CygxArticleDepartmentRep)
			departmentDetail, err = GetArticleDepartmentDateil(itemDepartment.NickName, itemDepartment.Remarks)
			if err != nil {
				return
			}
			newDepartmentId = int64(departmentDetail.DepartmentId)
		}
		item.DepartmentId = int(newDepartmentId)
	}
	sql = ` UPDATE cygx_article SET 
			category_name=?,
			title=?,
			abstract=?, 
			body=?,
			body_text=?,
			publish_status=?,
			last_updated_time = ?,
			seller_and_mobile=?,
			expert_background =?, 
			expert_number=? ,
			interview_date=?, 
			file_link=? ,
			chart_permission_ids =?,
			article_type_id =?,
			article_type_name =?,
			admin_id =?,
			admin_name =?,
			is_summary =?,
			is_report =?,
			department_id =?,
			publish_date =?,
			report_link =?
			WHERE article_id =?`
	_, err = to.Raw(sql, item.CategoryName, item.Title, item.Abstract, item.Body, item.BodyText, item.PublishStatus, item.LastUpdatedTime, item.SellerAndMobile, item.ExpertBackground, item.ExpertNumber, item.InterviewDate, item.FileLink, item.ChartPermissionIds, item.ArticleTypeId, item.ArticleTypeName, item.AdminId, item.AdminName, item.IsSummary, item.IsReport, item.DepartmentId, item.PublishDate, item.ReportLink, item.ArticleId).Exec()
	if err != nil {
		return
	}

	//删除文章关联行业 （避免截断表时产生的脏数据，故不用update而是先删除再增加）
	sql = `	DELETE FROM cygx_industrial_article_group_management WHERE article_id = ?`
	_, err = to.Raw(sql, item.ArticleId).Exec()
	if err != nil {
		return
	}
	//删除文章关联标的
	sql = `	DELETE FROM cygx_industrial_article_group_subject WHERE article_id = ?`
	_, err = to.Raw(sql, item.ArticleId).Exec()
	if err != nil {
		return
	}

	//添加产业与文章的关联
	industrialManagementIdList := strings.Split(industrialManagementIds, ",")
	for _, v := range industrialManagementIdList {
		newIndustrialId, _ := strconv.Atoi(v)
		itemIndustrialManagementGroup.CreateTime = time.Now()
		itemIndustrialManagementGroup.CygxArticleId = int(newId)
		itemIndustrialManagementGroup.ArticleId = item.ArticleId
		itemIndustrialManagementGroup.IndustrialManagementId = newIndustrialId
		_, err = AddCygxIndustrialArticleGroupManagement(itemIndustrialManagementGroup)
		if err != nil {
			return
		}
	}
	//添加标的与文章的关联
	if industrialSubjectIds != "" {
		industrialSubjectIdList := strings.Split(industrialSubjectIds, ",")
		for _, v := range industrialSubjectIdList {
			industrialSubjectId, _ := strconv.Atoi(v)
			itemIndustrialSubjectGroup.CygxArticleId = int(newId)
			itemIndustrialSubjectGroup.ArticleId = item.ArticleId
			itemIndustrialSubjectGroup.IndustrialSubjectId = industrialSubjectId
			itemIndustrialSubjectGroup.CreateTime = time.Now()
			_, err = AddCygxIndustrialArticleGroupSubject(itemIndustrialSubjectGroup)
			if err != nil {
				return
			}
		}
	}
	return
}

type CygxArticleReport struct {
	ArticleId          int       `description:"文章ID"`
	Title              string    `description:"标题"`
	Abstract           string    `description:"摘要"`
	Body               string    `description:"内容"`
	PublishStatus      int       `description:"发布状态，0未发布 ，1已发布"`
	PublishDate        string    `description:"发布时间"`
	CreateDate         time.Time `description:"创建时间"`
	LastUpdatedTime    time.Time `description:"更新时间"`
	ArticleIdMd5       string    `description:"ID，md5值"`
	SellerAndMobile    string    `description:"作者(姓名与手机号)"`
	SubjectName        string    `description:"标的名称"`
	IndustryName       string    `description:"产业名称"`
	DepartmentId       int       `description:"作者id"`
	ChartPermissionIds string    `description:"行业ID ,多个用 , 隔开"`
	ArticleTypeId      int       `description:"文章类型ID"`
	ArticleTypeName    string    `description:"文章类型名称"`
	ReportLink         string    `description:"报告链接"`
	ChartPermissionId  int       `description:"行业id"`
	ListIndustrial     []*IndustrialActivityGroupManagementRep
	ListSubject        []*SubjectActivityGroupManagementRep
}

// 通过纪要ID获取文章详情
func GetArticleIdInfoByreportIdEdit(articleId int) (item *CygxArticleReport, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
			a.* ,m.industry_name,
			GROUP_CONCAT(DISTINCT s.subject_name  SEPARATOR ',') AS subject_name
		FROM
			cygx_article  as  a 
			INNER JOIN  cygx_industrial_article_group_management as mg ON mg.cygx_article_id = a.id
			INNER JOIN cygx_industrial_management as m ON m.industrial_management_id = mg.industrial_management_id
			LEFT JOIN cygx_industrial_article_group_subject as sg ON sg.cygx_article_id = a.id
			LEFT JOIN cygx_industrial_subject as s ON s.industrial_subject_id = sg.industrial_subject_id
		WHERE
		a.article_id = ?`
	err = o.Raw(sql, articleId).QueryRow(&item)
	return
}

// 修改文章关联的标的ID
func UpdateSubjecIds(subjecIds string, industrialManagementId, articleId int) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	var industrialAndSubjectIds string
	industrialAndSubjectIds = strings.Replace(strings.Replace(subjecIds, "{|1|}", "", -1), "{|2|}", "", -1)
	fmt.Println(industrialAndSubjectIds)
	sql := `UPDATE cygx_article SET subject_ids=? ,industrial_management_id =?, industrial_and_subject_ids = ? WHERE article_id  = ?`
	_, err = o.Raw(sql, subjecIds, industrialManagementId, industrialAndSubjectIds, articleId).Exec()
	return
}

// 删除研选报告，以及相关归类，收藏
func DeleteArticleReport(articleId int) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			fmt.Println(err)
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	sql := ""
	//删除关联产业
	sql = ` DELETE FROM cygx_industrial_article_group_management WHERE article_id = ?`
	_, err = to.Raw(sql, articleId).Exec()
	if err != nil {
		return
	}
	//删除关联标的
	sql = ` DELETE FROM cygx_industrial_article_group_subject WHERE article_id = ?`
	_, err = to.Raw(sql, articleId).Exec()
	if err != nil {
		return
	}
	//删除关联收藏
	sql = ` DELETE FROM cygx_article_collect WHERE article_id = ?`
	_, err = to.Raw(sql, articleId).Exec()
	if err != nil {
		return
	}
	//删除阅读记录
	sql = ` DELETE FROM cygx_article_history_record WHERE article_id = ?`
	_, err = to.Raw(sql, articleId).Exec()
	if err != nil {
		return
	}

	//删除阅读记录
	sql = ` DELETE FROM cygx_article_history_record_newpv WHERE article_id = ?`
	_, err = to.Raw(sql, articleId).Exec()
	if err != nil {
		return
	}
	//删除报告
	sql = ` DELETE FROM cygx_article WHERE article_id = ?`
	_, err = to.Raw(sql, articleId).Exec()
	return
}

type AddArticleRoadshowEssenceRep struct {
	ArticleId              int    `description:"文章ID 0 新增，大于0 修改"`
	Title                  string `description:"标题"`
	SellerAndMobile        string `description:"作者(姓名与手机号)"`
	PublishDate            string `description:"发布时间"`
	ChartPermissionId      int    `description:"行业ID"`
	IndustrialManagementId string `description:"产业id，多个用 , 英文逗号隔开"`
	IndustrialSubjectIdStr string `description:"标的id多个用  , 英文逗号隔开"`
	Abstract               string `description:"摘要"`
	Body                   string `description:"内容"`
	ReportLink             string `description:"报告链接"`
	DoType                 int    `description:"操作方式，1发布，0保存"`
}

// 添加报告文章
func AddArticleRoadshowEssence(item *CygxArticle, industryIds, subjectIds string) (newId int64, err error) {
	itemIndustrialManagementGroup := new(CygxIndustrialArticleGroupManagement)
	itemIndustrialSubjectGroup := new(CygxIndustrialArticleGroupSubject)
	o := orm.NewOrmUsingDB("hz_cygx")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	newId, err = to.Insert(item) // 新增文章
	if err != nil {
		return
	}
	//添加产业与文章的关联
	industrialStrList := strings.Split(industryIds, ",")
	for _, v := range industrialStrList {
		itemIndustrialManagementGroup.CreateTime = time.Now()
		itemIndustrialManagementGroup.CygxArticleId = int(newId)
		itemIndustrialManagementGroup.ArticleId = item.ArticleId
		industryId, _ := strconv.Atoi(v)
		itemIndustrialManagementGroup.IndustrialManagementId = industryId
		_, err = AddCygxIndustrialArticleGroupManagement(itemIndustrialManagementGroup)
		if err != nil {
			return
		}
	}
	//添加标的与文章的关联
	if subjectIds != "" {
		slice := strings.Split(subjectIds, ",") //标的处理、添加标的与产业的关联、标的与文章的关联
		for _, v := range slice {
			itemIndustrialSubjectGroup.CygxArticleId = int(newId)
			itemIndustrialSubjectGroup.ArticleId = item.ArticleId
			subjectId, _ := strconv.Atoi(v)
			itemIndustrialSubjectGroup.IndustrialSubjectId = subjectId
			itemIndustrialSubjectGroup.CreateTime = time.Now()
			_, err = AddCygxIndustrialArticleGroupSubject(itemIndustrialSubjectGroup)
			if err != nil {
				return
			}
		}
	}
	return
}

// 修改报告文章
func UpdateArticleRoadshowEssence(item *CygxArticle, industryIds, subjectIds string) (err error) {
	itemIndustrialManagementGroup := new(CygxIndustrialArticleGroupManagement)
	itemIndustrialSubjectGroup := new(CygxIndustrialArticleGroupSubject)
	o := orm.NewOrmUsingDB("hz_cygx")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	newId := item.SummaryManageId
	sql := `UPDATE cygx_article SET title=? ,seller_and_mobile =?, chart_permission_ids = ?, abstract = ?, body = ?, body_text = ?, report_link = ? ,have_publish = ? ,publish_status = ? ,periods = ? ,link_article_id = ?,publish_date = ?, category_id = ? ,admin_id =? ,admin_name =? WHERE article_id  = ?`
	_, err = to.Raw(sql, item.Title, item.SellerAndMobile, item.ChartPermissionIds, item.Abstract, item.Body, item.BodyText, item.ReportLink, item.HavePublish, item.PublishStatus, item.Periods, item.LinkArticleId, item.PublishDate, item.CategoryId, item.AdminId, item.AdminName, item.ArticleId).Exec()
	if err != nil {
		return
	}
	//删除文章关联行业 （避免截断表时产生的脏数据，故不用update而是先删除再增加）
	sql = ` DELETE FROM cygx_industrial_article_group_management WHERE article_id = ?`
	_, err = to.Raw(sql, item.ArticleId).Exec()
	if err != nil {
		return
	}
	//删除文章关联标的
	sql = `	DELETE FROM cygx_industrial_article_group_subject WHERE article_id = ?`
	_, err = to.Raw(sql, item.ArticleId).Exec()
	if err != nil {
		return
	}
	//添加产业与文章的关联
	industrialStrList := strings.Split(industryIds, ",")
	for _, v := range industrialStrList {
		itemIndustrialManagementGroup.CreateTime = time.Now()
		itemIndustrialManagementGroup.CygxArticleId = int(newId)
		itemIndustrialManagementGroup.ArticleId = item.ArticleId
		industryId, _ := strconv.Atoi(v)
		itemIndustrialManagementGroup.IndustrialManagementId = industryId
		_, err = AddCygxIndustrialArticleGroupManagement(itemIndustrialManagementGroup)
		if err != nil {
			return
		}
	}
	//添加标的与文章的关联
	if subjectIds != "" {
		slice := strings.Split(subjectIds, ",") //标的处理、添加标的与产业的关联、标的与文章的关联
		for _, v := range slice {
			itemIndustrialSubjectGroup.CygxArticleId = int(newId)
			itemIndustrialSubjectGroup.ArticleId = item.ArticleId
			subjectId, _ := strconv.Atoi(v)
			itemIndustrialSubjectGroup.IndustrialSubjectId = subjectId
			itemIndustrialSubjectGroup.CreateTime = time.Now()
			_, err = AddCygxIndustrialArticleGroupSubject(itemIndustrialSubjectGroup)
			if err != nil {
				return
			}
		}
	}
	return
}

type ArticleRoadshowEssenceDetail struct {
	ArticleId              int    `description:"文章ID"`
	Title                  string `description:"标题"`
	SellerAndMobile        string `description:"作者(姓名与手机号)"`
	PublishDate            string `description:"发布时间"`
	ChartPermissionId      int    `orm:"column(chart_permission_ids);"description:"行业ID"`
	PermissionName         string `orm:"column(category_name);"description:"行业名称"`
	IndustrialManagementId string `description:"产业id，多个用 , 英文逗号隔开"`
	IndustryName           string `description:"产业名称"`
	IndustrialSubjectIdStr string `description:"标的id多个用  , 英文逗号隔开"`
	SubjectName            string `description:"标的名称"`
	Abstract               string `description:"摘要"`
	Body                   string `description:"内容"`
	ReportLink             string `description:"报告链接"`
	PublishStatus          int    `description:"发布状态，0未发布 ，1已发布"`
}

// 文章详情
func GetArticleRoadshowEssenceDetail(articleId int) (item *ArticleRoadshowEssenceDetail, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
	art.* ,
	GROUP_CONCAT( DISTINCT mg.industrial_management_id SEPARATOR ',' ) AS industrial_management_id ,
	GROUP_CONCAT( DISTINCT m.industry_name SEPARATOR ',' ) AS industry_name,
	GROUP_CONCAT( DISTINCT sg.industrial_subject_id SEPARATOR ',' ) AS industrial_subject_id_str ,
	GROUP_CONCAT( DISTINCT s.subject_name SEPARATOR ',' ) AS subject_name 
FROM
	cygx_article  as art 
	LEFT JOIN cygx_industrial_article_group_management as mg ON mg.article_id = art.article_id
	LEFT JOIN cygx_industrial_management as m ON m.industrial_management_id = mg.industrial_management_id
	LEFT JOIN cygx_industrial_article_group_subject as sg ON sg.article_id = art.article_id
	LEFT JOIN cygx_industrial_subject as s ON s.industrial_subject_id = sg.industrial_subject_id
WHERE
	art.article_id =  ?`
	err = o.Raw(sql, articleId).QueryRow(&item)
	return
}

// 列表
func GetArticleRoadshowEssenceList(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxResearchSummaryRep, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT *,
				(SELECT COUNT(1) FROM cygx_article_history_record AS h WHERE h.article_id=art.article_id) AS pv,
        		(SELECT COUNT(DISTINCT user_id) FROM cygx_article_history_record AS h WHERE h.article_id=art.article_id) AS uv
				FROM cygx_article as art WHERE 1= 1 `
	if condition != "" {
		sql += condition
	}
	sql += `   LIMIT ?,?`
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

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

// GetArticleListByIdList 根据报告id列表获取报告列表
func GetArticleListByIdList(articleLIdList []int) (items []*CygxArticle, err error) {
	num := len(articleLIdList)
	if num <= 0 {
		return
	}

	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_article as art WHERE 1= 1 AND article_id in (` + utils.GetOrmInReplace(num) + `)`
	_, err = o.Raw(sql, articleLIdList).QueryRows(&items)
	return
}

// RoadshowEssencePublishAndCancel 修改发布状态
func RoadshowEssencePublishAndCancel(item *CygxResearchSummaryRep) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `UPDATE cygx_article SET  publish_status=? , last_updated_time= ?, periods= ?,admin_id =? ,admin_name =? ,have_publish = 1 WHERE article_id=? `
	_, err = o.Raw(sql, item.PublishStatus, time.Now(), item.Periods, item.AdminId, item.AdminName, item.ArticleId).Exec()
	return
}

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

func UpdateArticleInfoVideo(reportId int, tbName, videoUrl, videoName, videoSize string, playSeconds float64) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `UPDATE ` + tbName + ` SET video_url=?,video_name=?,video_play_seconds=?,video_size=? WHERE article_id=? `
	_, err = o.Raw(sql, videoUrl, videoName, playSeconds, videoSize, reportId).Exec()
	return
}

// 客户其他行为数据导出 start
type CygxArticleCollect struct {
	ArticleId      int    `description:"文章id"`
	UserId         int    `description:"用户ID"`
	Title          string `description:"标题"`
	CreateTime     string `description:"创建时间"`
	PublishDate    string `description:"发布时间"`
	PermissionName string `description:"行业"`
	IndustryName   string `description:"产业名称"`
	SubjectName    string `description:"关联标的"`
	MatchTypeName  string `description:"报告类型"`
	CategoryId     string `description:"分类ID"`
}

type CygxArticleIndustry struct {
	UserId                 int    `description:"用户ID"`
	IndustrialManagementId int    `description:"产业id"`
	CreateTime             string `description:"创建时间"`
	IndustryName           string `description:"产业名称"`
}

type ArticleDepartment struct {
	DepartmentId           int    `description:"主键ID"`
	NickName               string `description:"昵称"`
	UserId                 int    `description:"用户ID"`
	IndustrialManagementId int    `description:"产业id"`
	CreateTime             string `description:"创建时间"`
	IndustryName           string `description:"产业名称"`
}

type KeyWord struct {
	UserId     int    `description:"用户ID"`
	CreateTime string `description:"创建时间"`
	KeyWord    string `description:"关键词"`
}

type CompanyOtherHistoryList struct {
	Mobile         string `description:"手机号"`
	Email          string `description:"邮箱"`
	RealName       string `description:"姓名"`
	ListArticle    []*CygxArticleCollect
	ListIndustrial []*CygxArticleIndustry
	ListDepartment []*ArticleDepartment
	ListKeyWord    []*KeyWord
}

type CompanyOtherHistoryListResp struct {
	List []*CompanyOtherHistoryList
}

// 文章列表
func GetArticleCollectList(condition string) (items []*CygxArticleCollect, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
			c.*,
			a.title,
			a.publish_date,
			a.category_id,
			a.match_type_name,
			(SELECT
				GROUP_CONCAT( DISTINCT m.industry_name SEPARATOR ',' ) AS industry_name 
			FROM
				cygx_industrial_management AS m 
			WHERE
			industrial_management_id IN ( SELECT industrial_management_id FROM cygx_industrial_article_group_management AS mg WHERE mg.article_id = c.article_id )) AS industry_name,
			(SELECT
				GROUP_CONCAT( DISTINCT s.subject_name SEPARATOR ',' ) AS subject_name 
			FROM
				cygx_industrial_subject AS s 
			WHERE
			industrial_subject_id IN ( SELECT industrial_subject_id FROM cygx_industrial_article_group_subject AS sg WHERE sg.article_id = c.article_id )) AS subject_name 
		FROM
			cygx_article_collect AS c
			INNER JOIN cygx_article AS a ON a.article_id = c.article_id 
		WHERE 1=1`
	if condition != "" {
		sql += condition
	}
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 产业列表
func GetCygxIndustryList(companyId int) (items []*CygxArticleIndustry, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
			f.user_id,f.create_time,m.industrial_management_id,m.industry_name
		FROM
			cygx_industry_fllow AS f
			INNER JOIN cygx_industrial_management AS m ON m.industrial_management_id = f.industrial_management_id 
		WHERE
			1 = 1 
			AND f.company_id = ?`
	_, err = o.Raw(sql, companyId).QueryRows(&items)
	return
}

// 作者列表
func GetArticleDepartmentList(companyId int) (items []*ArticleDepartment, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
			f.user_id,f.create_time,m.department_id,m.nick_name,
			(SELECT
						GROUP_CONCAT( DISTINCT m.industry_name SEPARATOR ',' ) AS industry_name 
					FROM
						cygx_industrial_management AS m 
					WHERE
					industrial_management_id IN ( SELECT industrial_management_id FROM cygx_industrial_article_group_management AS mg WHERE mg.article_id IN(SELECT article_id FROM cygx_article WHERE department_id = f.department_id) )) AS industry_name
		FROM
			cygx_article_department_follow AS f
			INNER JOIN cygx_article_department AS m ON m.department_id = f.department_id 
		WHERE
			1 = 1 
			AND f.company_id = ?`
	_, err = o.Raw(sql, companyId).QueryRows(&items)
	return
}

// 关键词列表
func GetCygxSearchKeyWordList(userIdStr string) (items []*KeyWord, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT *  FROM cygx_search_key_word  WHERE user_id IN (` + userIdStr + `)`
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

// 关键词列表
func GetCygxUserSearchKeyWordList(userIdStr string) (items []*KeyWord, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT *  FROM cygx_user_search_key_word  WHERE user_id IN (` + userIdStr + `) AND  page_type IN ('ReortSearch','HomeSearch')`
	_, err = o.Raw(sql).QueryRows(&items)
	return
} //end

type CreateTimesResp struct {
	CreateTimes string `description:"创建时间"`
}

type CompanyArticleCountResp struct {
	CreateTimes string `description:"创建时间"`
	ReadSum     int    `description:"总阅读数"`
	YiyaoSum    int    `description:"医药阅读数"`
	XiaofeiSum  int    `description:"医药阅读数"`
	KejiSum     int    `description:"医药阅读数"`
	ZhizaoSum   int    `description:"医药阅读数"`
	CelueSum    int    `description:"医药阅读数"`
	YanxuanSum  int    `description:"医药阅读数"`
}
type CompanyArticleCountListResp struct {
	List []*CompanyArticleCountResp
}

func GetCompanyHistoryRecordPvGroupDate(mobiles, emails string) (item []*CreateTimesResp, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := ` SELECT date_format(create_time,'%Y-%m') as create_times FROM cygx_article_history_record_all AS h
			INNER JOIN cygx_article art ON art.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 ) GROUP BY create_times    ORDER BY create_times DESC  `
	_, err = o.Raw(sql).QueryRows(&item)
	return
}

func GetCompanyHistoryRecordPv(mobiles, emails string) (item []*CompanyHistoryRecordNewPvRep, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := ` SELECT
			a.title,
			a.category_id,
		date_format(h.create_time,'%Y-%m') as create_time,
			m.chart_permission_name as permission_name
		FROM
			cygx_article_history_record_all AS h
			INNER JOIN cygx_article AS a ON a.article_id = h.article_id
			LEFT JOIN cygx_report_mapping AS m ON a.category_id = m.category_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
}

type CygxCelueArticleHistoryRecord struct {
	Id             int       `orm:"column(id);pk"`
	ArticleId      int       `description:"文章ID"`
	CelueHistoryId int       `description:"策略平台记录的ID"`
	CreateTime     string    `description:"本地创建时间"`
	CreateDateApi  time.Time `description:"图表创建时间"`
	Mobile         string    `description:"手机号"`
	CompanyName    string    `description:"公司名称"`
	RealName       string    `description:"用户姓名"`
}

func GetCygxCelueArticleHistoryRecordPvAll(articleIds string) (item []*ArticleHistoryRep, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_article_history_record_all as  h WHERE article_id IN ( ` + articleIds + ` )  AND   h.is_del = 0  AND h.company_id != 16   AND h.platfor = 2  `
	sql += ` ORDER BY create_time DESC  `
	_, err = o.Raw(sql).QueryRows(&item)
	return
}

func GetCygxCelueArticleComapnyName(mobiles string) (item []*ArticleHistoryRep, err error) {
	o := orm.NewOrm()
	sql := `SELECT
	c.company_name,a.real_name,u.mobile
FROM
	wx_user AS u
	INNER JOIN company as c ON c.company_id = u.company_id 
	INNER JOIN company_product as p ON p.company_id = c.company_id
	INNER JOIN admin as a On  a.admin_id = p.seller_id 
	WHERE p.product_id = 2
	AND u.mobile IN  ( ` + mobiles + `) GROUP BY u.mobile  `
	_, err = o.Raw(sql).QueryRows(&item)
	return
}

type ArticleDetailResp struct {
	ArticleId          int       `description:"文章ID"`
	Title              string    `description:"标题"`
	Abstract           string    `description:"摘要"`
	Body               string    `description:"内容"`
	PublishStatus      int       `description:"发布状态，0未发布 ，1已发布"`
	PublishDate        string    `description:"发布时间"`
	CreateDate         time.Time `description:"创建时间"`
	LastUpdatedTime    time.Time `description:"更新时间"`
	ArticleIdMd5       string    `description:"ID，md5值"`
	SellerAndMobile    string    `description:"作者(姓名与手机号)"`
	SubjectName        string    `description:"标的名称"`
	IndustryName       string    `description:"产业名称"`
	DepartmentId       int       `description:"作者id"`
	ChartPermissionIds string    `description:"行业ID ,多个用 , 隔开"`
	ArticleTypeId      int       `description:"文章类型ID"`
	ArticleTypeName    string    `description:"文章类型名称"`
	ListIndustrial     []*IndustrialActivityGroupManagementRep
	ListSubject        []*SubjectActivityGroupManagementRep
	ImgUrl             string `description:"头像url"`
	NickName           string `description:"昵称"`
	ReportLink         string `description:"报告链接"`
}

// GetArticleIdsFromIndustryAndSubjectGroupByKeyword 产业/标的关键词获取文章IDs
func GetArticleIdsFromIndustryAndSubjectGroupByKeyword(keyword string) (ids []int, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT DISTINCT
				mg.article_id
			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 m.industry_name LIKE ?
			
			UNION
			
			SELECT DISTINCT
				sg.article_id
			FROM
				cygx_industrial_article_group_subject AS sg
			INNER JOIN cygx_industrial_subject AS s ON s.industrial_subject_id = sg.industrial_subject_id
			WHERE
				1 = 1
			AND s.subject_name LIKE ?`
	_, err = o.Raw(sql, keyword, keyword).QueryRows(&ids)
	return
}

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

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