package service

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

	"be.ems/src/framework/constants/cachekey"
	"be.ems/src/framework/redis"
	"be.ems/src/modules/network_data/model"
	"be.ems/src/modules/network_data/repository"
)

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

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

// SelectGoldKPI 通过网元指标数据信息
func (r *PerfKPI) 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 *PerfKPI) SelectGoldKPITitle(neType string) []model.GoldKPITitle {
	return r.perfKPIRepository.SelectGoldKPITitle(neType)
}

// SelectUPFTotalFlow 查询UPF总流量 N3上行 N6下行
func (r *PerfKPI) SelectUPFTotalFlow(neType, rmUID string, day int) map[string]any {
	now := time.Now()
	// 获取当前日期
	endDate := fmt.Sprint(now.UnixMilli())
	// 将当前日期前几天数
	startDate := fmt.Sprint(now.AddDate(0, 0, -day).Truncate(24 * time.Hour).UnixMilli())

	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)
		if expireSecond > 120 {
			return info
		}
	}
	// down * 8 / 1000 / 1000 单位M
	info = r.perfKPIRepository.SelectUPFTotalFlow(neType, rmUID, startDate, endDate)
	if v, ok := info["up"]; ok && v == nil {
		info["up"] = 0
	}
	if v, ok := info["down"]; ok && v == nil {
		info["down"] = 0
	}

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

	return info
}
