package repository

import (
	"fmt"
	"time"

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

// 实例化数据层 NeConfigBackup 结构体
var NewNeConfigBackup = &NeConfigBackup{}

// NeConfigBackup 网元配置文件备份记录 数据层处理
type NeConfigBackup struct{}

// SelectByPage 分页查询集合
func (r NeConfigBackup) SelectByPage(query map[string]string) ([]model.NeConfigBackup, int64) {
	tx := db.DB("").Model(&model.NeConfigBackup{})
	// 查询条件拼接
	if v, ok := query["neType"]; ok && v != "" {
		tx = tx.Where("ne_type = ?", v)
	}
	if v, ok := query["neId"]; ok && v != "" {
		tx = tx.Where("ne_id = ?", v)
	}
	if v, ok := query["name"]; ok && v != "" {
		tx = tx.Where("name like ?", fmt.Sprintf("%%%s%%", v))
	}

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

	// 查询数量为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)
	err := tx.Order("id desc").Find(&rows).Error
	if err != nil {
		logger.Errorf("query find err => %v", err.Error())
		return rows, total
	}
	return rows, total
}

// SelectByIds 通过ID查询信息
func (r NeConfigBackup) SelectByIds(ids []int64) []model.NeConfigBackup {
	rows := []model.NeConfigBackup{}
	if len(ids) <= 0 {
		return rows
	}
	tx := db.DB("").Model(&model.NeConfigBackup{})
	// 构建查询条件
	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 新增信息 返回新增数据ID
func (r NeConfigBackup) Insert(item model.NeConfigBackup) int64 {
	if item.CreateBy != "" {
		ms := time.Now().UnixMilli()
		item.UpdateBy = item.CreateBy
		item.UpdateTime = ms
		item.CreateTime = ms
	}
	// 执行插入
	if err := db.DB("").Create(&item).Error; err != nil {
		logger.Errorf("insert err => %v", err.Error())
		return 0
	}
	return item.ID
}

// Update 修改信息 返回受影响行数
func (r NeConfigBackup) Update(item model.NeConfigBackup) int64 {
	if item.ID <= 0 {
		return 0
	}
	if item.UpdateBy != "" {
		item.UpdateTime = time.Now().UnixMilli()
	}
	tx := db.DB("").Model(&model.NeConfigBackup{})
	// 构建查询条件
	tx = tx.Where("id = ?", item.ID)
	tx = tx.Omit("id", "create_by", "create_time")
	// 执行更新
	if err := tx.Updates(item).Error; err != nil {
		logger.Errorf("update err => %v", err.Error())
		return 0
	}
	return tx.RowsAffected
}

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