package service

import (
	"fmt"

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

// 实例化服务层 NeSoftwareImpl 结构体
var NewNeSoftwareImpl = &NeSoftwareImpl{
	neSoftwareRepository: repository.NewNeSoftwareImpl,
}

// NeSoftwareImpl 网元软件包信息 服务层处理
type NeSoftwareImpl struct {
	// 网元软件包信息
	neSoftwareRepository repository.INeSoftware
}

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

// SelectConfigList 查询列表
func (r *NeSoftwareImpl) SelectList(neSoftware model.NeSoftware) []model.NeSoftware {
	return r.neSoftwareRepository.SelectList(neSoftware)
}

// SelectByIds 通过ID查询
func (r *NeSoftwareImpl) SelectById(id string) model.NeSoftware {
	if id == "" {
		return model.NeSoftware{}
	}
	neHosts := r.neSoftwareRepository.SelectByIds([]string{id})
	if len(neHosts) > 0 {
		return neHosts[0]
	}
	return model.NeSoftware{}
}

// Insert 新增信息
func (r *NeSoftwareImpl) Insert(neSoftware model.NeSoftware) string {
	return r.neSoftwareRepository.Insert(neSoftware)
}

// Update 修改信息
func (r *NeSoftwareImpl) Update(neSoftware model.NeSoftware) int64 {
	return r.neSoftwareRepository.Update(neSoftware)
}

// DeleteByIds 批量删除信息
func (r *NeSoftwareImpl) DeleteByIds(ids []string) (int64, error) {
	// 检查是否存在
	rowIds := r.neSoftwareRepository.SelectByIds(ids)
	if len(rowIds) <= 0 {
		return 0, fmt.Errorf("neSoftware.noData")
	}

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

// SelectByVersionAndPath 通过文件版本和路径查询
func (r *NeSoftwareImpl) SelectByVersionAndPath(version, path string) model.NeSoftware {
	neSoftwares := r.neSoftwareRepository.SelectList(model.NeSoftware{
		Version: version,
		Path:    path,
	})
	if len(neSoftwares) > 0 {
		return neSoftwares[0]
	}
	return model.NeSoftware{}
}

// CheckUniqueTypeAndFileNameAndVersion 校验网元类型和文件名版本是否唯一
func (r *NeSoftwareImpl) CheckUniqueTypeAndFileNameAndVersion(neType, fileName, version, id string) bool {
	uniqueId := r.neSoftwareRepository.CheckUniqueTypeAndFileNameAndVersion(model.NeSoftware{
		NeType:   neType,
		FileName: fileName,
		Version:  version,
	})
	if uniqueId == id {
		return true
	}
	return uniqueId == ""
}

// Install 安装软件包
func (r *NeSoftwareImpl) Install(neSoftware model.NeSoftware) (string, error) {
	return "", nil
}
