package controllers

import (
	"ai_developer_admin/models"
	"fmt"
	"github.com/beego/beego/v2/core/logs"
	"net/http"
	"os"
)

type FileController struct {
	MainController
}

func (server *FileController) Upload() {
	info, err := server.Check()
	if err != nil {
		server.respond(http.StatusUnauthorized, err.Error())
		return
	}
	if !(info.Role == 1 || info.Role == 2) {
		server.respond(http.StatusUnauthorized, "只有管理员才可执行此操作")
		return
	}
	dir := "uploads"
	if _, err = os.Stat(dir); err != nil {
		if os.IsNotExist(err) {
			logs.Debug("Upload 目录不存在")
		} else {
			logs.Debug("Upload", err.Error())
		}
	}
	_, header, err := server.GetFile("file")
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}
	path := dir + "/" + header.Filename
	err = server.SaveToFile("file", path)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}
	responseData := struct {
		Url string `json:"url"`
	}{
		Url: path,
	}
	server.respond(http.StatusOK, "文件上传成功", responseData)
}

func checkDIR(dir string) (bool, error) {
	if _, err := os.Stat("mydir"); err != nil {
		if os.IsNotExist(err) {
			fmt.Println("目录不存在")
			return false, nil

		} else {
			fmt.Println(err)
			return false, err
		}
	}

	return true, nil
}
