package data_stat

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

// EdbInfoUpdateStat 指标更新/刷新 汇总表（数据源明细表）
type EdbInfoUpdateStat 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
	UpdateTime             string  `description:"刷新时间"`
	LatestDate             string  `description:"数据最新日期"`
	LatestValue            float64 `description:"数据最新值"`
	TerminalCode           string  `description:"终端编码，用于配置在机器上"`
	ErDataUpdateDate       string  `description:"本次更新，数据发生变化的最早日期"`
	DataUpdateResult       int     `description:"数据更新结果：1成功，2失败"`
	DataUpdateFailedReason string  `description:"数据未正常更新原因"`
	DataUpdateTime         string  `description:"数据更新时间"`
	UpdateResult           int     `description:"本次刷新操作结果：1成功，2失败"`
	UpdateFailedReason     string  `description:"刷新失败原因"`
	ModifyTime             string  `description:"修改时间"`
	IsAdd                  int8    `description:"是否是当日新增的指标：1是，2否"`
	NeedRefresh            int8    `description:"今日是否需要定时刷新，1需要，0不需要"` //todo 确认该字段
	HasRefresh             int8    `description:"今日是否已刷新，1是，0否"`
}

type EdbInfoUpdateStatItem 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:"起始日期"`
	SysUserId              int     `description:"创建人ID"`
	SysUserRealName        string  `description:"创建人姓名"`
	LatestDate             string  `description:"数据最新日期"`
	CreateTime             string  `description:"创建时间"`
	LatestValue            float64 `description:"数据最新值"`
	TerminalCode           string  `description:"终端编码，用于配置在机器上"`
	ErDataUpdateDate       string  `description:"本次更新，数据发生变化的最早日期"`
	DataUpdateResult       int     `description:"数据更新结果：1成功，2失败"`
	DataUpdateFailedReason string  `description:"数据未正常更新原因"`
	DataUpdateTime         string  `description:"数据更新时间"`
	UpdateResult           int     `description:"本次刷新操作结果：1成功，2失败"`
	UpdateFailedReason     string  `description:"刷新失败原因"`
	UpdateTime             string  `description:"刷新时间"`
	IsAdd                  int8    `description:"是否是当日新增的指标：1是，2否"`
	NeedRefresh            int8    `description:"今日是否需要定时刷新，1需要，0不需要"`
	HasRefresh             int8    `description:"今日是否已刷新，1是，0否"`
}

type EdbInfoUpdateStatItemMore struct {
	EdbInfoUpdateStatItem
	InitSourceName string `description:"初始数据源"`
}

type GetEdbUpdateStatResp struct {
	List   []*EdbInfoUpdateStatItemMore
	Paging *paging.PagingItem
}

func GetEdbUpdateStatByCondition(condition string, pars []interface{}, orderStr string, pageSize, startSize int) (item []*EdbInfoUpdateStat, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := ` SELECT * FROM edb_info_update_stat WHERE 1=1 `
	if condition != "" {
		sql += condition
	}
	if orderStr != "" {
		sql += orderStr
	} else {
		sql += ` ORDER BY create_time DESC, id DESC `
	}

	sql += ` LIMIT ?,? `
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&item)
	return
}

// GetEdbUpdateStatCount
func GetEdbUpdateStatCount(condition string, pars []interface{}) (count int, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := ` SELECT count(*) FROM edb_info_update_stat WHERE 1=1 `
	if condition != "" {
		sql += condition
	}
	err = o.Raw(sql, pars).QueryRow(&count)
	return
}

type EdbUpdateFailedList struct {
	TerminalCode             string `description:"终端编码，用于配置在机器上"`
	SourceUpdateFailedReason string `description:"从终端刷新到数据源的数据未正常刷新原因"`
	Frequency                string `description:"频率"`
	SourceUpdateResult       int    `description:"从终端刷新到数据源的刷新结果：1成功，2失败"`
	Num                      int
}

type GetEdbUpdateFailedResp struct {
	List             []*EdbUpdateFailedList
	Name             string `description:"终端名称"`
	TerminalCode     string `description:"终端编码，用于配置在机器上"`
	DirPath          string `description:"终端存放的文件夹路径"`
	UpdateSuccessNum int    `description:"今日已更新成功指标数"`
	UpdateFailedNum  int    `description:"今日已更新失败指标数"`
}

func GetEdbUpdateStatFailedGroupByCondition(condition string, pars []interface{}) (item []*EdbUpdateFailedList, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT
	terminal_code,
	data_update_result as source_update_result,
	frequency,
	data_update_failed_reason as source_update_failed_reason,
	count(*) as num
FROM
	edb_info_update_stat 
WHERE
	data_update_result != 0`
	if condition != "" {
		sql += condition
	}
	sql += ` GROUP BY
	data_update_result,
	frequency,
	data_update_failed_reason
	ORDER BY count(*) desc`
	_, err = o.Raw(sql, pars).QueryRows(&item)
	return
}
