package models

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

type CygxResourceData struct {
	Id                int       `orm:"column(id);pk"`
	ChartPermissionId int       `description:"行业ID"`
	SourceId          int       `description:"资源ID"`
	Source            string    `description:"资源类型 报告 ：article 、图表 ：newchart、微路演 ：roadshow、活动 ：activity、活动视频：activityvideo、活动音频：activityvoice、专项调研活动：activityspecial"`
	Title             string    `description:"标题"`
	Annotation        string    `description:"核心观点"`
	CreateTime        time.Time `description:"创建时间"`
	PublishDate       string    `description:"发布时间"`
	Abstract          string    `description:"摘要"`
	SearchTag         string    `description:"搜索标签"`
	SearchTitle       string    `description:"搜索匹配用的标题"`
	SearchContent     string    `description:"搜索匹配用的内容"`
	SearchOrderTime   string    `description:"搜索排序时间"`
	TagName           string    `description:"标签名"`
	Sort              int       `description:"排序"`
}

// FICC研报小程序
type FiccReportXcx struct {
	Source        string `description:"资源类型"`
	Title         string `description:"标题"`
	SecondTitle   string `description:"副标题"`
	ImgUrl        string `description:"背景图片"`
	HasPermission int    `description:"1:有该行业权限,正常展示，2：无该行业权限，不存在权益客户下，3:无该品类权限,已提交过申请，4：无该行业权限,未提交过申请，5：潜在客户，未提交过申请，6：潜在客户,已提交过申请"`
	Mobile        string `description:"用户手机号"`
	SellerMobile  string `description:"销售电话"`
	SellerName    string `description:"销售姓名"`
	Appid         string `description:"FICC研报小程序Appid"`
	SourceUrl     string `description:"跳转资源地址"`
	ThirdCode     string `description:"三方加密标识"`
}

type CygxResourceDataResp struct {
	Id                 int                                     `orm:"column(id);pk"`
	BodyHighlight      []string                                `description:"搜索高亮展示结果"`
	IsSummary          int                                     `description:"是否是纪要"`
	SourceId           int                                     `description:"资源ID"`
	Source             string                                  `description:"资源类型 报告 ：article 、图表 ：newchart、微路演 ：roadshow、活动 ：activity、活动视频：activityvideo、活动音频：activityvoice、专项调研活动：activityspecial"`
	PublishDate        string                                  `description:"发布时间"`
	Article            *HomeArticle                            `description:"文章"`
	Newchart           *HomeChartListResp                      `description:"图表"`
	Roadshow           *MicroRoadShowPageList                  `description:"微路演"`
	Activity           *ActivityDetail                         `description:"活动"`
	Activityvideo      *MicroRoadShowPageList                  `description:"活动视频"`
	Activityvoice      *MicroRoadShowPageList                  `description:"活动音频"`
	Activityspecial    *CygxActivitySpecialDetail              `description:"专项调研活动"`
	Researchsummary    *CygxReportSelectionRep                 `description:"本周研究汇总"`
	Minutessummary     *CygxReportSelectionRep                 `description:"上周纪要汇总"`
	Meetingreviewchapt *CygxMorningMeetingGatherDetailListResp `description:"晨会精华"`
	ProductInterior    *CygxProductInteriorResp                `description:"产品内测"`
	IndustrialResource *IndustrialManagementHotResp            `description:"产业资源包"`
	ReportSelection    *CygxReportSelectionRep                 `description:"重点公司（原报告精选）"`
	YanxuanSpecial     *CygxYanxuanSpecialCenterResp           `description:"研选专栏"`
	AskserieVideo      *MicroRoadShowPageList                  `description:"活动音频"`
	FiccReport         *HomeArticle                            `description:"FICC研报"`
	FiccReportXcx      *FiccReportXcx                          `description:"FICC研报"`
}

// Source      string    `description:"资源类型 报告 ：article 、图表 ：newchart、微路演 ：roadshow、活动 ：activity、活动视频：activityvideo、活动音频：activityvoice、专项调研活动：activityspecial"`
type HomeResourceDataListResp struct {
	Paging *paging.PagingItem
	List   []*CygxResourceDataResp `description:"列表"`
}

// 列表
func GetResourceDataList(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxResourceData, err error) {
	o := orm.NewOrm()
	sql := `SELECT	 *   FROM cygx_resource_data  WHERE 1= 1 `
	if condition != "" {
		sql += condition
	}
	sql += ` ORDER BY publish_date  DESC ,  id  DESC   LIMIT ?,? `
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

// 列表
func GetResourceDataListCondition(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxResourceData, err error) {
	o := orm.NewOrm()
	sql := `SELECT	 *   FROM cygx_resource_data  WHERE 1= 1 `
	if condition != "" {
		sql += condition
	}
	sql += `  ORDER BY  sort DESC , search_order_time DESC   LIMIT ?,? `
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

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

// 添加
func AddCygxResourceData(item *CygxResourceData) (lastId int64, err error) {
	o := orm.NewOrm()
	lastId, err = o.Insert(item)
	return
}

// 删除数据
func DeleteResourceData(sourceId int, source string) (err error) {
	o := orm.NewOrm()
	sql := ` DELETE FROM cygx_resource_data WHERE source_id = ? AND source =?  `
	_, err = o.Raw(sql, sourceId, source).Exec()
	return
}

// 修改数据
func UpdateResourceData(sourceId int, source, publishDate string) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE cygx_resource_data SET publish_date=?  WHERE source_id=?  AND source =? `
	_, err = o.Raw(sql, publishDate, sourceId, source).Exec()
	return
}

// 修改
func UpdateResourceDataByItem(item *CygxResourceData) (err error) {
	o := orm.NewOrm()
	updateParams := make(map[string]interface{})
	updateParams["PublishDate"] = item.PublishDate
	updateParams["SearchTag"] = item.SearchTag
	updateParams["SearchTitle"] = item.SearchTitle
	updateParams["TagName"] = item.TagName
	updateParams["SearchContent"] = item.SearchContent
	updateParams["SearchOrderTime"] = item.SearchOrderTime
	ptrStructOrTableName := "cygx_resource_data"
	whereParam := map[string]interface{}{"source_id": item.SourceId, "source": item.Source}
	qs := o.QueryTable(ptrStructOrTableName)
	for expr, exprV := range whereParam {
		qs = qs.Filter(expr, exprV)
	}
	_, err = qs.Update(updateParams)
	if err != nil {
		return
	}
	return
}

// 批量删除
func DeleteResourceDataList(condition string, pars []interface{}) (err error) {
	if condition == "" {
		return
	}
	o := orm.NewOrm()
	sql := `DELETE  FROM cygx_resource_data   WHERE  1=1 ` + condition
	_, err = o.Raw(sql, pars).Exec()
	return
}

// 获取数量
func GetCygxReportSelectionBySourceAndId(sourceId int, source string) (count int, err error) {
	o := orm.NewOrm()
	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_resource_data  WHERE  source_id = ? AND source =?  `
	err = o.Raw(sqlCount, sourceId, source).QueryRow(&count)
	return
}

// 通过ID跟资源获取详情
func GetCygxResourceDataByIdAndSource(sourceId int, source string) (item *CygxResourceData, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_resource_data WHERE  source_id = ? AND source =?  `
	err = o.Raw(sql, sourceId, source).QueryRow(&item)
	return
}

// 获取数量
func GetCygxResourceDataBySourceAndIdCount(sourceId int, source string) (count int, err error) {
	o := orm.NewOrm()
	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_resource_data  WHERE  source_id = ? AND source =?  `
	err = o.Raw(sqlCount, sourceId, source).QueryRow(&count)
	return
}

// 隐藏同步过来的报告
func HideCygxResourceDataFiccReport(sourceIds []int) (err error) {
	lenArr := len(sourceIds)
	if lenArr == 0 {
		return
	}
	o := orm.NewOrm()
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	//隐藏资源表
	sql := ` DELETE  FROM cygx_resource_data  WHERE source_id IN (` + utils.GetOrmInReplace(lenArr) + `)  AND source = ? `
	_, err = to.Raw(sql, sourceIds, utils.CYGX_OBJ_FICC_REPORT).Exec()
	if err != nil {
		return
	}

	//对应文章取消发布
	sql = ` UPDATE cygx_article SET publish_status= 0  WHERE report_id IN (` + utils.GetOrmInReplace(lenArr) + `) `
	_, err = to.Raw(sql, sourceIds).Exec()
	if err != nil {
		return
	}

	return
}

// 更新搜索标题
func UpdatecygxResourceDatasearchTitle(searchTitle string, sourceId int) (err error) {
	o := orm.NewOrm()
	sql := ` UPDATE cygx_resource_data SET search_title= ?  WHERE source_id =  ? AND   source = 'article'  `
	_, err = o.Raw(sql, searchTitle, sourceId).Exec()
	if err != nil {
		return
	}

	return
}
