package service

import (
	"fmt"

	"be.ems/src/framework/config"
	"be.ems/src/framework/logger"
	"be.ems/src/framework/utils/crypto"
	"be.ems/src/modules/ne/model"
	"be.ems/src/modules/ne/repository"
)

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

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

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

// FindById 通过ID查询
func (r NeHost) FindById(hostId int64) model.NeHost {
	neHost := model.NeHost{}
	if hostId <= 0 {
		return neHost
	}
	neHosts := r.neHostRepository.SelectByIds([]int64{hostId})
	if len(neHosts) > 0 {
		neHost := neHosts[0]
		hostKey := config.Get("aes.hostKey").(string)
		if neHost.Password != "" {
			passwordDe, err := crypto.AESDecryptBase64(neHost.Password, hostKey)
			if err != nil {
				logger.Errorf("select encrypt: %v", err.Error())
				return neHost
			}
			neHost.Password = passwordDe
		}
		if neHost.PrivateKey != "" {
			privateKeyDe, err := crypto.AESDecryptBase64(neHost.PrivateKey, hostKey)
			if err != nil {
				logger.Errorf("select encrypt: %v", err.Error())
				return neHost
			}
			neHost.PrivateKey = privateKeyDe
		}
		if neHost.PassPhrase != "" {
			passPhraseDe, err := crypto.AESDecryptBase64(neHost.PassPhrase, hostKey)
			if err != nil {
				logger.Errorf("select encrypt: %v", err.Error())
				return neHost
			}
			neHost.PassPhrase = passPhraseDe
		}
		return neHost
	}
	return model.NeHost{}
}

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

// Insert 新增信息
func (r NeHost) Insert(neHost model.NeHost) int64 {
	hostKey := config.Get("aes.hostKey").(string)
	if neHost.Password != "" {
		passwordEn, err := crypto.AESEncryptBase64(neHost.Password, hostKey)
		if err != nil {
			logger.Errorf("insert encrypt: %v", err.Error())
			return 0
		}
		neHost.Password = passwordEn
	}
	if neHost.PrivateKey != "" {
		privateKeyEn, err := crypto.AESEncryptBase64(neHost.PrivateKey, hostKey)
		if err != nil {
			logger.Errorf("insert encrypt: %v", err.Error())
			return 0
		}
		neHost.PrivateKey = privateKeyEn
	}
	if neHost.PassPhrase != "" {
		passPhraseEn, err := crypto.AESEncryptBase64(neHost.PassPhrase, hostKey)
		if err != nil {
			logger.Errorf("insert encrypt: %v", err.Error())
			return 0
		}
		neHost.PassPhrase = passPhraseEn
	}
	return r.neHostRepository.Insert(neHost)
}

// Update 修改信息
func (r NeHost) Update(neHost model.NeHost) int64 {
	hostKey := config.Get("aes.hostKey").(string)
	if neHost.Password != "" {
		passwordEn, err := crypto.AESEncryptBase64(neHost.Password, hostKey)
		if err != nil {
			logger.Errorf("update password encrypt: %v", err.Error())
			return 0
		}
		neHost.Password = passwordEn
	}
	if neHost.PrivateKey != "" {
		privateKeyEn, err := crypto.AESEncryptBase64(neHost.PrivateKey, hostKey)
		if err != nil {
			logger.Errorf("update private key encrypt: %v", err.Error())
			return 0
		}
		neHost.PrivateKey = privateKeyEn
	}
	if neHost.PassPhrase != "" {
		passPhraseEn, err := crypto.AESEncryptBase64(neHost.PassPhrase, hostKey)
		if err != nil {
			logger.Errorf("update pass phrase encrypt: %v", err.Error())
			return 0
		}
		neHost.PassPhrase = passPhraseEn
	}
	return r.neHostRepository.Update(neHost)
}

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

	for _, v := range ids {
		if v.GroupID == "1" && checkNeHost {
			// 主机信息操作【%s】失败，禁止操作网元
			return 0, fmt.Errorf("neHost.banNE")
		}
	}

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

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