package repository

import (
	"time"

	"be.ems/src/framework/datasource"
	"be.ems/src/framework/logger"
	"be.ems/src/modules/network_data/model"
)

// 实例化数据层 NBState 结构体
var NewNBState = &NBState{}

// NBState 基站状态记录表 数据层处理
type NBState struct{}

// SelectByPage 分页查询集合
func (r NBState) SelectByPage(query model.NBStateQuery) ([]model.NBState, int64) {
	tx := datasource.DB("").Model(&model.NBState{})
	// 查询条件拼接
	if query.NeType != "" {
		tx = tx.Where("ne_type = ?", query.NeType)
	}
	if query.NeID != "" {
		tx = tx.Where("ne_id = ?", query.NeID)
	}
	if query.RmUID != "" {
		tx = tx.Where("rm_uid = ?", query.RmUID)
	}
	if query.Status != "" {
		tx = tx.Where("state = ?", query.Status)
	}
	if query.StartTime != "" {
		startTime := query.StartTime
		if len(startTime) == 10 {
			startTime = startTime + "000"
		}
		tx = tx.Where("create_time >= ?", startTime)
	}
	if query.EndTime != "" {
		endTime := query.EndTime
		if len(endTime) == 10 {
			endTime = endTime + "999"
		}
		tx = tx.Where("create_time <= ?", endTime)
	}

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

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

	// 排序
	if query.SortField != "" {
		sortField := query.SortField
		if query.SortOrder == "desc" {
			sortField = sortField + " desc"
		}
		tx = tx.Order(sortField)
	}

	// 查询数据分页
	pageNum, pageSize := datasource.PageNumSize(query.PageNum, query.PageSize)
	tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
	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 NBState) SelectByIds(ids []string) []model.NBState {
	rows := []model.NBState{}
	if len(ids) <= 0 {
		return rows
	}
	tx := datasource.DB("").Model(&model.NBState{})
	// 构建查询条件
	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
}

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

// Insert 新增信息
func (r NBState) Insert(param model.NBState) int64 {
	param.CreateTime = time.Now().UnixMilli()
	// 执行插入
	if err := datasource.DB("").Create(&param).Error; err != nil {
		logger.Errorf("insert err => %v", err.Error())
		return 0
	}
	return param.ID
}
