package models

import (
	"bytes"
	"io"
	"os"

	"github.com/gin-gonic/gin"
)

type UpBigFile struct {
	SaveDir   string //保存路径
	temporary string //临时文件
}

func (class *UpBigFile) SetSaveDir(dir string) *UpBigFile {
	if dir == "" {
		return nil
	}
	dirLen := len(dir)
	if dir[dirLen-1:] != "/" {
		class.SaveDir = dir + "/"
	} else {
		class.SaveDir = dir
	}
	return class
}

func (class *UpBigFile) Up(ctx *gin.Context) {
	if class.SaveDir == "" {
		return
	}
	if ctx.Request.PostFormValue("FileName") != "" {
		name := ctx.Request.PostFormValue("FileName")
		err := os.Rename(class.SaveDir+"blob", class.SaveDir+name)
		if err != nil {
			ctx.String(200, "false")
		} else {
			ctx.String(200, "true")
		}
	} else {
		if _, err := os.Stat(class.temporary); err != nil { //欲上传目录下没有这个文件
			file, h, err := ctx.Request.FormFile("part")
			if err != nil {
				//获取上传文件失败
				return
			}
			buf := bytes.NewBuffer(nil)
			defer file.Close()
			io.Copy(buf, file)
			f, _ := os.OpenFile(class.SaveDir+h.Filename, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0777)
			defer f.Close()
			f.Write(buf.Bytes())
		} else {
			file, h, _ := ctx.Request.FormFile("part")
			buf := bytes.NewBuffer(nil)
			defer file.Close()
			io.Copy(buf, file)
			f, _ := os.OpenFile(class.SaveDir+h.Filename, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0777)
			defer f.Close()
			f.Write(buf.Bytes())
		}
	}
}