package data_stat

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

// EdbSourceStat 数据源统计表
type EdbSourceStat struct {
	Id                int       `orm:"column(id);pk"`
	SourceName        string    `description:"来源名称"`
	Source            int       `description:"来源id"`
	TerminalCode      string    `description:"终端编码，用于配置在机器上"`
	EdbNum            int       `description:"指标总数"`
	EdbNewNum         int       `description:"今日新增指标数"`
	EdbDelNum         int       `description:"今日删除指标数"`
	NeedRefreshNum    int       `description:"今日需刷新指标"`
	HasRefreshNum     int       `description:"今日发起刷新任务指标数"`
	UpdateSuccessNum  int       `description:"今日已更新成功指标数"`
	UpdateFailedNum   int       `description:"今日已更新失败指标数"`
	RefreshSuccessNum int       `description:"今日已刷新成功指标数"`
	RefreshFailedNum  int       `description:"今日已刷新失败指标数"`
	CreateTime        time.Time `description:"创建时间"`
	ModifyTime        time.Time `description:"修改时间"`
}

func GetEdbSourceStatByCondition(condition string, pars []interface{}) (item []*EdbSourceStat, err error) {
	o := orm.NewOrm()
	sql := ` SELECT * FROM edb_source_stat WHERE 1=1 `
	if condition != "" {
		sql += condition
	}
	_, err = o.Raw(sql, pars).QueryRows(&item)
	return
}

// Add 新增
func (r *EdbSourceStat) Add(list []*EdbSourceStat) (err error) {
	o := orm.NewOrm()
	_, err = o.InsertMulti(len(list), list)
	return
}

// UpdateEdbSourceStatMulti 批量更新
func UpdateEdbSourceStatMulti(list []*EdbSourceStat) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE edb_source_stat 
SET 
edb_num=?,                              
edb_new_num=?,                          
edb_del_num=?,                          
need_refresh_num=?,                      
has_refresh_num=?,                       
update_success_num=?,                   
update_failed_num=?,          
refresh_success_num=?,                   
refresh_failed_num=?, 
modify_time=?                           
WHERE
	id = ?`
	p, err := o.Raw(sql).Prepare()
	if err != nil {
		return
	}
	defer func() {
		_ = p.Close() // 别忘记关闭 statement
	}()
	for _, v := range list {
		_, err = p.Exec(v.EdbNum, v.EdbNewNum, v.EdbDelNum, v.NeedRefreshNum, v.HasRefreshNum, v.UpdateSuccessNum, v.UpdateFailedNum, v.RefreshSuccessNum, v.RefreshFailedNum, v.ModifyTime, v.Id)
		if err != nil {
			return
		}
	}
	return
}
