/*
 * @description:
 * @Author: CP
 * @Date: 2021-03-31 15:06:21
 * @FilePath: \design_quantity\web\api\upload_api.go
 */
package api

import (
	"bytes"
	"fmt"
	"io"
	"log"
	"os"
	"strings"
	"time"

	"github.com/kataras/iris/v12"
	"go.mod/conf"
	"go.mod/services"
)

type UploadApi struct {
	//框架-web应用上下文环境
	Ctx iris.Context
	// // 需要用的service
	ServiceContract services.ContractService
}

// Upload ： 处理文件上传
func (c *UploadApi) Post() {
	errCode := 0
	id := "0"
	defer func() {
		if errCode < 0 {
			c.Ctx.JSON(iris.Map{"code": -1, "msg": "上传失败"})

		} else {
			c.Ctx.JSON(iris.Map{"code": 0, "msg": "上传成功", "data": id})
		}
		return
	}()

	file, head, err := c.Ctx.FormFile("file")
	if err != nil {
		log.Printf("Failed to get form data, err:%s\n", err.Error())
		errCode = -1
		return
	}
	defer file.Close()

	buf := bytes.NewBuffer(nil)
	if _, err := io.Copy(buf, file); err != nil {
		log.Printf("Failed to get file data, err:%s\n", err.Error())
		errCode = -2
		return
	}

	//  文件元信息-todo
	// FileName := head.Filename
	FileSize := int64(len(buf.Bytes()))
	UploadAt := fmt.Sprintf("%d", time.Now().UnixNano())

	Location := conf.MergeLocalRootDir + UploadAt + head.Filename // 存储地址
	newFile, err := os.Create(Location)
	if err != nil {
		log.Printf("Failed to create file, err:%s\n", err.Error())
		errCode = -3
		return
	}
	defer newFile.Close()

	nByte, err := newFile.Write(buf.Bytes())
	if int64(nByte) != FileSize || err != nil {
		log.Printf("Failed to save data into file, writtenSize:%d, err:%s\n", nByte, err.Error())
		errCode = -4
		return
	}

	// fmt.Println(c.Ctx.FormValue("id"))

	// treeVM := &viewmodels.TreeSectionContract{}
	// err = c.Ctx.ReadForm(treeVM)
	// if err != nil {
	// 	log.Println("folder-ValidRule-ReadForm转换异常, error=", err)
	// 	errCode = -6
	// 	return
	// }

	// fmt.Println(treeVM)

	// id, err := utils.GetDecryptId(treeVM.Id)
	// if err != nil {
	// 	errCode = -6
	// 	return
	// }

	ext := strings.Join(head.Header["Content-Type"], "")

	id, err = c.ServiceContract.SaveUpload(Location, head.Filename, ext)
	if err != nil {
		errCode = -6
		return
	}

}
