package services

import (
	"context"
	"errors"
	"eta/eta_api/utils"
	"fmt"
	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"log"
	"time"
)

//func GetMinIOSTSToken() (item *Token, err error) {
//	// MinIO服务的访问信息
//	item = new(Token)
//	//useSSL := false
//	//if utils.MinIoUseSSL == "true" {
//	//	useSSL = true
//	//}
//	// 创建MinIO客户端
//	//minioClient, err := minio.New(utils.MinIoEndpoint, &minio.Options{
//	//	Creds:  credentials.NewStaticV4(utils.MinIoAccessKeyId, utils.MinIoAccessKeySecret, ""),
//	//	Secure: useSSL,
//	//})
//	//if err != nil {
//	//	return nil, err
//	//}
//	// 设置STS凭证请求参数
//	//policy := `{
//	//    "Version": "2012-10-17",
//	//    "Statement": [
//	//        {
//	//            "Sid": "",
//	//            "Effect": "Allow",
//	//            "Principal": {"AWS": "arn:aws:iam::1234567890:root"},
//	//            "Action": "s3:GetObject",
//	//            "Resource": "arn:aws:s3:::<YourBucketName>/*"
//	//        }
//	//    ]
//	//}`
//	//expiry := time.Hour * 24 // STS凭证的过期时间
//	//获取STS凭证
//	//stsCredentials, err := minioClient.PresignedPutObject(context.Background(), "etastatic", "myobject", expiry)
//	//if err != nil {
//	//	return
//	//}
//	item.AccessKeyId = utils.MinIoAccessKeyId
//	item.SecretKeyId = utils.MinIoAccessKeySecret
//	item.Endpoint = utils.MinIoEndpoint
//	item.ImgHost = utils.MinIoImghost
//	item.Bucketname = utils.MinIoBucketname
//	item.UseSSL = utils.MinIoUseSSL
//	item.RegionId = utils.MinIoRegion
//	item.Port = utils.MinIoPort
//	return
//}

//type Token struct {
//	AccessKeyId string
//	SecretKeyId string
//	RegionId    string
//	Bucketname  string
//	Endpoint    string
//	ImgHost     string
//	UseSSL      string
//	Port        string
//}

//func UploadMinIo() {
//	ctx := context.Background()
//	endpoint := "8.136.199.33:9000/"
//	accessKeyID := "LfQ8uiJiLP7vLxjRrmNW"
//	secretAccessKey := "IszGVHsNicJMQxHC46cYFtbrOiapo0ynwOIJ6c2R"
//	useSSL := false
//
//	// Initialize minio client object.
//	minioClient, err := minio.New(endpoint, &minio.Options{
//		Creds:  credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
//		Secure: useSSL,
//	})
//	if err != nil {
//		log.Fatalln(err)
//	}
//
//	// Make a new bucket called mymusic.
//	bucketName := "etastatic"
//	location := "/"
//
//	err = minioClient.MakeBucket(ctx, bucketName, minio.MakeBucketOptions{Region: location})
//	if err != nil {
//		// Check to see if we already own this bucket (which happens if you run this twice)
//		exists, errBucketExists := minioClient.BucketExists(ctx, bucketName)
//		if errBucketExists == nil && exists {
//			log.Printf("We already own %s\n", bucketName)
//		} else {
//			log.Fatalln(err)
//		}
//	} else {
//		log.Printf("Successfully created %s\n", bucketName)
//	}
//	//buckets, err := minioClient.ListBuckets(ctx)
//	//for _, bucket := range buckets {
//	//	fmt.Println(bucket)
//	//}
//	// Upload the zip file
//	objectName := "1111.xlsx"
//	filePath := "/Users/xi/Desktop/1111.xlsx"
//	contentType := "application/xlsx"
//
//	// Upload the zip file with FPutObject
//	info, err := minioClient.FPutObject(ctx, bucketName, objectName, filePath, minio.PutObjectOptions{ContentType: contentType})
//	if err != nil {
//		log.Fatalln(err)
//	}
//
//	log.Printf("Successfully uploaded %s of size %d\n", objectName, info.Size)
//}

// UploadImgToMinIo 图片上传
//func UploadImgToMinIo(fileName, filePath string) (string, error) {
//	if utils.MinIoAccessKeyId == `` || utils.MinIoAccessKeySecret == `` {
//		return "0", errors.New("MinIo信息未配置")
//	}
//
//	ctx := context.Background()
//	endpoint := utils.MinIoEndpoint
//	accessKeyID := utils.MinIoAccessKeyId
//	secretAccessKey := utils.MinIoAccessKeySecret
//	useSSL := false
//	if utils.MinIoUseSSL == "true" {
//		useSSL = true
//	}
//	minioClient, err := minio.New(endpoint, &minio.Options{
//		Creds:  credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
//		Secure: useSSL,
//	})
//	if err != nil {
//		log.Fatalln(err)
//		return "1", err
//	}
//	bucketName := utils.MinIoBucketname
//	// Check to see if we already own this bucket (which happens if you run this twice)
//	exists, errBucketExists := minioClient.BucketExists(ctx, bucketName)
//	if errBucketExists == nil && exists {
//		log.Printf("We already own %s\n", bucketName)
//	} else {
//		log.Fatalln(err)
//		return "2", err
//	}
//	path := utils.MinIoUploadDir + time.Now().Format("200601/20060102/")
//	path += fileName
//	// Upload the zip file with FPutObject
//	//contentType := "application/xlsx"
//	_, err = minioClient.FPutObject(ctx, bucketName, path, filePath, minio.PutObjectOptions{})
//	if err != nil {
//		log.Fatalln(err)
//		return "3", err
//	}
//
//	path = utils.MinIoImghost + path
//	return path, err
//}

// UploadAudioToMinIo 音频上传
//func UploadAudioToMinIo(fileName, filePath string) (string, error) {
//	if utils.MinIoAccessKeyId == `` || utils.MinIoAccessKeySecret == `` {
//		return "0", errors.New("MinIo信息未配置")
//	}
//
//	ctx := context.Background()
//	endpoint := utils.MinIoEndpoint
//	accessKeyID := utils.MinIoAccessKeyId
//	secretAccessKey := utils.MinIoAccessKeySecret
//	useSSL := false
//	if utils.MinIoUseSSL == "true" {
//		useSSL = true
//	}
//	minioClient, err := minio.New(endpoint, &minio.Options{
//		Creds:  credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
//		Secure: useSSL,
//	})
//	if err != nil {
//		log.Fatalln(err)
//		return "1", err
//	}
//	bucketName := utils.MinIoBucketname
//	// Check to see if we already own this bucket (which happens if you run this twice)
//	exists, errBucketExists := minioClient.BucketExists(ctx, bucketName)
//	if errBucketExists == nil && exists {
//		log.Printf("We already own %s\n", bucketName)
//	} else {
//		log.Fatalln(err)
//		return "2", err
//	}
//
//	path := utils.MinIoUpload_Audio_Dir + time.Now().Format("200601/20060102/")
//	path += fileName
//
//	// Upload the zip file with FPutObject
//	//contentType := "application/xlsx"
//	_, err = minioClient.FPutObject(ctx, bucketName, path, filePath, minio.PutObjectOptions{})
//	if err != nil {
//		log.Fatalln(err)
//		return "3", err
//	}
//
//	path = utils.MinIoImghost + path
//	return path, err
//}

// UploadVideoToMinIo 视频上传
//func UploadVideoToMinIo(filename, filePath, savePath string) error {
//	if utils.MinIoAccessKeyId == `` || utils.MinIoAccessKeySecret == `` {
//		return errors.New("MinIo信息未配置")
//	}
//	defer func() {
//		os.Remove(filePath)
//	}()
//
//	ctx := context.Background()
//	endpoint := utils.MinIoEndpoint
//	accessKeyID := utils.MinIoAccessKeyId
//	secretAccessKey := utils.MinIoAccessKeySecret
//	useSSL := false
//	if utils.MinIoUseSSL == "true" {
//		useSSL = true
//	}
//	minioClient, err := minio.New(endpoint, &minio.Options{
//		Creds:  credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
//		Secure: useSSL,
//	})
//	if err != nil {
//		log.Fatalln(err)
//		return err
//	}
//	bucketName := utils.MinIoBucketname
//	// Check to see if we already own this bucket (which happens if you run this twice)
//	exists, errBucketExists := minioClient.BucketExists(ctx, bucketName)
//	if errBucketExists == nil && exists {
//		log.Printf("We already own %s\n", bucketName)
//	} else {
//		log.Fatalln(err)
//		return err
//	}
//
//	//path := utils.Upload_Audio_Dir + time.Now().Format("200601/20060102/")
//	//path += filename
//	_, err = minioClient.FPutObject(ctx, bucketName, savePath, filePath, minio.PutObjectOptions{})
//	if err != nil {
//		log.Fatalln(err)
//		return err
//	}
//	//path = utils.Imghost + path
//	//return path,err
//	return err
//}

// UploadFileToMinIo 上传文件
//func UploadFileToMinIo(filename, filePath, savePath string) error {
//	if utils.MinIoAccessKeyId == `` || utils.MinIoAccessKeySecret == `` {
//		return errors.New("MinIo信息未配置")
//	}
//	defer func() {
//		os.Remove(filePath)
//	}()
//	ctx := context.Background()
//	endpoint := utils.MinIoEndpoint
//	accessKeyID := utils.MinIoAccessKeyId
//	secretAccessKey := utils.MinIoAccessKeySecret
//	useSSL := false
//	if utils.MinIoUseSSL == "true" {
//		useSSL = true
//	}
//	minioClient, err := minio.New(endpoint, &minio.Options{
//		Creds:  credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
//		Secure: useSSL,
//	})
//	if err != nil {
//		log.Fatalln(err)
//		return err
//	}
//	bucketName := utils.MinIoBucketname
//	// Check to see if we already own this bucket (which happens if you run this twice)
//	exists, errBucketExists := minioClient.BucketExists(ctx, bucketName)
//	if errBucketExists == nil && exists {
//		log.Printf("We already own %s\n", bucketName)
//	} else {
//		log.Fatalln(err)
//		return err
//	}
//	//path := utils.Upload_Audio_Dir + time.Now().Format("200601/20060102/")
//	//path += filename
//	_, err = minioClient.FPutObject(ctx, bucketName, savePath, filePath, minio.PutObjectOptions{})
//	if err != nil {
//		log.Fatalln(err)
//		return err
//	}
//	//path = utils.Imghost + path
//	//return path,err
//	return err
//}

// UploadMinIoToDir 上传至hzchart
//func UploadMinIoToDir(filename, filePath, uploadDir, fileDir string) (string, error) {
//	if utils.MinIoAccessKeyId == `` || utils.MinIoAccessKeySecret == `` {
//		return "0", errors.New("MinIo信息未配置")
//	}
//	ctx := context.Background()
//	endpoint := utils.MinIoEndpoint
//	accessKeyID := utils.MinIoAccessKeyId
//	secretAccessKey := utils.MinIoAccessKeySecret
//	useSSL := false
//	if utils.MinIoUseSSL == "true" {
//		useSSL = true
//	}
//	minioClient, err := minio.New(endpoint, &minio.Options{
//		Creds:  credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
//		Secure: useSSL,
//	})
//	if err != nil {
//		log.Fatalln(err)
//		return "1", err
//	}
//	bucketName := utils.MinIoBucketname
//	// Check to see if we already own this bucket (which happens if you run this twice)
//	exists, errBucketExists := minioClient.BucketExists(ctx, bucketName)
//	if errBucketExists == nil && exists {
//		log.Printf("We already own %s\n", bucketName)
//	} else {
//		log.Fatalln(err)
//		return "2", err
//	}
//	if uploadDir == "" {
//		uploadDir = utils.MinIoUploadDir
//	}
//	if fileDir == "" {
//		fileDir = time.Now().Format("200601/20060102/")
//	}
//	path := uploadDir + fileDir
//	path += filename
//	_, err = minioClient.FPutObject(ctx, bucketName, path, filePath, minio.PutObjectOptions{})
//	if err != nil {
//		log.Fatalln(err)
//		return "3", err
//	}
//	path = utils.MinIoImghost + path
//	return path, err
//}

//func UploadImgToMinIoTest(fileName, filePath string) (string, error) {
//	ctx := context.Background()
//	endpoint := utils.Endpoint
//	accessKeyID := utils.AccessKeyId
//	secretAccessKey := utils.AccessKeySecret
//	useSSL := false
//	if utils.MinIoUseSSL == "true" {
//		useSSL = true
//	}
//	minioClient, err := minio.New(endpoint, &minio.Options{
//		Creds:  credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
//		Secure: useSSL,
//	})
//	if err != nil {
//		log.Fatalln(err)
//		return "1", err
//	}
//	bucketName := utils.Bucketname
//	// Check to see if we already own this bucket (which happens if you run this twice)
//
//	buckets, e := minioClient.ListBuckets(ctx)
//	if e != nil {
//		fmt.Println("ListBuckets: ", e.Error())
//		return "", e
//	}
//	for k := range buckets {
//		fmt.Println(k)
//	}
//
//	exists, errBucketExists := minioClient.BucketExists(ctx, bucketName)
//	fmt.Println("exists: ", exists)
//	fmt.Println("errBucketExists: ", errBucketExists)
//	if errBucketExists == nil && exists {
//		log.Printf("We already own %s\n", bucketName)
//	} else {
//		log.Fatalln(err)
//		return "2", err
//	}
//	path := utils.UploadDir + time.Now().Format("200601/20060102/")
//	path += fileName
//	// Upload the zip file with FPutObject
//	//contentType := "application/xlsx"
//	_, err = minioClient.FPutObject(ctx, bucketName, path, filePath, minio.PutObjectOptions{})
//	if err != nil {
//		log.Fatalln(err)
//		return "3", err
//	}
//
//	path = utils.Imghost + path
//	return path, err
//}

type MinioOss struct{}

// UploadFile 上传文件
func (m *MinioOss) UploadFile(fileName, filePath, savePath string) (string, error) {
	if utils.MinIoAccessKeyId == `` || utils.MinIoAccessKeySecret == `` {
		return "0", errors.New("MinIo信息未配置")
	}

	ctx := context.Background()
	// 此处兼容一下前后端endpoint不一致的情况, 前端用minio_endpoint后端用minio_back_endpoint, minio_back_endpoint为空则都取前者
	endpoint := utils.MinIoEndpoint
	if utils.MinIoBackEndpoint != "" {
		endpoint = utils.MinIoBackEndpoint
	}
	accessKeyID := utils.MinIoAccessKeyId
	secretAccessKey := utils.MinIoAccessKeySecret
	useSSL := false
	if utils.MinIoUseSSL == "true" {
		useSSL = true
	}
	minioClient, err := minio.New(endpoint, &minio.Options{
		Creds:  credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
		Secure: useSSL,
	})
	if err != nil {
		log.Fatalln(err)
		return "1", err
	}
	bucketName := utils.MinIoBucketname
	exists, errBucketExists := minioClient.BucketExists(ctx, bucketName)
	if errBucketExists != nil || !exists {
		err = fmt.Errorf("BucketExists: %v; err: %v", exists, errBucketExists)
		return "2", err
	}

	path := savePath
	if savePath == "" {
		path = utils.MinIoUploadDir + time.Now().Format("200601/20060102/") + fileName
	}
	_, err = minioClient.FPutObject(ctx, bucketName, path, filePath, minio.PutObjectOptions{})
	if err != nil {
		log.Fatalln(err)
		return "3", err
	}
	resourceUrl := utils.MinIoImghost + path
	return resourceUrl, err
}

func (m *MinioOss) GetUploadToken() (token OssToken, err error) {
	token.AccessKeyId = utils.MinIoAccessKeyId
	token.SecretKeyId = utils.MinIoAccessKeySecret
	token.Endpoint = utils.MinIoEndpoint
	token.ImgHost = utils.MinIoImghost
	token.Bucketname = utils.MinIoBucketname
	token.UseSSL = utils.MinIoUseSSL
	token.RegionId = utils.MinIoRegion
	token.Port = utils.MinIoPort
	return
}