package tool

import (
	"errors"
	"strconv"
	"strings"
)

// int64 to string
func I64ToS(i64 int64) string {
	return strconv.FormatInt(i64, 10)
}

// int32 to string
func I32ToS(i32 int32) string {
	return strconv.FormatInt(int64(i32), 10)
}

// float64 to string
func F64ToS(f64 float64) string {
	return strconv.FormatFloat(f64, 'f', 2, 64)
}

// 去掉小数点
func F64ToS0(f64 float64) string {
	return strconv.FormatFloat(f64, 'f', 0, 64)
}

// string to float64
func SToF64(s string) float64 {
	f64, err := strconv.ParseFloat(s, 10)
	if err != nil {
		return 0
	}
	return f64
}

// SToI64 string to int64
func SToI64(s string) int64 {
	i, _ := strconv.ParseInt(s, 10, 64)
	return i
}

// SToUI64 string to uint64
func SToUI64(s string) uint64 {
	i, _ := strconv.ParseUint(s, 10, 64)
	return i
}

// SToI32 string to int32
func SToI32(s string) int32 {
	i, _ := strconv.ParseInt(s, 10, 64)
	return int32(i)
}

// SToI16 string to int16
func SToI16(s string) int16 {
	i, _ := strconv.ParseInt(s, 10, 64)
	return int16(i)
}

// SToI8 string to int8
func SToI8(s string) int8 {
	i, _ := strconv.ParseInt(s, 10, 8)
	return int8(i)
}

// StringSliceToInt32Slice 字符串切片转换为int32类型切片
func StringSliceToInt32Slice(strSlice []string) ([]int32, error) {
	int32Slice := make([]int32, len(strSlice))
	for i, str := range strSlice {
		num, err := strconv.ParseInt(str, 10, 32)
		if err != nil {
			return nil, err
		}
		int32Slice[i] = int32(num)
	}
	return int32Slice, nil
}

// StringSliceToIntSlice 字符串切片转换为int类型切片
func StringSliceToIntSlice(strSlice []string) ([]int32, error) {
	int32Slice := make([]int32, len(strSlice))
	for i, str := range strSlice {
		num, err := strconv.Atoi(str)
		if err != nil {
			return nil, err
		}
		int32Slice[i] = int32(num)
	}
	return int32Slice, nil
}

// StringToInt8Slice 字符串转换为int8类型切片
func StringToInt8Slice(str string, spl string) ([]int8, error) {
	if len(str) <= 0 {
		var arr []int8
		return arr, errors.New("字符串不能为空")
	}
	strSlice := strings.Split(str, spl)
	int8Slice := make([]int8, len(strSlice))
	for i, str := range strSlice {
		num, err := strconv.ParseInt(str, 10, 32)
		if err != nil {
			return nil, err
		}
		int8Slice[i] = int8(num)
	}
	return int8Slice, nil
}

func BoolToInt8(b bool) int8 {
	if b {
		return 1
	}
	return 0
}
