package services

import (
	"errors"
	"eta/eta_index_lib/models"
	"eta/eta_index_lib/utils"
)

// GetTerminal 获取终端信息
func GetTerminal(source int, oldTerminalCode string) (edbTerminal *models.EdbTerminal, err error) {
	if source == utils.DATA_SOURCE_WIND && oldTerminalCode == "" {
		tmpConfig := new(models.EdbConfig)
		tmpConfig, err = models.GetConfigDetailByCode("wind_terminal_code")
		if err != nil && err.Error() != utils.ErrNoRow() {
			err = errors.New("获取配置的wind地址失败，err:" + err.Error())
			return
		}
		err = nil
		if tmpConfig != nil {
			oldTerminalCode = tmpConfig.ConfigValue
			//return
		}
	}
	if oldTerminalCode != "" {
		edbTerminal, err = models.GetEdbTerminalByCode(oldTerminalCode)
		if err != nil {
			return
		}
		return
	}

	// 配置中没有的话，那么就从分组获取,
	list, err := models.GetEdbCountGroupByTerminal(source)
	if err != nil {
		return
	}
	//windUrlNum := 0

	//获取对应的配置url
	terminalNumMap := make(map[string]int)
	for _, v := range list {
		terminalNumMap[v.TerminalCode] = v.Total
	}

	terminalList, err := models.GetEdbTerminalListBySource(source)
	if err != nil {
		return
	}
	if len(terminalList) == 0 {
		err = errors.New("终端地址未配置")
		return
	}
	num := 0
	for _, v := range terminalList {
		tmpNum := terminalNumMap[v.TerminalCode]
		if edbTerminal == nil {
			edbTerminal = v
			num = tmpNum
		} else if tmpNum < num {
			edbTerminal = v
			num = tmpNum
		}
	}
	if edbTerminal == nil {
		err = errors.New("获取配置的终端地址失败")
		return
	}
	/*if edbTerminal != nil {
		windUrl = edbTerminal.ServerUrl
		terminalCode = edbTerminal.TerminalCode
	}*/
	return
}

func GetFirstTerminal(source int, oldTerminalCode string) (edbTerminal *models.EdbTerminal, err error) {
	if oldTerminalCode != "" {
		edbTerminal, err = models.GetEdbTerminalByCode(oldTerminalCode)
		if err != nil {
			return
		}
		return
	}

	edbTerminal, err = models.GetEdbTerminalFirstBySource(source)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			err = errors.New("终端未配置")
			return
		}
		return
	}
	return
}
