package data_manage

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
)

func ModifyEdbInfoThsDsDataStatus(edbInfoId int64, edbCode string) (err error) {
	o := orm.NewOrmUsingDB("data")
	tableName := `edb_data_ths_ds`
	sql := ` UPDATE %s SET edb_info_id=?,modify_time=NOW() WHERE edb_code=? `
	sql = fmt.Sprintf(sql, tableName)
	_, err = o.Raw(sql, edbInfoId, edbCode).Exec()
	return
}

// GetEdbDataList 获取指标的数据（日期正序返回）
func GetEdbDataThsDsList(endInfoId int, startDate, endDate string) (list []*EdbDataList, err error) {
	tableName := `edb_data_ths_ds`
	var pars []interface{}
	sql := `SELECT edb_data_id,edb_info_id,data_time,value,data_timestamp FROM %s WHERE edb_info_id=? `
	if startDate != "" {
		sql += ` AND data_time>=? `
		pars = append(pars, startDate)
	}
	if endDate != "" {
		sql += ` AND data_time<=? `
		pars = append(pars, endDate)
	}

	sql += ` ORDER BY data_time ASC `
	sql = fmt.Sprintf(sql, tableName)
	o := orm.NewOrmUsingDB("data")
	_, err = o.Raw(sql, endInfoId, pars).QueryRows(&list)
	return
}

func GetTHsDsDataCountByCondition(condition string, pars []interface{}, source int) (count int, err error) {
	o := orm.NewOrmUsingDB("data")
	tableName := `edb_data_ths_ds`
	sql := ` SELECT COUNT(1) AS count FROM %s WHERE 1=1 `
	sql = fmt.Sprintf(sql, tableName)
	if condition != "" {
		sql += condition
	}
	err = o.Raw(sql, pars).QueryRow(&count)
	return
}

func GetThsDsDataListByCondition(condition string, pars []interface{}, source, pageSize, startSize int) (item []*EdbData, err error) {
	o := orm.NewOrmUsingDB("data")
	tableName := `edb_data_ths_ds`
	sql := ` SELECT * FROM %s WHERE 1=1 `
	sql = fmt.Sprintf(sql, tableName)

	if condition != "" {
		sql += condition
	}
	sql += ` ORDER BY data_time DESC `
	sql += ` LIMIT ?,? `
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&item)
	return
}
