package data_manage

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

func GetEdbDataCalculateByCodeAndDate(edbCode string, startDate string) (count int, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := ` SELECT COUNT(1) AS count FROM edb_data_calculate WHERE edb_code=? AND data_time=? `
	err = o.Raw(sql, edbCode, startDate).QueryRow(&count)
	return
}

func ModifyEdbDataCalculate(edbInfoId int64, dataTime string, value float64) (err error) {
	o := orm.NewOrmUsingDB("data")
	sql := ` UPDATE edb_data_calculate SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
	_, err = o.Raw(sql, value, edbInfoId, dataTime).Exec()
	return
}

func AddEdbDataCalculateBySql(sqlStr string) (err error) {
	o := orm.NewOrmUsingDB("data")
	_, err = o.Raw(sqlStr).Exec()
	return
}

// DeleteEdbDataCalculateBySql 根据删除sql删除指标数据
func DeleteEdbDataCalculateBySql(deleteStr string, edbInfoId int) (err error) {
	o := orm.NewOrmUsingDB("data")
	_, err = o.Raw(deleteStr, edbInfoId).Exec()
	return
}

type EdbInfoCalculateDetail struct {
	EdbInfoCalculateId int       `orm:"column(edb_info_calculate_id);pk"`
	EdbInfoId          int       `description:"指标id"`
	EdbCode            string    `description:"指标编码"`
	FromEdbInfoId      int       `description:"计算指标id"`
	FromEdbCode        string    `description:"计算指标编码"`
	FromEdbName        string    `description:"计算指标名称"`
	FromSource         int       `description:"计算指标来源"`
	FromSourceName     string    `description:"计算指标来源名称"`
	FromTag            string    `description:"来源指标标签"`
	Sort               int       `description:"计算指标名称排序"`
	CreateTime         time.Time `description:"创建时间"`
	ModifyTime         time.Time `description:"修改时间"`
	StartDate          string    `description:"开始日期"`
	EndDate            string    `description:"结束日期"`
}

func GetEdbInfoCalculateDetail(edbInfoId int) (list []*EdbInfoCalculateDetail, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := ` SELECT a.*,b.start_date,b.end_date FROM edb_info_calculate_mapping AS a
			INNER JOIN edb_info AS b ON a.from_edb_info_id=b.edb_info_id
			WHERE a.edb_info_id=? ORDER BY sort ASC `
	_, err = o.Raw(sql, edbInfoId).QueryRows(&list)
	return
}

func GetEdbInfoCalculateMap(edbInfoId, source int) (list []*EdbInfoCalculateDetail, err error) {
	o := orm.NewOrmUsingDB("data")

	calculateTableName := GetEdbInfoCalculateTableName(source)
	sql := ` SELECT a.*,b.start_date,b.end_date,b.edb_type FROM %s AS a
			INNER JOIN edb_info AS b ON a.from_edb_info_id=b.edb_info_id
			WHERE a.edb_info_id=? ORDER BY sort ASC `
	sql = fmt.Sprintf(sql, calculateTableName)
	_, err = o.Raw(sql, edbInfoId).QueryRows(&list)
	return
}