package fetchlink

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

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

// IMSUeSessionNum IMS会话数量
//
// 返回结果 0
func IMSUeSessionNum(neInfo model.NeInfo) (int64, error) {
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/ueManagement/v1/elementType/ims/objectType/ueNum", neInfo.IP, neInfo.Port)
	resBytes, err := fetch.Get(neUrl, nil, 60_000)
	if err != nil {
		errStr := err.Error()
		logger.Warnf("IMSUeSessionNum Get \"%s\"", neUrl)
		logger.Errorf("IMSUeSessionNum %s", errStr)
		return 0, fmt.Errorf("NeService IMS API Error")
	}
	// 序列化结果 {"data":{"ueNum":0}}
	var resData map[string]any
	err = json.Unmarshal(resBytes, &resData)
	if err != nil {
		logger.Errorf("IMSUeSessionNum Unmarshal %s", err.Error())
		return 0, err
	}

	// 固定返回字段，方便前端解析
	var ueNum int64 = 0
	if v, ok := resData["data"]; ok && v != nil {
		if num := v.(map[string]any)["ueNum"]; num != nil {
			ueNum = parse.Number(num)
		}
	}
	return ueNum, nil
}

// IMSUeSessionList IMS会话列表
//
// 查询参数 {"imsi":"460001230000002","msisdn":"12307551232"}
//
// 返回结果 []
func IMSUeSessionList(neInfo model.NeInfo, data map[string]string) ([]map[string]any, error) {
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/ueManagement/v1/elementType/ims/objectType/ueInfo", neInfo.IP, neInfo.Port)
	// 查询参数拼接
	query := []string{}
	if v, ok := data["imsi"]; ok && v != "" {
		query = append(query, fmt.Sprintf("imsi=%s", v))
	}
	if v, ok := data["msisdn"]; ok && v != "" {
		query = append(query, fmt.Sprintf("msisdn=%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 {
		errStr := err.Error()
		logger.Warnf("IMSUeSessionList Get \"%s\"", neUrl)
		logger.Errorf("IMSUeSessionList %s", errStr)
		return nil, fmt.Errorf("NeService IMS API Error")
	}

	// 序列化结果
	// { "data":[
	//     {
	//         "activeTime": "2023-11-29 17:04:54",
	//         "barring": 0,
	//         "impu": "sip:12307551232@ims.mnc000.mcc460.3gppnetwork.org",
	//         "imsi": "460001230000002",
	//         "msisdn": "12307551232",
	//         "regState": 1
	//     }
	// ] }
	var resData map[string]any
	err = json.Unmarshal(resBytes, &resData)
	if err != nil {
		logger.Errorf("IMSUeSessionList 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
}
