package maphelper

import (
	"fmt"

	"github.com/shopspring/decimal"
)

func GetString(m map[string]interface{}, key string) (string, error) {
	val, ok := m[key]
	if !ok {
		return "", fmt.Errorf("参数错误，缺少字段 %s", key)
	}
	strVal, ok := val.(string)
	if !ok {
		return "", fmt.Errorf("字段 %s 类型错误", key)
	}
	return strVal, nil
}

func GetFloat64(m map[string]interface{}, key string) (float64, error) {
	val, ok := m[key]
	if !ok {
		return 0, fmt.Errorf("参数错误，缺少字段 %s", key)
	}
	f, ok := val.(float64)
	if !ok {
		return 0, fmt.Errorf("字段 %s 类型错误", key)
	}
	return f, nil
}

func GetBool(m map[string]interface{}, key string) bool {
	if val, ok := m[key].(bool); ok {
		return val
	}
	return false
}

func GetDecimal(m map[string]interface{}, key string) decimal.Decimal {
	if val, ok := m[key].(string); ok {
		d, _ := decimal.NewFromString(val)
		return d
	}
	return decimal.Zero
}
