package repository

import (
	"fmt"
	"time"

	"be.ems/src/framework/database/db"
	"be.ems/src/framework/logger"
	"be.ems/src/modules/ne/model"
)

// 实例化数据层 NeHost 结构体
var NewNeHost = &NeHost{}

// NeHost 网元主机连接 数据层处理
type NeHost struct{}

// SelectByPage 分页查询集合
func (r NeHost) SelectByPage(query map[string]string) ([]model.NeHost, int64) {
	tx := db.DB("").Model(&model.NeHost{})
	// 查询条件拼接
	if v, ok := query["hostType"]; ok && v != "" {
		tx = tx.Where("host_type = ?", v)
	}
	if v, ok := query["groupId"]; ok && v != "" {
		tx = tx.Where("group_id = ?", v)
	}
	if v, ok := query["title"]; ok && v != "" {
		tx = tx.Where("title like ?", fmt.Sprintf("%s%%", v))
	}

	// 查询结果
	var total int64 = 0
	rows := []model.NeHost{}

	// 查询数量为0直接返回
	if err := tx.Count(&total).Error; err != nil || total <= 0 {
		return rows, total
	}

	// 查询数据分页
	pageNum, pageSize := db.PageNumSize(query["pageNum"], query["pageSize"])
	tx = tx.Limit(pageSize).Offset(pageSize * pageNum)

	// 排序
	if sv, ok := query["sortField"]; ok && sv != "" {
		sortSql := fmt.Sprint(sv)
		if sortSql == "updateTime" {
			sortSql = "update_time"
		}
		if sortSql == "createTime" {
			sortSql = "create_time"
		}
		if ov, ok := query["sortOrder"]; ok && ov != "" {
			if fmt.Sprint(ov) == "desc" {
				sortSql += " desc "
			} else {
				sortSql += " asc "
			}
		}
		tx = tx.Order(sortSql)
	}

	err := tx.Find(&rows).Error
	if err != nil {
		logger.Errorf("query find err => %v", err.Error())
		return rows, total
	}
	return rows, total
}

// SelectByIds 通过ID查询
func (r NeHost) SelectByIds(ids []int64) []model.NeHost {
	rows := []model.NeHost{}
	if len(ids) <= 0 {
		return rows
	}
	tx := db.DB("").Model(&model.NeHost{})
	// 构建查询条件
	tx = tx.Where("id in ?", ids)
	// 查询数据
	if err := tx.Find(&rows).Error; err != nil {
		logger.Errorf("query find err => %v", err.Error())
		return rows
	}
	return rows
}

// Insert 新增信息
func (r NeHost) Insert(param model.NeHost) int64 {
	param.UpdateTime = time.Now().UnixMilli()
	// 根据认证模式清除不必要的信息
	if param.AuthMode == "0" {
		param.PrivateKey = ""
		param.PassPhrase = ""
	}
	if param.AuthMode == "1" {
		param.Password = ""
	}
	if param.AuthMode == "2" {
		param.Password = ""
		param.PrivateKey = ""
		param.PassPhrase = ""
	}
	// 执行插入
	if err := db.DB("").Create(&param).Error; err != nil {
		logger.Errorf("insert err => %v", err.Error())
		return 0
	}
	return param.ID
}

// Update 修改信息
func (r NeHost) Update(param model.NeHost) int64 {
	if param.ID == 0 {
		return 0
	}
	// 根据认证模式清除不必要的信息
	if param.AuthMode == "0" {
		param.PrivateKey = ""
		param.PassPhrase = ""
	}
	if param.AuthMode == "1" {
		param.Password = ""
	}
	if param.AuthMode == "2" {
		param.Password = ""
		param.PrivateKey = ""
		param.PassPhrase = ""
	}
	param.UpdateTime = time.Now().UnixMilli()
	tx := db.DB("").Model(&model.NeHost{})
	// 构建查询条件
	tx = tx.Where("id = ?", param.ID)
	tx = tx.Omit("id")
	// 执行更新
	if err := tx.Updates(param).Error; err != nil {
		logger.Errorf("update err => %v", err.Error())
		return 0
	}
	return tx.RowsAffected
}

// DeleteByIds 批量删除信息
func (r NeHost) DeleteByIds(ids []int64) int64 {
	if len(ids) <= 0 {
		return 0
	}
	tx := db.DB("").Where("id in ?", ids)
	if err := tx.Delete(&model.NeHost{}).Error; err != nil {
		logger.Errorf("delete err => %v", err.Error())
		return 0
	}
	return tx.RowsAffected
}

// CheckUnique 检查信息是否唯一 返回数据ID
func (r NeHost) CheckUnique(param model.NeHost) int64 {
	tx := db.DB("").Model(&model.NeHost{})
	// 查询条件拼接
	if param.HostType != "" {
		tx = tx.Where("host_type = ?", param.HostType)
	}
	if param.GroupID != "" {
		tx = tx.Where("group_id = ?", param.GroupID)
	}
	if param.Title != "" {
		tx = tx.Where("title = ?", param.Title)
	}
	// 查询数据
	var id int64 = 0
	if err := tx.Select("id").Limit(1).Find(&id).Error; err != nil {
		logger.Errorf("query find err => %v", err.Error())
		return id
	}
	return id
}
