package service

import (
	"encoding/json"
	"fmt"
	"nms_nbi/src/framework/constants/uploadsubpath"
	"nms_nbi/src/framework/logger"
	"nms_nbi/src/framework/utils/file"
	"nms_nbi/src/modules/nms_cxy/utils/common"
	"nms_nbi/src/modules/nms_cxy/utils/kafka"
)

// 实例化数据层 ResourceImpl 结构体
var NewResourceImpl = &ResourceImpl{}

// 资源数据处理服务 服务层处理
type ResourceImpl struct{}

// ResourceeUploadOSS 资源数据上报
// OMC在每天的0时及12时上报网元的全量资源数据文件至OSS
func (s *ResourceImpl) ResourceeUploadOSS(neType string) error {
	// 资源数据
	dataArr := []any{}
	dataArr = append(dataArr, map[string]any{
		"RUID":              "WXZX001CLL0000115349200113",
		"UserLabel":         "cell1000",
		"CellBarred":        0,
		"UeInactiveTimer":   10000,
		"SupportRRCNumbers": 200,
	})

	// 文件名
	dataSaveFileName := common.DataSaveFileName{
		ResCode: neType,
	}
	fileName := dataSaveFileName.JSON()
	filePath := fmt.Sprintf("%s/%s", file.ParseUploadFileDir(uploadsubpath.EXPORT), fileName)
	// 数据写入json文件
	err := file.WriterFileJSONLine(dataArr, filePath)
	if err != nil {
		return err
	}
	return common.UploadOSSByJSONToZip(filePath, neType, "NRM")
}

// KafkaPush 推送数据Kafka
//
// acronyms 资源对象类型简称,没有就填空字符串
func (s *ResourceImpl) KafkaPush(neType string, acronyms string, data any) error {
	if neType == "" {
		return nil
	}

	// 数据序列化
	bytes, err := json.Marshal(data)
	if err != nil {
		logger.Errorf("KafkaPush ResourceChangeData err => %s", err.Error())
		return err
	}

	// 订阅topic，名称为：专业编码-厂商编码-OMC编号-网元类型-数据类别（固定为NRM）-资源对象类型简称
	basePath := common.BasePath("-")
	topic := fmt.Sprintf("%s-%s-NRM", basePath, neType)
	if acronyms != "" {
		topic = topic + "-" + acronyms
	}

	// 发送消息
	partition, offset, err := kafka.KInitConm.MessageSyncSend(topic, 0, string(bytes))
	if err != nil {
		logger.Errorf("KafkaPush MessageSyncSend err => %s", err.Error())
		return err
	}
	logger.Infof("KafkaPush MessageSyncSend Partition:%d, Offset:%d", partition, offset)
	return err
}
