package repository

import (
	"fmt"
	"strings"

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

// 实例化数据层 TraceData 结构体
var NewTraceData = &TraceData{}

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

// SelectByPage 分页查询集合
func (r TraceData) SelectByPage(query map[string]string) ([]model.TraceData, int64) {
	tx := db.DB("").Model(&model.TraceData{})
	// 查询条件拼接
	if v, ok := query["traceId"]; ok && v != "" {
		tx = tx.Where("trace_id = ?", v)
	}
	if v, ok := query["startTime"]; ok && v != "" {
		if len(v) == 10 {
			v = fmt.Sprintf("%s000", v)
			tx = tx.Where("timestamp >= ?", v)
		} else if len(v) == 13 {
			tx = tx.Where("timestamp >= ?", v)
		}
	}
	if v, ok := query["endTime"]; ok && v != "" {
		if len(v) == 10 {
			v = fmt.Sprintf("%s999", v)
			tx = tx.Where("timestamp <= ?", v)
		} else if len(v) == 13 {
			tx = tx.Where("timestamp <= ?", v)
		}
	}

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

	// 查询数量为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)
	// 排序
	sortByStr, sortOk := query["sortBy"]
	sortOrderStr, orderOk := query["sortOrder"]
	if sortOk && sortByStr != "" && orderOk && sortOrderStr != "" {
		sortByArr := strings.Split(sortByStr, ",")
		sortOrderArr := strings.Split(sortOrderStr, ",")
		for i := range sortByArr {
			sortBy := sortByArr[i]
			sortOrder := sortOrderArr[i]
			// 排序字段
			sort := "id"
			if sortBy == "timestamp" {
				sort = "timestamp"
			}
			// 排序方式
			order := "ASC"
			if strings.HasPrefix(sortOrder, "asc") {
				order = "ASC"
			} else if strings.HasPrefix(sortOrder, "desc") {
				order = "DESC"
			}
			tx = tx.Order(fmt.Sprintf("%s %s", sort, order))
		}
	} else {
		tx = tx.Order("id desc")
	}
	err := tx.Omit("raw_msg").Find(&rows).Error
	if err != nil {
		logger.Errorf("query find err => %v", err.Error())
		return rows, total
	}
	return rows, total
}

// SelectByIds 通过ID查询信息
func (r TraceData) SelectByIds(ids []int64) []model.TraceData {
	rows := []model.TraceData{}
	if len(ids) <= 0 {
		return rows
	}
	tx := db.DB("").Model(&model.TraceData{})
	// 构建查询条件
	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 TraceData) Insert(param model.TraceData) int64 {
	// 执行插入
	if err := db.DB("").Create(&param).Error; err != nil {
		logger.Errorf("insert err => %v", err.Error())
		return 0
	}
	return param.ID
}

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

// DeleteByTraceId 删除跟踪任务数据 返回受影响行数
func (r TraceData) DeleteByTraceId(traceId string) int64 {
	if traceId == "" || traceId == "<nil>" {
		return 0
	}
	tx := db.DB("").Where("trace_id = ?", traceId)
	if err := tx.Delete(&model.TraceData{}).Error; err != nil {
		logger.Errorf("delete err => %v", err.Error())
		return 0
	}
	return tx.RowsAffected
}
