package stl

import (
	"eta/eta_api/utils"
	"time"

	"github.com/beego/beego/v2/client/orm"
)

type EdbDataCalculateStl struct {
	EdbDataId     int       `orm:"pk"`
	EdbInfoId     int       `description:"指标id"`
	EdbCode       string    `description:"指标编码"`
	DataTime      time.Time `description:"数据时间"`
	Value         float64   `description:"数据值"`
	CreateTime    time.Time `description:"创建时间"`
	ModifyTime    time.Time `description:"修改时间"`
	DataTimestamp int64     `description:"数据时间戳"`
}

func GetEdbDataCalculateStlByEdbCode(edbCode string) (items []*EdbDataCalculateStl, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT * FROM edb_data_calculate_stl WHERE edb_code =? ORDER BY data_time`
	_, err = o.Raw(sql, edbCode).QueryRows(&items)
	return
}

func DeleteAndInsertEdbDataCalculateStl(edbCode string, dataList []*EdbDataCalculateStl) (err error) {
	tx, err := orm.NewOrmUsingDB("data").Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	sql := `DELETE FROM edb_data_calculate_stl WHERE edb_code =?`
	_, err = tx.Raw(sql, edbCode).Exec()
	if err != nil {
		return
	}
	_, err = tx.InsertMulti(utils.MultiAddNum, dataList)
	return
}

func (m *EdbDataCalculateStl) GetMaxId() (maxId int, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT max(edb_data_id) id FROM edb_data_calculate_stl limit 1`
	err = o.Raw(sql).QueryRow(&maxId)
	return
}

func (m *EdbDataCalculateStl) BatchInsert(dataList []*EdbDataCalculateStl) (err error) {
	o := orm.NewOrmUsingDB("data")
	_, err = o.InsertMulti(utils.MultiAddNum, dataList)
	return
}