package fetchlink

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

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

// PCFRuleInfo PCF策略配置查询信息
func PCFRuleInfo(neInfo model.NeInfo, data map[string]string) ([]map[string]any, error) {
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/ueManagement/v1/elementType/pcf/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, "&"))
	}

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

	// 序列化结果
	err = json.Unmarshal(resBytes, &resData)
	if err != nil {
		logger.Errorf("PCFRuleInfo 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
}

// PCFRuleAdd PCF策略配置添加
func PCFRuleAdd(neInfo model.NeInfo, data any) error {
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/ueManagement/v1/elementType/pcf/objectType/ueInfo", neInfo.IP, neInfo.Port)
	resBytes, err := fetch.PostJSON(neUrl, data, nil)
	if err != nil {
		errStr := err.Error()
		// 正常
		if strings.HasPrefix(errStr, "201") {
			return nil
		}
		// 错误结果
		if strings.HasPrefix(errStr, "400") {
			// 序列化结果
			var resData map[string]any
			err = json.Unmarshal(resBytes, &resData)
			if err != nil {
				logger.Errorf("PCFRuleAdd Unmarshal %s", err.Error())
				return err
			}
			return fmt.Errorf("%s", resData["cause"])
		}

		logger.Warnf("PCFRuleAdd Put \"%s\"", neUrl)
		logger.Errorf("PCFRuleAdd %s", errStr)
		return fmt.Errorf("NeService PCF API Error")
	}
	return nil
}

// PCFRuleAddBatch PCF策略配置批量添加
func PCFRuleAddBatch(neInfo model.NeInfo, data map[string]any, num int64) error {
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/ueManagement/v1/elementType/pcf/objectType/ueInfo/batch/%d", neInfo.IP, neInfo.Port, num)
	resBytes, err := fetch.PostJSON(neUrl, data, nil)
	if err != nil {
		errStr := err.Error()
		// 正常
		if strings.HasPrefix(errStr, "201") {
			return nil
		}
		// 错误结果
		if strings.HasPrefix(errStr, "400") {
			// 序列化结果
			var resData map[string]any
			err = json.Unmarshal(resBytes, &resData)
			if err != nil {
				logger.Errorf("PCFRuleAddBatch Unmarshal %s", err.Error())
				return err
			}
			return fmt.Errorf("%s", resData["cause"])
		}

		logger.Warnf("PCFRuleAddBatch Put \"%s\"", neUrl)
		logger.Errorf("PCFRuleAddBatch %s", errStr)
		return fmt.Errorf("NeService PCF API Error")
	}
	return nil
}

// PCFRuleUpdate PCF策略配置修改
func PCFRuleUpdate(neInfo model.NeInfo, data map[string]any) error {
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/ueManagement/v1/elementType/pcf/objectType/ueInfo", neInfo.IP, neInfo.Port)
	resBytes, err := fetch.PutJSON(neUrl, data, nil)
	if err != nil {
		errStr := err.Error()
		// 错误结果
		if strings.HasPrefix(errStr, "400") {
			// 序列化结果
			var resData map[string]any
			err = json.Unmarshal(resBytes, &resData)
			if err != nil {
				logger.Errorf("PCFRuleUpdate Unmarshal %s", err.Error())
				return err
			}
			return fmt.Errorf("%s", resData["cause"])
		}

		logger.Warnf("PCFRuleUpdate Put \"%s\"", neUrl)
		logger.Errorf("PCFRuleUpdate %s", errStr)
		return fmt.Errorf("NeService PCF API Error")
	}
	return nil
}

// PCFRuleUpdateBatch PCF策略配置批量修改
func PCFRuleUpdateBatch(neInfo model.NeInfo, data map[string]any, num int64) error {
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/ueManagement/v1/elementType/pcf/objectType/ueInfo/batch/%d", neInfo.IP, neInfo.Port, num)
	resBytes, err := fetch.PutJSON(neUrl, data, nil)
	if err != nil {
		errStr := err.Error()
		// 错误结果
		if strings.HasPrefix(errStr, "400") {
			// 序列化结果
			var resData map[string]any
			err = json.Unmarshal(resBytes, &resData)
			if err != nil {
				logger.Errorf("PCFRuleUpdateBatch Unmarshal %s", err.Error())
				return err
			}
			return fmt.Errorf("%s", resData["cause"])
		}

		logger.Warnf("PCFRuleUpdateBatch Put \"%s\"", neUrl)
		logger.Errorf("PCFRuleUpdateBatch %s", errStr)
		return fmt.Errorf("NeService PCF API Error")
	}
	return nil
}

// PCFRuleDelete PCF策略配置删除
func PCFRuleDelete(neInfo model.NeInfo, imsi string) error {
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/ueManagement/v1/elementType/pcf/objectType/ueInfo?imsi=%s", neInfo.IP, neInfo.Port, imsi)
	resBytes, err := fetch.Delete(neUrl, nil)
	if err != nil {
		errStr := err.Error()
		// 正常
		if strings.HasPrefix(errStr, "204") {
			return nil
		}
		// 错误结果
		if strings.HasPrefix(errStr, "400") {
			// 序列化结果
			var resData map[string]any
			err = json.Unmarshal(resBytes, &resData)
			if err != nil {
				logger.Errorf("PCFRuleDelete Unmarshal %s", err.Error())
				return err
			}
			return fmt.Errorf("%s", resData["cause"])
		}

		logger.Warnf("PCFRuleDelete Delete \"%s\"", neUrl)
		logger.Errorf("PCFRuleDelete %s", errStr)
		return fmt.Errorf("NeService PCF API Error")
	}
	return nil
}

// PCFRuleDeleteBatch PCF策略配置批量删除
func PCFRuleDeleteBatch(neInfo model.NeInfo, imsi string, num int64) error {
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/ueManagement/v1/elementType/pcf/objectType/ueInfo/batch/%d?imsi=%s", neInfo.IP, neInfo.Port, num, imsi)
	resBytes, err := fetch.Delete(neUrl, nil)
	if err != nil {
		errStr := err.Error()
		// 正常
		if strings.HasPrefix(errStr, "204") {
			return nil
		}
		// 错误结果
		if strings.HasPrefix(errStr, "400") {
			// 序列化结果
			var resData map[string]any
			err = json.Unmarshal(resBytes, &resData)
			if err != nil {
				logger.Errorf("PCFRuleDeleteBatch Unmarshal %s", err.Error())
				return err
			}
			return fmt.Errorf("%s", resData["cause"])
		}

		logger.Warnf("PCFRuleDeleteBatch Delete \"%s\"", neUrl)
		logger.Errorf("PCFRuleDeleteBatch %s", errStr)
		return fmt.Errorf("NeService PCF API Error")
	}
	return nil
}

// PCFRuleExport PCF策略配置导出
func PCFRuleExport(neInfo model.NeInfo, data map[string]string) ([]byte, error) {
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/ueManagement/v1/elementType/pcf/objectType/ueInfo/file/export", neInfo.IP, neInfo.Port)
	// 查询参数拼接
	query := []string{}
	if v, ok := data["fileType"]; ok && v != "" {
		query = append(query, fmt.Sprintf("fileType=%s", v))
	}
	if len(query) > 0 {
		neUrl = fmt.Sprintf("%s?%s", neUrl, strings.Join(query, "&"))
	}

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

// PCFRuleImport PCF策略配置导入
func PCFRuleImport(neInfo model.NeInfo, data map[string]any) (string, error) {
	neUrl := fmt.Sprintf("http://%s:%d/api/rest/ueManagement/v1/elementType/pcf/objectType/ueInfo/file/import", neInfo.IP, neInfo.Port)
	resBytes, err := fetch.PutJSON(neUrl, data, nil)
	var resData map[string]any
	if err != nil {
		errStr := err.Error()
		// 错误结果
		if strings.HasPrefix(errStr, "400") {
			// 序列化结果
			var resData map[string]any
			err = json.Unmarshal(resBytes, &resData)
			if err != nil {
				logger.Errorf("PCFRuleDeleteBatch Unmarshal %s", err.Error())
				return "", err
			}
			return "", fmt.Errorf("%s", resData["cause"])
		}

		logger.Warnf("PCFRuleImport Put \"%s\"", neUrl)
		logger.Errorf("PCFRuleImport %s", errStr)
		return "", fmt.Errorf("NeService PCF API Error")
	}

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

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