package service

import (
	"fmt"

	"nms_nbi/src/modules/network_element/model"
	"nms_nbi/src/modules/network_element/repository"
)

// 实例化服务层 NeHostImpl 结构体
var NewNeHostImpl = &NeHostImpl{
	neHostRepository: repository.NewNeHostImpl,
}

// NeHostImpl 网元主机连接 服务层处理
type NeHostImpl struct {
	// 网元主机连接表
	neHostRepository repository.INeHost
}

// SelectNeHostPage 分页查询列表数据
func (r *NeHostImpl) SelectPage(query map[string]any) map[string]any {
	return r.neHostRepository.SelectPage(query)
}

// SelectConfigList 查询列表
func (r *NeHostImpl) SelectList(neHost model.NeHost) []model.NeHost {
	return r.neHostRepository.SelectList(neHost)
}

// SelectByIds 通过ID查询
func (r *NeHostImpl) SelectById(hostId string) model.NeHost {
	if hostId == "" {
		return model.NeHost{}
	}
	neHosts := r.neHostRepository.SelectByIds([]string{hostId})
	if len(neHosts) > 0 {
		return neHosts[0]
	}
	return model.NeHost{}
}

// Insert 批量添加
func (r *NeHostImpl) Inserts(neHosts []model.NeHost) int64 {
	var num int64 = 0
	for _, v := range neHosts {
		hostId := r.neHostRepository.Insert(v)
		if hostId != "" {
			num += 1
		}
	}
	return num
}

// Insert 新增信息
func (r *NeHostImpl) Insert(neHost model.NeHost) string {
	return r.neHostRepository.Insert(neHost)
}

// Update 修改信息
func (r *NeHostImpl) Update(neHost model.NeHost) int64 {
	return r.neHostRepository.Update(neHost)
}

// DeleteByIds 批量删除网元主机连接信息
func (r *NeHostImpl) DeleteByIds(hostIds []string) (int64, error) {
	// 检查是否存在
	ids := r.neHostRepository.SelectByIds(hostIds)
	if len(ids) <= 0 {
		return 0, fmt.Errorf("neHost.noData")
	}

	if len(ids) == len(hostIds) {
		rows := r.neHostRepository.DeleteByIds(hostIds)
		return rows, nil
	}
	// 删除信息失败！
	return 0, fmt.Errorf("delete fail")
}

// CheckUniqueHostTitle 校验分组组和主机名称是否唯一
func (r *NeHostImpl) CheckUniqueHostTitle(groupId, title, hostType, hostId string) bool {
	uniqueId := r.neHostRepository.CheckUniqueNeHost(model.NeHost{
		HostType: hostType,
		GroupID:  groupId,
		Title:    title,
	})
	if uniqueId == hostId {
		return true
	}
	return uniqueId == ""
}
