package models

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

// EdbTerminal 指标终端
type EdbTerminal struct {
	TerminalId   int       `orm:"column(terminal_id);pk"`
	Source       int       `orm:"column(source)" description:"指标来源类型"`
	Name         string    `description:"终端别名"`
	TerminalCode string    `description:"终端编码，用于配置在机器上"`
	ServerUrl    string    `description:"终端地址"`
	Num          int       `description:"终端最大指标数"`
	Status       int       `description:"状态，1启用，2禁用"`
	Value        string    `description:"终端相关的凭证"`
	ModifyTime   time.Time `description:"修改时间"`
	CreateTime   time.Time `description:"创建时间"`
}

// GetEdbTerminalListBySource 根据指标来源类型获取所有的终端列表
func GetEdbTerminalListBySource(source int) (items []*EdbTerminal, err error) {
	o := orm.NewOrm()
	sql := ` SELECT *  FROM edb_terminal WHERE source = ? and status=1 ORDER BY terminal_id ASC `
	_, err = o.Raw(sql, source).QueryRows(&items)
	return
}

// GetEdbTerminalFirstBySource 根据指标来源类型获取配置的首个终端信息
func GetEdbTerminalFirstBySource(source int) (item *EdbTerminal, err error) {
	o := orm.NewOrm()
	sql := ` SELECT *  FROM edb_terminal WHERE source = ? and status=1 ORDER BY terminal_id ASC Limit 1 `
	err = o.Raw(sql, source).QueryRow(&item)
	return
}

type TerminalCodeCountGroup struct {
	TerminalCode string
	Total        int
}

// GetEdbTerminalByCode 根据终端编码获取终端信息
func GetEdbTerminalByCode(terminalCode string) (item *EdbTerminal, err error) {
	o := orm.NewOrm()
	sql := ` SELECT *  FROM edb_terminal WHERE terminal_code = ? `
	err = o.Raw(sql, terminalCode).QueryRow(&item)
	return
}

// GetEdbCountGroupByTerminal 获取终端code分组总数
func GetEdbCountGroupByTerminal(source int) (list []TerminalCodeCountGroup, err error) {
	o := orm.NewOrm()
	sql := `select terminal_code,count(1) total from edb_info where source = ? AND no_update=0 AND terminal_code != "" group by terminal_code; `
	_, err = o.Raw(sql, source).QueryRows(&list)
	return
}

type BaseIndexTerminalCode struct {
	TerminalCode string `description:"终端编码，用于配置在机器上"`
	IndexName    string
}

// GetBaseIndexTerminalCode 获取数据源的终端code
func GetBaseIndexTerminalCode(edbCode, tableName string) (item BaseIndexTerminalCode, err error) {
	o := orm.NewOrm()
	sql := fmt.Sprintf(`select terminal_code, index_name from %s where index_code = ? `, tableName)
	err = o.Raw(sql, edbCode).QueryRow(&item)
	return
}
