package service

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

	"nms_nbi/src/framework/logger"
	"nms_nbi/src/framework/utils/fetch"
	"nms_nbi/src/modules/network_element/model"
)

// NeState 获取网元端服务状态
func NeState(neInfo model.NeInfo) (map[string]any, error) {
	// 网元状态
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/systemManagement/v1/elementType/%s/objectType/systemState", neInfo.IP, neInfo.Port, strings.ToLower(neInfo.NeType))
	resBytes, err := fetch.Get(neUrl, nil, 250)
	if err != nil {
		logger.Warnf("NeState %s", err.Error())
		return nil, err
	}

	// 序列化结果
	var resData map[string]any
	err = json.Unmarshal(resBytes, &resData)
	if err != nil {
		logger.Warnf("NeState Unmarshal %s", err.Error())
		return nil, err
	}

	return map[string]any{
		"neType":      neInfo.NeType,
		"neId":        neInfo.NeId,
		"neName":      neInfo.NeName,
		"neIP":        neInfo.IP,
		"refreshTime": time.Now().UnixMilli(), // 获取时间
		"version":     resData["version"],
		"capability":  resData["capability"],
		"sn":          resData["serialNum"],
		"expire":      resData["expiryDate"],
		"cpu":         resData["cpuUsage"],
		"mem":         resData["memUsage"],
		"disk":        resData["diskSpace"],
	}, nil
}

// NeConfigOMC 网元配置对端网管信息
func NeConfigOMC(neInfo model.NeInfo) (map[string]any, error) {
	// 网元配置对端网管信息
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/systemManagement/v1/elementType/%s/objectType/config/omcNeConfig", neInfo.IP, neInfo.Port, strings.ToLower(neInfo.NeType))
	resBytes, err := fetch.PutJSON(neUrl, map[string]any{
		"neId":       neInfo.NeId,
		"neName":     neInfo.NeName,
		"port":       neInfo.Port,
		"province":   neInfo.Province,
		"pvFlag":     neInfo.PvFlag,
		"rmUID":      neInfo.RmUID,
		"vendorName": neInfo.VendorName,
		"dn":         neInfo.Dn,
	}, nil)
	var resData map[string]any
	if err != nil {
		status := err.Error()
		logger.Warnf("NeConfigOMC %s", status)
		if strings.HasPrefix(status, "204") {
			return resData, nil
		}
		return nil, err
	}

	// 序列化结果
	err = json.Unmarshal(resBytes, &resData)
	if err != nil {
		logger.Warnf("NeConfigOMC Unmarshal %s", err.Error())
		return nil, err
	}

	return resData, nil
}
