package eta

import (
	logger "eta/eta_mini_ht_api/common/component/log"
	"eta/eta_mini_ht_api/models"
	"strings"
	"time"
)

const (
	colunms      = "id,author,abstract,title,publish_time,state,"
	detailColumn = "id,author,abstract,title,publish_time,content,collaborate_type,report_layout,video_url,video_name,video_play_seconds,head_resource_id,end_resource_id,has_chapter,need_splice,state"
	Published    = 2
	Passed       = 6

	limit                                  = 500
	TlbChartPermissionSearchKeyWordMapping = "chart_permission_search_key_word_mapping"
)

var (
	classifyIds = []string{"classify_id_third", "classify_id_second", "classify_id_first"}
)

func (ETAReport) TableName() string {
	return "report"
}

type ETAReport struct {
	ID               int       `gorm:"primary_key;auto_increment"`
	ClassifyID       int       `gorm:"_"`
	ClassifyIDFirst  int       `gorm:"column:classify_id_first;default:0"`
	ClassifyIDSecond int       `gorm:"column:classify_id_second;default:0"`
	ClassifyIDThird  int       `gorm:"column:classify_id_third;default:0"`
	Title            string    `gorm:"column:title;size:125;"`
	Abstract         string    `gorm:"column:abstract;size:255;"`
	Author           string    `gorm:"column:author;size:50;"`
	PublishTime      time.Time `gorm:"column:publish_time"`
	Content          string    `gorm:"column:content"`
	CollaborateType  int       `gorm:"column:collaborate_type"`
	ReportLayout     int       `gorm:"column:report_layout"`
	VideoUrl         string    `gorm:"column:video_url"`
	VideoName        string    `gorm:"column:video_name"`
	VideoPlaySeconds string    `gorm:"column:video_play_seconds"`
	HeadResourceId   int       `gorm:"column:head_resource_id"`
	EndResourceId    int       `gorm:"column:end_resource_id"`
	HasChapter       bool      `gorm:"column:has_chapter"`
	NeedSplice       bool      `gorm:"column:need_splice"`
	State            int       `gorm:"column:state"`
}

//type ReportClassify struct {
//	ClassifyID int `gorm:"column:classify_id" json:"classify_id"`
//	ReportPermission
//}

type ReportPermission struct {
	ChartPermissionID int `gorm:"primaryKey;autoIncrement;column:chart_permission_id;comment:主键"`
	ParentID          int `gorm:"size:11;default:0;column:parent_id;comment:父级权限id"`
}

func GetETAReports(id int) (reports []ETAReport, err error) {
	err = models.ETA().Table("report").Select(colunms+strings.Join(classifyIds, ",")).Where("state =? or state=?", Published, Passed).Where("id > ?", id).Order("id asc").Limit(limit).Find(&reports).Error
	if reports != nil {
		for i := 0; i < len(reports); i++ {
			setClassifyIdValue(&reports[i])
		}
	}
	return
}

func GetUpdateETAReports() (reports []ETAReport, err error) {
	duration := time.Now().Add(-30 * time.Second)
	modifyTime := duration.Format(time.DateTime)
	err = models.ETA().Table("report").Select(colunms+strings.Join(classifyIds, ",")).Where("modify_time >=?", modifyTime).Order("id asc").Find(&reports).Error
	if err != nil {
		logger.Error("同步eta研报数据失败:%v", err)
	}
	if reports != nil {
		for i := 0; i < len(reports); i++ {
			//var date time.Time
			//date, err = time.Parse(time.DateTime, reports[i].PublishTime)
			//if err != nil {
			//	logger.Error("时间转换错误:%v", err)
			//} else {
			//	reports[i].PublishedTime = date
			//}
			setClassifyIdValue(&reports[i])
		}
	}
	return
}

func GetETAReportById(id int) (report ETAReport, err error) {
	err = models.ETA().Table("report").Select(detailColumn).Where("id = ?", id).Where("state =? or state=?", Published, Passed).First(&report).Error
	if err != nil {
		return
	}
	//var date time.Time
	//date, err = time.Parse(time.DateTime, report.PublishTime)
	//if err != nil {
	//	logger.Error("时间转换错误:%v", err)
	//	err = nil
	//} else {
	//	report.PublishedTime = date
	//}
	return
}
func DoSql(sql string, result interface{}, values ...interface{}) (err error) {
	db := models.ETA()
	return db.Raw(sql, values...).Scan(&result).Error
}
func GetReportClassifyById(id int) (classifyId int, err error) {
	db := models.ETA()
	err = db.Table("report").
		Select("COALESCE(NULLIF(classify_id_third,0),NULLIF(classify_id_second,0),classify_id_first) classify_id").
		Where("id =?", id).Scan(&classifyId).Error
	return
}

func GetETAReportIdsByClassifyIds(classifyIds []int) (reportIds []int, err error) {
	db := models.ETA()
	err = db.Model(&ETAReport{}).Select("DISTINCT id").Where("COALESCE(NULLIF(classify_id_third,0),NULLIF(classify_id_second,0),classify_id_first) in (?)", classifyIds).Scan(&reportIds).Error
	return
}
func setClassifyIdValue(report *ETAReport) {
	if report.ClassifyIDThird > 0 {
		report.ClassifyID = report.ClassifyIDThird
		return
	}
	if report.ClassifyIDSecond > 0 {
		report.ClassifyID = report.ClassifyIDSecond
		return
	}
	report.ClassifyID = report.ClassifyIDFirst
}
