package api

import (
	"errors"
	"fmt"
	"nrhe-train/db/model"
	"nrhe-train/db/repo"
	"path"
	"path/filepath"
	"time"

	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

func Upload(r *GinRouter) {
	r.POSTJWT("/upload/pkg", UploadPkg)
}

func UploadPkg(c *gin.Context, apictx *ApiSession) (interface{}, error) {

	version := c.PostForm("version")
	name := c.PostForm("name")
	userId, _ := primitive.ObjectIDFromHex(apictx.User.ID)
	user, err := GetUserById(apictx, (apictx.User.ID))
	if err != nil {
		fmt.Println(err)
	}
	file, err := c.FormFile("file")
	if err != nil {
		return nil, err
	}
	fmt.Println(file.Size)
	size := fmt.Sprintf("%.2fM", float64(file.Size)/float64(1024*1024))
	fmt.Println(size)
	if path.Ext(file.Filename) != ".zip" {
		return nil, errors.New("仅支持zip文件")
	}

	basePath := "./package/"
	filename := basePath + filepath.Base(file.Filename)
	if err := c.SaveUploadedFile(file, filename); err != nil {
		return nil, err
	}
	versions := &model.Versions{
		UserId:     userId,
		UserName:   user.LoginName,
		Name:       name,
		Url:        fmt.Sprintf("/cr/pkg/%s", file.Filename),
		Size:       size,
		Version:    version,
		CreateTime: time.Now(),
		UpdateTime: time.Now(),
	}
	return repo.RepoAddDoc(apictx.CreateRepoCtx(), repo.CollectionVersions, versions)
}
