package utils

import (
	"bytes"
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	uuid "github.com/satori/go.uuid"
	extConfig "go-admin/config"
	"io"
	"mime/multipart"
	"path/filepath"
	"strconv"
	"time"
)

func StringToInt(data string) int {
	reply, _ := strconv.Atoi(data)
	return reply
}

func GetAvg(data string, count int64) string {
	floatData, _ := strconv.ParseFloat(data, 64)
	return strconv.FormatFloat(floatData/float64(count), 'f', 2, 64)

	//res := fmt.Sprintf("%.2f", floatData/float64(count))
	//return res
}

func StringToFloat(data string) float64 {
	reply, _ := strconv.ParseFloat(data, 64)
	return reply
}

func StringToTime(data string) time.Time {
	timeData, _ := time.Parse("2006-01-02 15:04:05", data)
	return timeData
}

//上传文件
func UploadFile(f multipart.File, h *multipart.FileHeader) (string, error) {

	fullFileName := ""

	bucket, err := GetOssBucket()
	if err != nil {
		return fullFileName, err
	}

	uuidValue := uuid.NewV4()
	guid := uuidValue.String()
	buf := bytes.NewBuffer(nil)
	_, err = io.Copy(buf, f)

	if err != nil {
		return fullFileName, err
	}

	//上传到阿里云oss
	yunfiletmp := fmt.Sprintf("%s/%s", extConfig.ExtConfig.Upload.Dir, GetDate())
	fullFileName = fmt.Sprintf("%s/%s%s", yunfiletmp, guid, filepath.Ext(h.Filename))
	//fmt.Println(fullFileName)
	option := oss.ContentType("image/jpg")
	if err = bucket.PutObject(fullFileName, buf, option); err != nil {
		return fullFileName, err
	}
	return fullFileName, nil
}

func GetOssBucket() (*oss.Bucket, error) {
	var Buckets *oss.Bucket

	client, err := oss.New(extConfig.ExtConfig.Aliyunoss.Endpoint, extConfig.ExtConfig.Aliyunoss.Accessid, extConfig.ExtConfig.Aliyunoss.Accesskey)

	if err != nil {
		return nil, err
	}

	// 获取存储空间。
	Buckets, err = client.Bucket(extConfig.ExtConfig.Aliyunoss.Bucket)

	if err != nil {
		return nil, err
	}

	return Buckets, nil
}

func GetDate() string {
	year := time.Now().Format("2006")
	month := time.Now().Format("01")
	day := time.Now().Format("02")
	return year + month + day
}

func Md5Pwd(data string) string {
	h := md5.New()
	h.Write([]byte(data))
	return hex.EncodeToString(h.Sum(nil))
}
