package service

import (
	"encoding/json"
	"fmt"
	"time"

	"nms_nbi/src/framework/constants/cachekey"
	"nms_nbi/src/framework/redis"
	"nms_nbi/src/modules/network_data/model"
	"nms_nbi/src/modules/network_data/repository"
)

// 实例化数据层 PerfKPIImpl 结构体
var NewPerfKPIImpl = &PerfKPIImpl{
	perfKPIRepository: repository.NewPerfKPIImpl,
}

// PerfKPIImpl 性能统计 服务层处理
type PerfKPIImpl struct {
	// 性能统计数据信息
	perfKPIRepository repository.IPerfKPI
}

// SelectGoldKPI 通过网元指标数据信息
func (r *PerfKPIImpl) SelectGoldKPI(query model.GoldKPIQuery) []map[string]any {
	// 获取数据指标id
	var kpiIds []string
	kpiTitles := r.perfKPIRepository.SelectGoldKPITitle(query.NeType)
	for _, kpiId := range kpiTitles {
		kpiIds = append(kpiIds, kpiId.KPIID)
	}

	data := r.perfKPIRepository.SelectGoldKPI(query, kpiIds)
	if data == nil {
		return []map[string]any{}
	}
	return data
}

// SelectGoldKPITitle 网元对应的指标名称
func (r *PerfKPIImpl) SelectGoldKPITitle(neType string) []model.GoldKPITitle {
	return r.perfKPIRepository.SelectGoldKPITitle(neType)
}

// SelectUPFTotalFlow 查询UPF总流量 N3上行 N6下行
func (r *PerfKPIImpl) SelectUPFTotalFlow(neType, rmUID string, day int) map[string]any {
	// 获取当前日期
	now := time.Now()
	endDate := now.Format("2006-01-02")
	// 将当前日期前几天数
	afterDays := now.AddDate(0, 0, -day)
	startDate := afterDays.Format("2006-01-02")

	var info map[string]any

	// 读取缓存数据 小于2分钟重新缓存
	key := fmt.Sprintf("%sUPF:totalFlow:%s_%d", cachekey.NE_DATA_KEY, rmUID, day)
	infoStr, _ := redis.Get("", key)
	if infoStr != "" {
		json.Unmarshal([]byte(infoStr), &info)
		expireSecond, _ := redis.GetExpire("", key)
		expireMinute := (time.Duration(int64(expireSecond)) * time.Second)
		if expireMinute > 2*time.Minute {
			return info
		}
	}

	info = r.perfKPIRepository.SelectUPFTotalFlow(neType, rmUID, startDate, endDate)

	// 保存到缓存
	infoJSON, _ := json.Marshal(info)
	redis.SetByExpire("", key, string(infoJSON), time.Duration(10)*time.Minute)

	return info
}
