package fetchlink

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

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

// N3IWFSubInfoList N3IWF在线列表信息
//
// 查询参数 {"imsi":"460302072701181"}
//
// 返回结果 {"rows":[],"total":0}
func N3IWFSubInfoList(neInfo model.NeInfo, data map[string]string) (map[string]any, error) {
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/ueManagement/v1/elementType/n3iwf/objectType/ueInfo", neInfo.IP, neInfo.Port)
	// 查询参数拼接
	query := []string{}
	if v, ok := data["imsi"]; ok && v != "" {
		query = append(query, fmt.Sprintf("imsi=%s", v))
	}
	if len(query) > 0 {
		neUrl = fmt.Sprintf("%s?%s", neUrl, strings.Join(query, "&"))
	}

	resBytes, err := fetch.Get(neUrl, nil, 60_000)
	if err != nil {
		logger.Warnf("N3IWFSubInfo Get \"%s\"", neUrl)
		logger.Errorf("N3IWFSubInfo %s", err.Error())
		return nil, fmt.Errorf("NeService N3IWF API Error")
	}

	// 序列化结果
	// {
	// 	"data": [
	// 		{
	// 			"activeTime": "2023-11-29 06:35:43",
	// 			"imsi": "460302072701181",
	// 			"nai": "0460302072701181@nai.epc.mnc030.mcc460.3gppnetwork.org",
	// 			"regState": 1
	// 		}
	// 	]
	// }
	var resData map[string]any
	err = json.Unmarshal(resBytes, &resData)
	if err != nil {
		logger.Errorf("N3IWFSubInfo Unmarshal %s", err.Error())
		return nil, err
	}

	// 固定返回字段，方便前端解析
	if v, ok := resData["data"]; ok && v != nil {
		resData["rows"] = v.([]any)
		resData["total"] = len(v.([]any))
		delete(resData, "data")
	} else {
		resData["rows"] = []any{}
		resData["total"] = 0
	}
	return resData, nil
}
