package service

import (
	"fmt"
	"nms_nbi/src/framework/constants/uploadsubpath"
	"nms_nbi/src/framework/utils/file"
	neDataModel "nms_nbi/src/modules/network_data/model"
	neDataService "nms_nbi/src/modules/network_data/service"
	"nms_nbi/src/modules/nms_cxy/utils/common"
)

// 实例化数据层 PerformanceImpl 结构体
var NewPerformanceImpl = &PerformanceImpl{
	perfKPIService: neDataService.NewPerfKPIImpl,
}

// 性能数据处理服务 服务层处理
type PerformanceImpl struct {
	// 统计信息服务
	perfKPIService neDataService.IPerfKPI
}

// PerformanceUploadOSS 性能数据上报
// 性能数据文件的上报周期为15分钟。
func (s *PerformanceImpl) PerformanceUploadOSS(neType, startTime, endTime string) error {
	dataArr := [][]string{}

	// 标题行
	titleData := s.perfKPIService.SelectGoldKPITitle(neType)
	titleArr := []string{}
	for _, v := range titleData {
		titleArr = append(titleArr, v.KPIID)
	}
	titleArr = append(titleArr, "neType", "neName", "startIndex", "timeGroup")
	dataArr = append(dataArr, titleArr)

	// 数据行
	query := neDataModel.GoldKPIQuery{
		NeType:    neType,
		StartTime: startTime,
		EndTime:   endTime,
		Interval:  900,
	}
	data := s.perfKPIService.SelectGoldKPI(query)
	for _, v := range data {
		itemLen := len(v)
		dataItem := make([]string, len(v))

		for j, titleStr := range titleArr {
			if strV, ok := v[titleStr]; ok && strV != nil {
				fmt.Println("titleArr ", titleStr, strV)
				dataItem[j] = fmt.Sprint(strV)
			}
		}

		dataItem[itemLen-4] = fmt.Sprint(v["neType"])
		dataItem[itemLen-3] = fmt.Sprint(v["neName"])
		dataItem[itemLen-2] = fmt.Sprint(v["startIndex"])
		dataItem[itemLen-1] = fmt.Sprint(v["timeGroup"])
		dataArr = append(dataArr, dataItem)
	}

	// 文件名
	dataSaveFileName := common.DataSaveFileName{
		ResCode: neType,
	}
	fileName := dataSaveFileName.CSV()
	filePath := fmt.Sprintf("%s/%s", file.ParseUploadFileDir(uploadsubpath.EXPORT), fileName)
	err := file.WriterFileCSV(dataArr, filePath)
	if err != nil {
		return err
	}

	return common.UploadOSSByZip(filePath, neType, "PM")
}
