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"
)

// SMFSubNum SMF在线订阅用户数量 只含5G用户数据
//
// 返回结果 0
func SMFSubNum(neInfo model.NeInfo) (int64, error) {
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/ueManagement/v1/elementType/smf/objectType/ueNum", neInfo.IP, neInfo.Port)
	resBytes, err := fetch.Get(neUrl, nil, 60_000)
	if err != nil {
		errStr := err.Error()
		logger.Warnf("SMFSubNum Get \"%s\"", neUrl)
		logger.Errorf("SMFSubNum %s", errStr)
		return 0, fmt.Errorf("NeService SMF API Error")
	}
	// 序列化结果 {"data":{"ueNum":0}}
	var resData map[string]any
	err = json.Unmarshal(resBytes, &resData)
	if err != nil {
		logger.Errorf("IMSUeSession 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
}

// SMFSubInfoList SMF在线订阅用户列表信息
//
// 查询参数 {"imsi":"360000100000130","msisdn":"8612300000130","upstate":"Inactive","pageNum":"1"}
//
// 返回结果 {"rows":[],"total":0}
func SMFSubInfoList(neInfo model.NeInfo, data map[string]string) (map[string]any, error) {
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/ueManagement/v1/elementType/smf/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 v, ok := data["upstate"]; ok && v != "" {
		query = append(query, fmt.Sprintf("upstate=%s", v))
	}
	// 固定页数量50条
	if v, ok := data["pageNum"]; ok && v != "" {
		pageNum := parse.Number(v)
		query = append(query, fmt.Sprintf("pageNum=%d", pageNum))
	}

	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("SMFSubInfo Get \"%s\"", neUrl)
		logger.Errorf("SMFSubInfo %s", err.Error())
		return nil, fmt.Errorf("NeService SMF API Error")
	}

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

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