package user

import (
	"eta/eta_mini_ht_api/models"
	"gorm.io/gorm"
	"time"
)

const (
	userSourceClickFlows = "user_source_click_flows"
)

// UserReportClickFlow 用户点击研报流水记录
type UserSourceClickFlow struct {
	ID             int        `gorm:"column:id;primaryKey;autoIncrement:'id'"`
	UserID         int        `gorm:"column:user_id"` // 用户ID\
	Mobile         string     `gorm:"column:mobile"`
	SourceId       int        `gorm:"column:source_id"` // 研报ID
	SourceType     SourceType `gorm:"column:source_type;type:enum('REPORT','VIDEO','AUDIO')"`
	ClickTime      time.Time  `gorm:"column:click_time"` // 点击时间
	IPAddress      string     `gorm:"column:ip_address"` // IP地址
	Location       string     `gorm:"column:location"`   // 地理位置
	Hidden         bool       `gorm:"column:hidden;type:tinyint(1);default:0"`
	Referer        string     `gorm:"column:referer"`         // 来源页面
	AdditionalData string     `gorm:"column:additional_data"` // 额外数据
}

func (v *UserSourceClickFlow) BeforeCreate(tx *gorm.DB) (err error) {
	v.ClickTime = time.Now()
	return
}

func CountSourceClicks(count UserSourceClickFlow) (err error) {
	db := models.Main()
	err = db.Create(&count).Error
	return
}

type CountClickFlowById struct {
	SourceId int `gorm:"column:source_id"`
	Count    int `gorm:"column:count"`
}

func GetTimeDurationReportCountsById(begin string, end string, limit int, sourceType SourceType) (ids []CountClickFlowById, err error) {
	db := models.Main()
	err = db.Table(userSourceClickFlows).Select("source_id,count(*) count").Where("source_id>0 and source_type=? and DATE(click_time) BETWEEN ? AND ? AND hidden =0", sourceType, begin, end).Group("source_id").Order("count desc").Limit(limit).Scan(&ids).Error
	return
}

func HiddenFlows(id int, sourceType SourceType) (err error) {
	db := models.Main()
	err = db.Table(userSourceClickFlows).Where("source_type=? and source_id =?", sourceType, id).Update("hidden", 1).Error
	return
}
