package service

import (
	"fmt"

	"be.ems/src/modules/ne/model"
	"be.ems/src/modules/ne/repository"
)

// 实例化服务层 NeHostCmd 结构体
var NewNeHostCmd = &NeHostCmd{
	neHostCmdRepository: repository.NewNeHostCmd,
}

// NeHostCmd 网元主机命令 服务层处理
type NeHostCmd struct {
	neHostCmdRepository *repository.NeHostCmd // 网元主机命令表
}

// FindByPage 分页查询列表数据
func (r *NeHostCmd) FindByPage(query map[string]string) ([]model.NeHostCmd, int64) {
	return r.neHostCmdRepository.SelectByPage(query)
}

// FindById 通过ID查询
func (r *NeHostCmd) FindById(id int64) model.NeHostCmd {
	if id <= 0 {
		return model.NeHostCmd{}
	}
	neHosts := r.neHostCmdRepository.SelectByIds([]int64{id})
	if len(neHosts) > 0 {
		return neHosts[0]
	}
	return model.NeHostCmd{}
}

// Insert 新增信息
func (r *NeHostCmd) Insert(neHostCmd model.NeHostCmd) int64 {
	return r.neHostCmdRepository.Insert(neHostCmd)
}

// Update 修改信息
func (r *NeHostCmd) Update(neHostCmd model.NeHostCmd) int64 {
	return r.neHostCmdRepository.Update(neHostCmd)
}

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

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

// CheckUniqueGroupTitle 校验同类型组内是否唯一
func (r *NeHostCmd) CheckUniqueGroupTitle(groupId, title, cmdType string, cmdId int64) bool {
	uniqueId := r.neHostCmdRepository.CheckUnique(model.NeHostCmd{
		CmdType: cmdType,
		GroupID: groupId,
		Title:   title,
	})
	if uniqueId == cmdId {
		return true
	}
	return uniqueId == 0
}
