package repository

import (
	"time"

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

// 实例化数据层 NEState 结构体
var NewNEState = &NEState{}

// NEState 网元状态记录表 数据层处理
type NEState struct{}

// SelectByPage 分页查询集合
func (r NEState) SelectByPage(query model.NEStateQuery) ([]model.NEState, int64) {
	tx := db.DB("").Model(&model.NEState{})
	// 查询条件拼接
	if query.NeType != "" {
		tx = tx.Where("ne_type = ?", query.NeType)
	}
	if query.NeID != "" {
		tx = tx.Where("ne_id = ?", query.NeID)
	}
	if query.BeginTime != "" {
		startTime := query.BeginTime
		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.NEState{}

	// 查询数量为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 := db.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 NEState) SelectByIds(ids []string) []model.NEState {
	rows := []model.NEState{}
	if len(ids) <= 0 {
		return rows
	}
	tx := db.DB("").Model(&model.NEState{})
	// 构建查询条件
	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
}

// DeleteByTime 删除信息
func (r NEState) DeleteByTime(ltTime int64) int64 {
	if ltTime <= 0 {
		return 0
	}
	tx := db.DB("").Where("create_time < ?", ltTime)
	if err := tx.Delete(&model.NEState{}).Error; err != nil {
		logger.Errorf("delete err => %v", err.Error())
		return 0
	}
	return tx.RowsAffected
}

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