package fetchlink

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

	"be.ems/src/framework/logger"
	"be.ems/src/framework/utils/fetch"
	"be.ems/src/modules/ne/model"
)

// AMFNbInfoList AMF基站信息
//
// 查询参数 {"id":"7"}
//
// 返回结果 []
func AMFNbInfoList(neInfo model.NeInfo, data map[string]string) ([]map[string]any, error) {
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/ueManagement/v1/elementType/amf/objectType/nbInfo", neInfo.IP, neInfo.Port)
	// 查询参数拼接
	query := []string{}
	if v, ok := data["id"]; ok && v != "" {
		query = append(query, fmt.Sprintf("nbId=%s", v))
	}
	if len(query) > 0 {
		neUrl = fmt.Sprintf("%s?%s", neUrl, strings.Join(query, "&"))
	}

	var resData map[string]any
	resBytes, err := fetch.Get(neUrl, nil, 60_000)
	if err != nil {
		errStr := err.Error()
		logger.Warnf("AMFNbInfoList Get \"%s\"", neUrl)
		logger.Errorf("AMFNbInfoList %s", errStr)
		return nil, fmt.Errorf("NeService AMF API Error")
	}

	// 序列化结果 {"data":[{"id":"7","name":"NR-SA-GNB","address":"192.168.5.100:60110","ueNum":0}]}
	err = json.Unmarshal(resBytes, &resData)
	if err != nil {
		logger.Errorf("AMFNbInfoList Unmarshal %s", err.Error())
		return nil, err
	}

	// 固定返回字段，方便前端解析
	if v, ok := resData["data"]; ok && v != nil {
		if arr := v.([]any); len(arr) > 0 {
			result := make([]map[string]any, len(arr))
			for i, item := range arr {
				result[i] = item.(map[string]any)
			}
			return result, nil
		}
	}
	return []map[string]any{}, nil
}

// AMFGnbStateList AMF基站状态信息，对比配置项gnbList
//
// 返回结果 []
func AMFGnbStateList(neInfo model.NeInfo) ([]map[string]any, error) {
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/ueManagement/v1/elementType/amf/objectType/nbState", neInfo.IP, neInfo.Port)
	resBytes, err := fetch.Get(neUrl, nil, 60_000)
	if err != nil {
		errStr := err.Error()
		logger.Warnf("AMFGnbStateList Get \"%s\"", neUrl)
		logger.Errorf("AMFGnbStateList %s", errStr)
		return nil, fmt.Errorf("NeService AMF API Error")
	}

	// 序列化结果
	// {
	// 	"data": [
	// 		{
	// 			"index": 1,
	// 			"name": "Gnb",
	// 			"address": "192.168.8.1",
	// 			"position": "Area-B",
	// 			"offTime": "2024-12-30T16:31:57+08:00",
	// 			"onTime": "2024-12-30T15:41:59+08:00",
	// 			"state": "OFF",
	// 			"nbName": "SA",
	// 			"ueNum": 1
	// 		},
	// 	]
	// }
	var resData map[string]any
	err = json.Unmarshal(resBytes, &resData)
	if err != nil {
		logger.Errorf("AMFGnbStateList Unmarshal %s", err.Error())
		return nil, err
	}

	// 固定返回字段，方便前端解析
	if v, ok := resData["data"]; ok && v != nil {
		if arr := v.([]any); len(arr) > 0 {
			result := make([]map[string]any, len(arr))
			for i, item := range arr {
				result[i] = item.(map[string]any)
			}
			return result, nil
		}
	}
	return []map[string]any{}, nil
}
