package models

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

// 报告推送给同花顺的表结构体
type ReportSendThsDetail struct {
	SendId     int       `orm:"column(send_id);pk" description:"发送给同花顺的Id"`
	ReportId   int       `description:"报告id"`
	ReportType string    `description:"报告类型"`
	Status     int8      `description:"发送结果，0：待发送，-1发送失败，1发送成功"`
	Remark     string    `description:"失败原因"`
	MsgType    int       `description:"消息类型，1：h5链接；2：小程序，3：文字；4：图片"`
	Title      string    `description:"推送标题"`
	LabelStr   string    `description:"推送标签"`
	Content    string    `description:"推送内容"`
	JumpUrl    string    `description:"跳转地址"`
	Pic        string    `description:"推送图片"`
	Level      int       `description:"等级，1：紧急，2：优先，3：普通"`
	PushTime   time.Time `description:"实际开始推送时间/预推送时间"`
	CreateTime time.Time `description:"发送时间"`
}

type ReportSendThsListResp struct {
	Paging *paging.PagingItem
	List   []*ReportSendThsListItem
}

type ReportSendThsTypeListResp struct {
	List []*ReportSendThsTypeListItem
}

type ReportSendThsTypeListItem struct {
	ReportType string `description:"报告类型"`
}

type ReportSendThsListItem struct {
	SendId     int    `description:"发送给同花顺的Id"`
	ReportId   int    `description:"报告id"`
	ReportType string `description:"报告类型"`
	Status     int8   `description:"发送结果，0：待发送，-1发送失败，1发送成功"`
	Remark     string `description:"失败原因"`
	Title      string `description:"推送标题"`
	LabelStr   string `description:"推送标签"`
	PushTime   string `description:"实际开始推送时间/预推送时间"`
	CreateTime string `description:"发送时间"`
	Level      int    `description:"等级，1：紧急，2：优先，3：普通"`
}

// 新增报告发送给同花顺的记录
func AddReportSendThsDetail(item *ReportSendThsDetail) (lastId int64, err error) {
	o := orm.NewOrm()
	//o.Using("rddp")
	lastId, err = o.Insert(item)
	return
}

// 修改报告发送给同花顺的记录状态
func ModifyReportSendThsDetailStatus(sendId int, status int8, remark string) (err error) {
	o := orm.NewOrm()
	//o.Using("rddp")
	sql := `UPDATE report_send_ths_detail SET status = ?,remark=? WHERE send_id = ? `
	_, err = o.Raw(sql, status, remark, sendId).Exec()
	return
}

// 根据报告id获取发送记录
func GetReportSendThsDetailByReportId(reportId int, reportType string) (item *ReportSendThsDetail, err error) {
	o := orm.NewOrm()
	sql := ` SELECT * FROM report_send_ths_detail WHERE report_id=? and report_type=? order by send_id desc`
	//o.Using("rddp")
	err = o.Raw(sql, reportId, reportType).QueryRow(&item)
	return
}

// GetLatelyReportSendThsDetail 获取发送中/发送成功的 距离现在最近的一条记录
func GetLatelyReportSendThsDetail() (item *ReportSendThsDetail, err error) {
	o := orm.NewOrm()
	sql := ` SELECT * FROM report_send_ths_detail WHERE status >=0  order by push_time desc,send_id desc`
	//o.Using("rddp")
	err = o.Raw(sql).QueryRow(&item)
	return
}

// GetLatelyWaitReportSendThs 获取待发送的 距离现在最近的一条记录
func GetLatelyWaitReportSendThs() (item *ReportSendThsDetail, err error) {
	o := orm.NewOrm()
	sql := ` SELECT * FROM report_send_ths_detail WHERE status =2  order by push_time desc,send_id desc`
	//o.Using("rddp")
	err = o.Raw(sql).QueryRow(&item)
	return
}

// GetNearlyWaitReportSendThsByPushTime 查询是否存在和设置时间相近的待推送记录
func GetNearlyWaitReportSendThsByPushTime(sendId int, pushTimeStart, pushTimeEnd time.Time) (item *ReportSendThsDetail, err error) {
	o := orm.NewOrm()
	sql := ` SELECT * FROM report_send_ths_detail WHERE send_id !=? and status =2 and (push_time >= ? and push_time <= ?) order by push_time desc,send_id desc`
	//o.Using("rddp")
	err = o.Raw(sql, sendId, pushTimeStart, pushTimeEnd).QueryRow(&item)
	return
}

func GetWaitReportSendThsList(condition string, pars []interface{}, startSize, pageSize int) (items []*ReportSendThsDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM report_send_ths_detail WHERE status = 2 `
	if condition != "" {
		sql += condition
	}
	sql += ` order by push_time asc,send_id asc limit ?,? `
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

func GetWaitReportSendThsType() (items []*ReportSendThsDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM report_send_ths_detail WHERE status = 2 group by report_type`
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

func GetWaitReportSendThsCount(condition string, pars []interface{}) (count int64, err error) {
	o := orm.NewOrm()
	sql := `SELECT COUNT(1) AS count FROM report_send_ths_detail WHERE status = 2 `
	if condition != "" {
		sql += condition
	}
	err = o.Raw(sql, pars).QueryRow(&count)
	return
}

func GetWaitReportSendThsAll(condition string, pars []interface{}) (items []*ReportSendThsDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM report_send_ths_detail WHERE status = 2 `
	if condition != "" {
		sql += condition
	}
	sql += ` order by push_time asc,send_id asc`
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

// 根据sendId获取发送记录
func GetReportSendThsBySendId(sendId int) (item *ReportSendThsDetail, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM report_send_ths_detail WHERE send_id=? `
	//o.Using("rddp")
	err = o.Raw(sql, sendId).QueryRow(&item)
	return
}

// MultiUpdateReportSendThsPushTime 批量修改配置时间
func MultiUpdateReportSendThsPushTime(sendId int, newTime, multiSql, updateSendIds string) (err error) {
	o := orm.NewOrm()
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	//修改单条数据
	sql := ` UPDATE report_send_ths_detail SET push_time = ? WHERE send_id = ? `
	_, err = to.Raw(sql, newTime, sendId).Exec()
	if err != nil {
		return
	}
	if multiSql != "" {
		//修改定时推送时间
		sql = `UPDATE report_send_ths_detail 
SET push_time =
CASE send_id ` + multiSql + ` END 
WHERE 
	status = 2 AND send_id IN (` + updateSendIds + ` ) AND push_time > ? `
		_, err = to.Raw(sql, newTime).Exec()
	}
	return
}

// GetLatelyWaitLevelReportSendThs 获取相同推送等级level下待发送的 距离现在最近的一条记录
func GetLatelyWaitLevelReportSendThs(level int) (item *ReportSendThsDetail, err error) {
	o := orm.NewOrm()
	sql := ` SELECT * FROM report_send_ths_detail WHERE status =2 AND level=? order by push_time desc,send_id desc`
	err = o.Raw(sql, level).QueryRow(&item)
	return
}

// GetEarliestWaitGtLevelReportSendThs 获取大于该推送等级level（推送级别更低）下待发送的 距离现在最早的一条记录
func GetEarliestWaitGtLevelReportSendThs(level int) (item *ReportSendThsDetail, err error) {
	o := orm.NewOrm()
	sql := ` SELECT * FROM report_send_ths_detail WHERE status = 2 AND level > ? order by push_time asc,send_id asc`
	err = o.Raw(sql, level).QueryRow(&item)
	return
}

// UpdateReportSendThsPushTime 批量修改配置时间
func UpdateReportSendThsPushTime(pushTime time.Time, newTime string) (err error) {
	o := orm.NewOrm()
	//UPDATE comment c set c.time = DATE_ADD(c.time, INTERVAL 7 DAY) ;
	//select date_add(@dt, interval 1 minute); - 加1分钟
	//修改定时推送时间
	sql := `UPDATE report_send_ths_detail 
SET push_time = ` + newTime + ` WHERE status = 2 AND push_time > ? `
	_, err = o.Raw(sql, pushTime).Exec()
	return
}

// UpdateReportSendThsPushTimeByEqGtPushTime 根据发布时间批量修改配置时间（大于等于该发布时间）
func UpdateReportSendThsPushTimeByEqGtPushTime(pushTime time.Time, newTime string) (err error) {
	o := orm.NewOrm()
	//修改定时推送时间
	sql := `UPDATE report_send_ths_detail 
SET push_time = ` + newTime + ` WHERE status = 2 AND push_time >= ? `
	_, err = o.Raw(sql, pushTime).Exec()
	return
}

// GetLatelyIsSendSendThsDetail 获取发送中/发送成功/发送失败的 距离现在最近的一条记录
func GetLatelyIsSendSendThsDetail() (item *ReportSendThsDetail, err error) {
	o := orm.NewOrm()
	//`status` tinyint(1) DEFAULT '0' COMMENT '发送结果，0：待发送，1发送成功，2:等待系统定时发送',
	sql := ` SELECT * FROM report_send_ths_detail WHERE status in (0,1)  order by push_time desc,send_id desc`
	err = o.Raw(sql).QueryRow(&item)
	return
}
