package cygx

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

type CygxReportSelection struct {
	ArticleId          int       `orm:"column(article_id);pk"description:"报告id"`
	AddType            string    `description:"更新方式 1重新编辑  ，2 继承往期"`
	Title              string    `description:"标题"`
	Department         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否"`
	InheritPeriods     string    `description:"继承期数"`
	ProductDescription string    `description:"产品说明"`
	UpdateDescription  string    `description:"更新说明"`
	FocusOn            string    `description:"近期重点关注方向"`
	AdminId            int       `description:"销售/管理员ID"`
	AdminName          string    `description:"销售/管理员姓名"`
	MarketStrategy     string    `description:"市场策略核心逻辑汇总"`
	ReportLink         string    `description:"报告链接"`
}

type CygxReportSelectionRep struct {
	ArticleId          int    `orm:"column(article_id);pk"description:"报告id"`
	AddType            string `description:"更新方式 1重新编辑  ，2 继承往期"`
	Title              string `description:"标题"`
	Department         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"`
	ProductDescription string `description:"产品说明"`
	UpdateDescription  string `description:"更新说明"`
	FocusOn            string `description:"近期重点关注方向"`
	InheritPeriods     string `description:"继承期数"`
	AdminId            int    `description:"销售/管理员ID"`
	AdminName          string `description:"销售/管理员姓名"`
	MarketStrategy     string `description:"市场策略核心逻辑汇总"`
	ReportLink         string `description:"报告链接"`
	VisibleRange       int    `description:"设置可见范围1全部，0内部"`
	IsSendWxMsg        int    `description:"是否推送过微信模版消息，1是，0否"`
	ApplyTotal         int    `description:"申请路演的数量"`
}

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

type AddCygxReportSelection struct {
	ArticleId          int                               `description:"报告Id ，传0时新增，大于0时修改"`
	AddType            string                            `description:"更新方式 1重新编辑  ，2 继承往期"`
	InheritPeriods     string                            `description:"继承期数"`
	Title              string                            `description:"标题"`
	Department         string                            `description:"作者"`
	PublishDate        string                            `description:"发布时间"`
	ProductDescription string                            `description:"产品说明"`
	UpdateDescription  string                            `description:"更新说明"`
	FocusOn            string                            `description:"近期重点关注方向"`
	DoType             int                               `description:"操作方式，1发布，0保存"`
	MarketStrategy     string                            `description:"市场策略核心逻辑汇总"`
	ReportLink         string                            `description:"报告链接"`
	List               []*AddCygxReportSelectionLog      `description:"标的列表内容"`
	ListChartSummary   []*AddCygxReportSelectionChartLog `description:"行业核心逻辑汇总列表"`
}

type OverviewArticle struct {
	ArticleId int    `description:"文章ID"`
	Title     string `description:"文章标题"`
}

type DetailCygxReportSelectionRep struct {
	ArticleId          int                         `description:"报告Id ，传0时新增，大于0时修改"`
	AddType            string                      `description:"更新方式 1重新编辑  ，2 继承往期"`
	Title              string                      `description:"标题"`
	Department         string                      `description:"作者"`
	PublishStatus      int                         `description:"发布状态，1已发布，0未发布"`
	PublishDate        string                      `description:"发布时间"`
	CreateTime         string                      `description:"创建时间"`
	LastUpdatedTime    string                      `description:"最后一次更新时间"`
	Periods            string                      `description:"期数"`
	HavePublish        int                         `description:"是否发布过，1是，0否"`
	InheritPeriods     string                      `description:"继承期数"`
	InheritPeriodsName string                      `description:"继承期数名称"`
	ProductDescription string                      `description:"产品说明"`
	UpdateDescription  string                      `description:"更新说明"`
	FocusOn            string                      `description:"近期重点关注方向"`
	MarketStrategy     string                      `description:"市场策略核心逻辑汇总"`
	ReportLink         string                      `description:"报告链接"`
	List               []*CygxReportSelectionChart `description:"内容列表"`
}

type HistoryReportSelectionRep struct {
	Count int                            `description:"数量"`
	List  []*HistoryReportSelectionChart `description:"内容列表"`
}

type HistoryReportSelectionChart struct {
	//ChartPermissionId   int                           `description:"行业ID"`
	ChartPermissionName string                           `description:"行业名称"`
	List                []*HistoryReportSelectionLogResp `description:"列表内容’"`
}

type HistoryReportSelectionLogResp struct {
	IndustrialSubjectId string `description:"标的ID"`
	SubjectName         string `description:"标的名称"`
	Count               int    `description:"数量"`
	IsNew               int    `description:"是否为New标签"`
}

type ReportSelectionId struct {
	ArticleId int `description:"报告ID"`
}

// 添加
func AddCygxReportSelectionOrm(itme *CygxReportSelection, items []*CygxReportSelectionLog, itemsChart []*CygxReportSelectionChartLog) (newArtId 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()
		}
	}()
	newArtId, err = to.Insert(itme)
	if err != nil {
		return
	}
	for _, v := range items {
		v.ArticleId = int(newArtId)
		_, err = to.Insert(v)
		if err != nil {
			return
		}
	}
	for _, v := range itemsChart {
		v.ArticleId = int(newArtId)
		_, err = to.Insert(v)
		if err != nil {
			return
		}
	}
	return
}

// 编辑
func UpdateCygxReportSelectionOrm(item *CygxReportSelection, items []*CygxReportSelectionLog, itemsChart []*CygxReportSelectionChartLog) (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_report_selection SET title=?, department=? ,add_type = ?, inherit_periods= ? ,product_description=?,update_description=?,focus_on=?, publish_status = ?,publish_date = ?,last_updated_time = ?,periods = ?,admin_id =? ,admin_name =? ,have_publish = ?,market_strategy = ?,report_link = ? WHERE article_id=?`
	_, err = to.Raw(sql, item.Title, item.Department, item.AddType, item.InheritPeriods, item.ProductDescription, item.UpdateDescription, item.FocusOn, item.PublishStatus, item.PublishDate, item.LastUpdatedTime, item.Periods, item.AdminId, item.AdminName, item.HavePublish, item.MarketStrategy, item.ReportLink, articleId).Exec()
	if err != nil {
		return
	}
	sql = ` DELETE FROM cygx_report_selection_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
		}
	}

	sql = ` DELETE FROM cygx_report_selection_chart_log WHERE article_id = ?`
	_, err = to.Raw(sql, articleId).Exec()
	if err != nil {
		return
	}
	for _, v := range itemsChart {
		v.ArticleId = articleId
		newId, err = to.Insert(v)
		if err != nil {
			return
		}
	}
	return
}

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

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

// 通过纪要ID获取活动详情
func GetCygxReportSelectionInfoByPeriods(periods string) (item *CygxReportSelectionRep, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT * FROM cygx_report_selection  WHERE periods=?`
	err = o.Raw(sql, periods).QueryRow(&item)
	return
}

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

// 列表
func GetReportSelectionList(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxReportSelectionRep, 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 = 'bgjx' 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 = 'bgjx' AND  h.company_id != 16 ) AS uv
				FROM cygx_report_selection 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 ReportSelectionPublishAndCancel(item *CygxReportSelectionRep) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `UPDATE cygx_report_selection 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 ReportSelectionVisibleRange(item *CygxReportSelectionRep) (err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `UPDATE cygx_report_selection 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
}

type CygxReportSelectionPeriodsRep struct {
	Periods            string `description:"继承期数"`
	InheritPeriodsName string `description:"继承期数"`
}

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

// 期数列表
func GetReportSelectionListPeriods(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxReportSelectionPeriodsRep, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT periods FROM cygx_report_selection as rs WHERE have_publish = 1`
	if condition != "" {
		sql += condition
	}
	sql += ` ORDER BY  rs.periods  DESC    LIMIT ?,?`
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

type ReportSelectionChartPermission struct {
	PermissionName string `description:"权限名称"`
	IcoLink        string `orm:"column(image_url)"description:"图标链接"`
	List           []*CygxReportSelectionLogDetail
}
type CygxReportSelectionLogDetail struct {
	IndustrialManagementId string `description:"产业Id"`
	SubjectName            string `description:"标的名称"`
	Body                   string `description:"内容"`
}

// 列表
func GetReportSelectionlogSonListAll(articleId, chartPermissionId int) (items []*CygxReportSelectionLogDetail, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT l.* 
			FROM
			cygx_report_selection_log AS l
			INNER JOIN cygx_industrial_subject AS s ON s.industrial_subject_id = l.industrial_subject_id 
			WHERE l.article_id = ? AND l.chart_permission_id =?`
	_, err = o.Raw(sql, articleId, chartPermissionId).QueryRows(&items)
	return
}

// 获取，bgjx:报告精选、bzyjhz:本周研究汇总、szjyhz:上周纪要汇总 阅读记录
func GetReportSelectionHistoryList(articleId int, condition string) (items []*ArticleHistoryRep, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT
			h.real_name,
			h.mobile,
			h.company_name,
			h.seller_name,
			h.create_time
			FROM
				cygx_report_history_record AS h
			WHERE
				h.article_id = ? AND  h.company_id != 16 `
	if condition != "" {
		sql = sql + condition + ` GROUP BY h.id`
	}

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

type CygxArticleIdAndTableResp struct {
	Title string `description:"标题"`
}

// 通过纪要ID获取不同类型报告的title详情
func GetArticleInfoByIdAndTable(table string, articleId int) (item *CygxArticleIdAndTableResp, err error) {
	o := orm.NewOrmUsingDB("hz_cygx")
	sql := `SELECT title FROM ` + table + `  WHERE article_id=?`
	err = o.Raw(sql, articleId).QueryRow(&item)
	return
}
