package repository

import (
	"fmt"
	"time"

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

// 实例化数据层 TraceTaskHlr 结构体
var NewTraceTaskHlr = &TraceTaskHlr{}

// TraceTaskHlr 跟踪_任务给HRL网元 数据层处理
type TraceTaskHlr struct{}

// SelectByPage 分页查询集合
func (r TraceTaskHlr) SelectByPage(query model.TraceTaskHlrQuery) ([]model.TraceTaskHlr, int64) {
	tx := db.DB("").Model(&model.TraceTaskHlr{})
	// 查询条件拼接
	if query.IMSI != "" {
		tx = tx.Where("imsi like ?", fmt.Sprintf("%s%%", query.IMSI))
	}
	if query.MSISDN != "" {
		tx = tx.Where("msisdn like ?", fmt.Sprintf("%s%%", query.MSISDN))
	}
	if query.StartTime != "" && len(query.StartTime) == 13 {
		tx = tx.Where("start_time >= ?", query.StartTime)
	}
	if query.EndTime != "" && len(query.EndTime) == 13 {
		tx = tx.Where("end_time >= ?", query.StartTime)
	}

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

	// 查询数量为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 query.SortField != "" {
		sortSql := query.SortField
		if query.SortOrder != "" {
			if query.SortOrder == "desc" {
				sortSql += " desc "
			} else {
				sortSql += " asc "
			}
		}
		tx.Order(fmt.Sprintf("id desc, %s ", 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 TraceTaskHlr) SelectByIds(ids []int64) []model.TraceTaskHlr {
	rows := []model.TraceTaskHlr{}
	if len(ids) <= 0 {
		return rows
	}
	tx := db.DB("").Model(&model.TraceTaskHlr{})
	// 构建查询条件
	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 TraceTaskHlr) Insert(param model.TraceTaskHlr) int64 {
	if param.CreateBy != "" {
		ms := time.Now().UnixMilli()
		param.UpdateBy = param.CreateBy
		param.UpdateTime = ms
		param.CreateTime = ms
	}
	// 执行插入
	if err := db.DB("").Create(&param).Error; err != nil {
		logger.Errorf("insert err => %v", err.Error())
		return 0
	}
	return param.ID
}

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

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

// LastID 最后一条ID
func (r TraceTaskHlr) LastID() int64 {
	tx := db.DB("").Model(&model.TraceTaskHlr{})
	// 查询数据
	var id int64 = 0
	if err := tx.Select("id").Order("id DESC").Limit(1).Find(&id).Error; err != nil {
		logger.Errorf("query find err => %v", err.Error())
		return id
	}
	return id
}
