package fetchlink

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

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

// 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 {
		errStr := err.Error()
		if strings.HasPrefix(errStr, "201") || strings.HasPrefix(errStr, "204") {
			return resData, nil
		}
		logger.Warnf("NeConfigOMC Put \"%s\"", neUrl)
		logger.Errorf("NeConfigOMC %s", errStr)
		return nil, fmt.Errorf("NeService Config OMC Update API Error")
	}

	// 200 成功无数据时
	if len(resBytes) == 0 {
		return resData, nil
	}

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

	return resData, nil
}

// NeConfigInfo 网元配置信息
func NeConfigInfo(neInfo model.NeInfo, paramName string) (map[string]any, error) {
	// 网元参数配置信息
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/systemManagement/v1/elementType/%s/objectType/config/%s", neInfo.IP, neInfo.Port, strings.ToLower(neInfo.NeType), paramName)
	resBytes, err := fetch.Get(neUrl, nil, 30_000)
	if err != nil {
		logger.Warnf("NeConfigInfo Get \"%s\"", neUrl)
		logger.Errorf("NeConfigInfo %s", err.Error())
		return nil, fmt.Errorf("NeService Config Info API Error")
	}

	// 序列化结果
	var resData map[string]any
	err = json.Unmarshal(resBytes, &resData)
	if err != nil {
		logger.Errorf("NeConfigInfo Unmarshal %s", err.Error())
		return nil, err
	}
	// 网元参数配置信息为空时是{}，需要补充data属性
	if _, ok := resData["data"]; !ok {
		resData["data"] = []map[string]any{}
	}
	return resData, nil
}

// NeConfigUpdate 网元配置更新
func NeConfigUpdate(neInfo model.NeInfo, paramName, loc string, data map[string]any) (map[string]any, error) {
	// array需要层级
	if loc != "" {
		loc = fmt.Sprintf("?loc=%v", loc)
	}
	// 网元参数配置新增（array）
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/systemManagement/v1/elementType/%s/objectType/config/%s%s", neInfo.IP, neInfo.Port, strings.ToLower(neInfo.NeType), paramName, loc)
	resBytes, err := fetch.PutJSON(neUrl, data, nil)
	var resData map[string]any
	if err != nil {
		errStr := err.Error()
		logger.Warnf("NeConfigUpdate Put \"%s\"", neUrl)
		if strings.HasPrefix(errStr, "201") || strings.HasPrefix(errStr, "204") {
			return resData, nil
		}
		logger.Errorf("NeConfigUpdate %s", errStr)
		return nil, fmt.Errorf("NeService Config Update API Error")
	}

	// 200 成功无数据时
	if len(resBytes) == 0 {
		return resData, nil
	}

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

// NeConfigAdd 网元配置新增 array
func NeConfigAdd(neInfo model.NeInfo, paramName, loc string, data map[string]any) (map[string]any, error) {
	// 网元参数配置新增（array）
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/systemManagement/v1/elementType/%s/objectType/config/%s?loc=%v", neInfo.IP, neInfo.Port, strings.ToLower(neInfo.NeType), paramName, loc)
	resBytes, err := fetch.PostJSON(neUrl, data, nil)
	var resData map[string]any
	if err != nil {
		errStr := err.Error()
		logger.Warnf("NeConfigAdd Post \"%s\"", neUrl)
		if strings.HasPrefix(errStr, "201") || strings.HasPrefix(errStr, "204") {
			return resData, nil
		}
		logger.Errorf("NeConfigAdd %s", errStr)
		return nil, fmt.Errorf("NeService Config Add API Error")
	}

	// 200 成功无数据时
	if len(resBytes) == 0 {
		return resData, nil
	}

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

// NeConfigDelete 网元配置删除 array
func NeConfigDelete(neInfo model.NeInfo, paramName, loc string) (map[string]any, error) {
	// 网元参数配置删除（array）
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/systemManagement/v1/elementType/%s/objectType/config/%s?loc=%v", neInfo.IP, neInfo.Port, strings.ToLower(neInfo.NeType), paramName, loc)
	resBytes, err := fetch.Delete(neUrl, nil)
	var resData map[string]any
	if err != nil {
		errStr := err.Error()
		logger.Warnf("NeConfigDelete Delete \"%s\"", neUrl)
		if strings.HasPrefix(errStr, "201") || strings.HasPrefix(errStr, "204") {
			return resData, nil
		}
		logger.Errorf("NeConfigDelete %s", errStr)
		return nil, fmt.Errorf("NeService Config Update API Error")
	}

	// 200 成功无数据时
	if len(resBytes) == 0 {
		return resData, nil
	}

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