package v1

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"bwallet/pkg/app"
	"bwallet/pkg/e"
	"bwallet/pkg/setting"
	"bwallet/pkg/upload"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"fmt"
)

func Upload(c *gin.Context) {
	appG := app.Gin{C: c}

	accessKeyId := setting.OssSetting.AccessKeyId
	accessKeySecret := setting.OssSetting.AccessKeySecret
	endpoint := setting.OssSetting.Endpoint
	bucketName := setting.OssSetting.Bucket

	file, image, err := c.Request.FormFile("image")
	if err != nil {
		appG.Response(http.StatusInternalServerError, e.ERROR, nil)
		return
	}

	if image == nil {
		appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
		return
	}

	imageName := upload.GetImageName(image.Filename)
	fullPath := upload.GetImageFullPath()
	//savePath := upload.GetImagePath()
	src := fullPath + imageName

	if !upload.CheckImageExt(imageName) || !upload.CheckImageSize(file) {
		appG.Response(http.StatusBadRequest, e.ERROR_UPLOAD_CHECK_IMAGE_FORMAT, nil)
		return
	}

	err = upload.CheckImage(fullPath)
	if err != nil {
		appG.Response(http.StatusInternalServerError, e.ERROR_UPLOAD_CHECK_IMAGE_FAIL, nil)
		return
	}

	if err := c.SaveUploadedFile(image, src); err != nil {
		appG.Response(http.StatusInternalServerError, e.ERROR_UPLOAD_SAVE_IMAGE_FAIL, nil)
		return
	}

	client, err := oss.New(endpoint, accessKeyId, accessKeySecret)
	if err != nil {
		appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
		return
	}

	bucket, err := client.Bucket(bucketName)
	if err != nil {
		appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
		return
	}

	uploaddir := "upload/test"
	objectName := fmt.Sprintf("%s/%s", uploaddir, imageName) //完整的oss路径
	err = bucket.PutObjectFromFile(objectName, upload.GetImageFullUrl(imageName))
	if err != nil {
		fmt.Println("aaaaaa")
		fmt.Println(err)
		return
	}
	var resultfile = objectName
	fmt.Println(imageName)
	fmt.Println(resultfile)
	appG.Response(http.StatusOK, e.SUCCESS, map[string]string{
		"image_url":  resultfile,
		"image_name": imageName,
	})
}
