package cygx

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

type CygxMinutesSummary struct {
	ArticleId       int       `orm:"column(article_id);pk"description:"报告id"`
	Title           string    `description:"标题"`
	Department      string    `description:"作者"`
	Abstract        string    `description:"摘要"`
	PublishStatus   int       `description:"发布状态，1已发布，0未发布"`
	PublishDate     time.Time `description:"发布时间"`
	CreateTime      time.Time `description:"创建时间"`
	LastUpdatedTime time.Time `description:"最后一次更新时间"`
	Periods         string    `description:"期数"`
	HavePublish     int       `description:"是否发布过，1是，0否"`
	AdminId         int       `description:"销售/管理员ID"`
	AdminName       string    `description:"销售/管理员姓名"`
}

type CygxMinutesSummaryRep struct {
	ArticleId       int    `orm:"column(article_id);pk"description:"报告id"`
	Title           string `description:"标题"`
	Department      string `description:"作者"`
	Abstract        string `description:"摘要"`
	PublishStatus   int    `description:"发布状态，1已发布，0未发布"`
	PublishDate     string `description:"发布时间"`
	CreateTime      string `description:"创建时间"`
	LastUpdatedTime string `description:"最后一次更新时间"`
	Periods         string `description:"期数"`
	HavePublish     int    `description:"是否发布过，1是，0否"`
	Pv              int    `description:"PV"`
	Uv              int    `description:"Uv"`
	AdminId         int    `description:"销售/管理员ID"`
	AdminName       string `description:"销售/管理员姓名"`
	VisibleRange    int    `description:"设置可见范围1全部，0内部"`
	IsSendWxMsg     int    `description:"是否推送过微信模版消息，1是，0否"`
}

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

type AddCygxMinutesSummary struct {
	ArticleId   int                       `description:"报告Id ，传0时新增，大于0时修改"`
	Title       string                    `description:"标题"`
	Department  string                    `description:"作者"`
	Abstract    string                    `description:"摘要"`
	DoType      int                       `description:"操作方式，1发布，0保存"`
	PublishDate string                    `description:"发布时间"`
	Content     *CygxMinutesList          `description:"内容"`
	List        []*CygxMSlChartPermission `description:"内容"`
}

type DetailCygxMinutesSummaryRep struct {
	ArticleId     int    `description:"报告Id ，传0时新增，大于0时修改"`
	Title         string `description:"标题"`
	Department    string `description:"作者"`
	Abstract      string `description:"摘要"`
	PublishDate   string `description:"发布时间"`
	PublishStatus int    `description:"发布状态，1已发布，0未发布"`
	//List          []*CygxRSlChartPermissionIco `description:"内容列表"`

	SortCydyjy string                       `description:"产业调研纪要排序"`
	ListCydyjy []*CygxRSlChartPermissionIco `description:"类型——’CYDYJY：产业调研纪要’"`
	ListSsgs   []*CygxRSlChartPermissionIco `description:"类型——’SSGS：上市公司调研纪要篇’"`
	SortSsgs   string                       `description:"上市公司调研纪要篇排序"`
	SortYanx   string                       `description:"研选排序"`
	ListYanx   []*AddCygxMinutesSummaryLog  `description:"类型——’YANX：研选’"`
}

type CygxMinutesList struct {
	ListCydyjy []*CygxRSlChartPermission   `description:"类型——’CYDYJY：产业调研纪要’"`
	SortCydyjy string                      `description:"产业调研纪要排序"`
	ListSsgs   []*CygxRSlChartPermission   `description:"类型——’SSGS：上市公司调研纪要篇’"`
	SortSsgs   string                      `description:"上市公司调研纪要篇排序"`
	ListYanx   []*AddCygxMinutesSummaryLog `description:"类型——’YANX：研选’"`
	SortYanx   string                      `description:"研选排序"`
}

type DetailCygxMinutesSummaryTmpRep struct {
	Title       string                          `description:"标题"`
	Department  string                          `description:"作者"`
	Abstract    string                          `description:"摘要"`
	PublishDate string                          `description:"发布时间"`
	SortSdbg    string                          `description:"深度报告排序"`
	ListSdbg    []*CygxRSlChartPermissionIcoTmp `description:"类型——’SDBG：深度报告片篇’"`
	SortCydyjy  string                          `description:"产业调研纪要排序"`
	ListCydyjy  []*CygxRSlChartPermissionIcoTmp `description:"类型——’CYDYJY：产业调研纪要’"`
	SortSjdp    string                          `description:"事件点评排序"`
	ListSjdp    []*AddCygxMinutesSummaryLog     `description:"类型——’SJDP：事件点评"`
	SortBzchjh  string                          `description:"本周晨会精华排序"`
	ListBzchjh  []*CygxRSlChartPermissionIcoTmp `description:"类型——’BZCHJH：本周晨会精华’"`
}

type MinutesSummaryId struct {
	ArticleId int `description:"报告Id"`
}

// 添加
func AddCygxMinutesSummaryOrm(itme *CygxMinutesSummary, items []*CygxMinutesSummaryLog) (newArtId int64, err error) {
	o := orm.NewOrm()
	//o.Begin()
	//defer func() {
	//	fmt.Println(err)
	//	if err == nil {
	//		o.Commit()
	//	} else {
	//		o.Rollback()
	//	}
	//}()
	newArtId, err = o.Insert(itme)
	if err != nil {
		return
	}
	for _, v := range items {
		v.ArticleId = int(newArtId)
		_, err = o.Insert(v)
		if err != nil {
			return
		}
	}
	return
}

// 编辑
func UpdateCygxMinutesSummaryOrm(item *CygxMinutesSummary, items []*CygxMinutesSummaryLog) (newId int64, 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()
		}
	}()
	articleId := item.ArticleId
	fmt.Println("m文章ID", articleId)
	sql := `UPDATE cygx_minutes_summary SET title=?, department=? ,abstract = ?,publish_status = ?,publish_date = ?,last_updated_time = ?,periods = ?,admin_id =? ,admin_name =? ,have_publish = ? WHERE article_id=?`
	_, err = to.Raw(sql, item.Title, item.Department, item.Abstract, item.PublishStatus, item.PublishDate, item.LastUpdatedTime, item.Periods, item.AdminId, item.AdminName, item.HavePublish, articleId).Exec()
	if err != nil {
		return
	}
	sql = ` DELETE FROM cygx_minutes_summary_log WHERE article_id = ?`
	_, err = to.Raw(sql, articleId).Exec()
	if err != nil {
		return
	}
	for _, v := range items {
		v.ArticleId = articleId
		newId, err = to.Insert(v)
		if err != nil {
			return
		}
	}
	return
}

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

// 通过纪要ID获取活动详情
func GetCygxMinutesSummaryInfoById(articleId int) (item *CygxMinutesSummaryRep, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_minutes_summary  WHERE article_id=?`
	err = o.Raw(sql, articleId).QueryRow(&item)
	return
}

// 删除数据
func DeleteCygxMinutesSummary(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 := ` DELETE FROM cygx_minutes_summary  WHERE article_id=? `
	_, err = to.Raw(sql, articleId).Exec()
	if err != nil {
		return
	}
	sql = ` DELETE FROM cygx_minutes_summary_log WHERE article_id = ?`
	_, err = to.Raw(sql, articleId).Exec()
	return
}

// 列表
func GetMinutesSummaryList(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxMinutesSummaryRep, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT *,
				(SELECT COUNT(1) FROM cygx_report_history_record AS h WHERE h.article_id=rs.article_id AND report_type = 'szjyhz'  AND  h.company_id != 16 ) AS pv,
        		(SELECT COUNT(DISTINCT user_id) FROM cygx_report_history_record AS h WHERE h.article_id=rs.article_id  AND report_type = 'szjyhz' AND  h.company_id != 16 ) AS uv
				FROM cygx_minutes_summary as rs WHERE 1= 1 `
	if condition != "" {
		sql += condition
	}
	sql += ` ORDER BY  rs.publish_date  DESC  LIMIT ?,?`
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

// 修改发布状态
func MinutesSummaryPublishAndCancel(item *CygxMinutesSummaryRep) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `UPDATE cygx_minutes_summary 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 MinutesSummaryVisibleRange(item *CygxMinutesSummaryRep) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `UPDATE cygx_minutes_summary SET  is_send_wx_msg = 1,  visible_range=? , last_updated_time= ?,admin_id =? ,admin_name =?  WHERE article_id=? `
	_, err = o.Raw(sql, item.VisibleRange, time.Now(), item.AdminId, item.AdminName, item.ArticleId).Exec()
	return
}

// 列表
func GetMinutesSummarylogListAll(articleId int) (items []*ResearchSummaryChartPermission, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	//sql := `SELECT c.permission_name ,c.image_url,l.*
	//		FROM
	//		cygx_minutes_summary_log AS l
	//		INNER JOIN chart_permission AS c ON c.chart_permission_id = l.chart_permission_id
	//		WHERE l.article_id = ?
	//		GROUP BY l.chart_permission_id
	//		ORDER BY l.chart_permission_sort ASC   `

	sql := `SELECT l.* 
			FROM cygx_minutes_summary_log AS l 
			WHERE l.article_id = ? 
			GROUP BY l.type 
			ORDER BY l.sort ASC `
	_, err = o.Raw(sql, articleId).QueryRows(&items)
	return
}

// 列表
func GetMinutesSummarylogSonListSecond(articleId int, artType string) (items []*CygxResearchSummaryLogSecond, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT  l.* 
			FROM
			cygx_minutes_summary_log AS l
			WHERE l.article_id = ? AND l.type =?
			GROUP BY l.chart_permission_id
			ORDER  BY l.chart_permission_sort ASC`
	_, err = o.Raw(sql, articleId, artType).QueryRows(&items)
	return
}

// 列表
func GetMinutesSummarylogListThird(articleId, chartPermissionId int, artType string) (items []*CygxResearchSummaryLogThird, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT  l.link_article_id,l.body ,a.video_url
			FROM cygx_minutes_summary_log AS l
			LEFT JOIN cygx_article as a ON a.article_id = l.link_article_id
			WHERE l.article_id = ? AND l.type =? AND  l.chart_permission_id = ? 
			ORDER  BY l.chart_permission_sort ASC `
	_, err = o.Raw(sql, articleId, artType, chartPermissionId).QueryRows(&items)
	return
}

type MinutesSummaryChartPermission struct {
	PermissionName    string `description:"行业名称"`
	ChartPermissionId int    `description:"行业ID"`
	MinutesSummary    string `orm:"column(image_url)"description:"图标链接"`
	List              []*CygxMinutesSummaryLogDetail
}

type CygxMinutesSummaryLogDetail struct {
	Body        string `description:"内容"`
	ReportLink  string `orm:"column(link_article_id)"description:"报告链接"`
	VideoUrl    string `description:"链接"`
	IsHaveVideo bool   `description:"是否含有音频文件"`
}

// 列表
func GetMinutesSummarylogSonListAll(articleId, chartPermissionId int) (items []*CygxMinutesSummaryLogDetail, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT   l.link_article_id,l.body ,a.video_url 
			FROM
			cygx_minutes_summary_log AS l
			LEFT JOIN cygx_article as a ON a.article_id = l.link_article_id
			WHERE l.article_id = ? AND l.chart_permission_id =?`
	_, err = o.Raw(sql, articleId, chartPermissionId).QueryRows(&items)
	return
}
