package data_stat

import (
	"errors"
	"eta/eta_api/models/data_manage"
	"eta/eta_api/utils"
	"fmt"
	"time"
)

// SaveEdbTerminal 保存数据源终端信息
func SaveEdbTerminal(req *data_manage.AddEdbTerminalListReq) (errMsg string, err error) {
	nowTime := time.Now().Local()
	// 更新
	if req.TerminalId > 0 {
		item, e := data_manage.GetEdbTerminalById(req.TerminalId)
		if e != nil {
			if e.Error() == utils.ErrNoRow() {
				errMsg = "终端不存在"
				err = errors.New(errMsg)
				return
			}
			errMsg = "获取终端信息失败"
			err = errors.New("获取终端信息失败, Err:" + e.Error())
			return
		}
		updateCols := make([]string, 0)
		updateCols = append(updateCols, "Source", "Name", "ServerUrl", "DirPath", "Num", "Value", "ModifyTime")
		item.Source = req.Source
		item.Name = req.Name
		item.ServerUrl = req.ServerUrl
		item.DirPath = req.DirPath
		item.Num = req.Num
		item.Value = req.Value
		// todo 状态是否可修改
		//item.Status = 1
		item.ModifyTime = nowTime
		if e := item.Update(updateCols); e != nil {
			errMsg = "更新失败"
			err = errors.New("更新终端失败, Err:" + e.Error())
		}
		return
	}
	terminalCode := createTerminalCode(req.Source, req.Name)
	//item.TerminalCode = req.TerminalCode
	// 新增
	newTerminal := &data_manage.EdbTerminal{
		Source:       req.Source,
		Name:         req.Name,
		TerminalCode: terminalCode,
		ServerUrl:    req.ServerUrl,
		DirPath:      req.DirPath,
		Num:          req.Num,
		Status:       1,
		Value:        req.Value,
		CreateTime:   nowTime,
		ModifyTime:   nowTime,
	}
	if e := newTerminal.Add(); e != nil {
		errMsg = "新增失败"
		err = errors.New("新增终端失败, Err:" + e.Error())
	}
	return
}

// SetEdbTerminalStatus 启用/禁用 终端
func SetEdbTerminalStatus(id int, status int) (errMsg string, err error) {
	nowTime := time.Now().Local()
	// 更新
	item, e := data_manage.GetEdbTerminalById(id)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			errMsg = "终端不存在"
			err = errors.New(errMsg)
			return
		}
		errMsg = "获取终端信息失败"
		err = errors.New("获取终端信息失败, Err:" + e.Error())
		return
	}
	updateCols := make([]string, 0)
	updateCols = append(updateCols, "Status", "ModifyTime")
	item.Status = status
	item.ModifyTime = nowTime
	if e := item.Update(updateCols); e != nil {
		errMsg = "更新失败"
		err = errors.New("更新终端失败, Err:" + e.Error())
	}
	return
}

func createTerminalCode(source int, sourceName string) (terminalCode string) {
	randInt := utils.GetRandNumber(1000)
	terminalCode = utils.MD5(fmt.Sprintf("%d_%s_%s_%d", source, sourceName, time.Now(), randInt))
	return
}
