package data_stat

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

// EdbInfoUpdateLog 指标更新/刷新日志列表
type EdbInfoUpdateLog struct {
	Id                     uint64    `orm:"column(id);pk"`
	EdbInfoId              int       `description:"指标ID"`
	SourceName             string    `description:"来源名称"`
	Source                 int       `description:"来源id"`
	EdbCode                string    `description:"指标编码"`
	EdbName                string    `description:"指标名称"`
	EdbNameSource          string    `description:"指标名称来源"`
	Frequency              string    `description:"频率"`
	Unit                   string    `description:"单位"`
	StartDate              string    `description:"起始日期"`
	EndDate                string    `description:"终止日期"`
	SysUserId              int       `description:"创建人ID"`
	SysUserRealName        string    `description:"创建人姓名"`
	UniqueCode             string    `description:"指标唯一编码"`
	EdbCreateTime          time.Time `description:"指标创建时间"`
	EdbModifyTime          time.Time `description:"指标修改时间"`
	CreateTime             time.Time `description:"创建时间"`
	UpdateSysUserId        int       `description:"变更人ID"`
	UpdateSysUserRealName  string    `description:"变更人姓名"`
	LatestDate             string    `description:"数据最新日期"`
	LatestValue            float64   `description:"数据最新值"`
	TerminalCode           string    `description:"终端编码，用于配置在机器上"`
	ErDataUpdateDate       string    `description:"本次更新，数据发生变化的最早日期"`
	UpdateResult           int       `description:"本次刷新操作结果：1成功，2失败"`
	UpdateFailedReason     string    `description:"刷新失败原因"`
	DataUpdateResult       int       `description:"数据更新结果：1成功，2失败"`
	DataUpdateFailedReason string    `description:"数据未正常更新原因"`
	DataUpdateTime         string    `description:"数据更新时间"`
	IsSourceRefresh        int       `description:"是否为终端刷新到数据源的刷新操作：0否，1是"`
}

func AddEdbUpdateLog(item *EdbInfoUpdateLog) (lastId int64, err error) {
	o := orm.NewOrm()
	lastId, err = o.Insert(item)
	return
}

// GetEdbUpdateLogByCondition 获取指标更新记录
func GetEdbUpdateLogByCondition(condition string, pars []interface{}) (item []*EdbInfoUpdateLog, err error) {
	o := orm.NewOrm()
	sql := ` SELECT * FROM edb_info_update_log WHERE 1=1 `
	if condition != "" {
		sql += condition
	}
	_, err = o.Raw(sql, pars).QueryRows(&item)
	return
}

// GetEdbUpdateSourceLogByCreateDate 获取指标终端更新记录
func GetEdbUpdateSourceLogByCreateDate(source int, startDate, endDate string) (item []*EdbInfoUpdateLog, err error) {
	o := orm.NewOrm()
	sql := ` SELECT * FROM edb_info_update_log WHERE source = ? and create_time >= ? and create_time < ? and is_source_refresh =1 order by data_update_result asc, id desc`
	_, err = o.Raw(sql, source, startDate, endDate).QueryRows(&item)
	return
}
