package api

import (
	"errors"
	"fmt"
	"github.com/kataras/iris/v12"
	"github.com/sirupsen/logrus"
	"main/database"
	"main/model"
	"main/utils"
	"mime/multipart"
	"os"
	"path"
	"path/filepath"
	"strings"
	"time"
)

func getRootFile(ctx iris.Context) {
	username := utils.GetLoginUser(ctx)
	if utils.DataIsNil(username) {
		return
	}
	userPath := fmt.Sprintf("./upload/%s", username.Username)
	if !utils.FileIsExist(userPath) {
		err := os.MkdirAll(userPath, 0755)
		if utils.ErrHandle(ctx, err) {
			return
		}
	}
	var files filesRes
	fileList, err := os.ReadDir(userPath)
	if utils.ErrHandle(ctx, err) {
		return
	}
	for _, file := range fileList {
		if file.IsDir() {
			files.Dirs = append(files.Dirs, file.Name())
		} else {
			var item fileItem
			item.Name = file.Name()
			f, err := os.Stat(path.Join(userPath, file.Name()))
			if utils.ErrHandle(ctx, err) {
				return
			}
			item.Size = f.Size()
			item.Type = utils.GetFileType(f.Name())
			files.Files = append(files.Files, item)
		}
	}
	err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", files))
	if utils.ErrHandle(ctx, err) {
		return
	}
}

// 获取指定目录下文件
func getFile(ctx iris.Context) {
	username := utils.GetLoginUser(ctx)
	if utils.DataIsNil(username) {
		return
	}
	filePath := ctx.Params().Get("path")
	userPath := fmt.Sprintf("./upload/%s/%s", username.Username, filePath)
	if !utils.FileIsExist(userPath) {
		ctx.StatusCode(iris.StatusBadRequest)
		ctx.SetErr(errors.New(userPath + ":目录不存在"))
		return
	}
	var files filesRes
	fileList, err := os.ReadDir(userPath)
	if utils.ErrHandle(ctx, err) {
		return
	}
	for _, file := range fileList {
		if file.IsDir() {
			files.Dirs = append(files.Dirs, file.Name())
		} else {
			var item fileItem
			item.Name = file.Name()
			f, err := os.Stat(path.Join(userPath, file.Name()))
			if utils.ErrHandle(ctx, err) {
				return
			}
			item.Size = f.Size()
			item.Type = utils.GetFileType(f.Name())
			files.Files = append(files.Files, item)
		}
	}
	err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", files))
	if utils.ErrHandle(ctx, err) {
		return
	}
}

// 删除文件或目录
func deleteFile(ctx iris.Context) {
	username := utils.GetLoginUser(ctx)
	if utils.DataIsNil(username) {
		return
	}
	filePath := ctx.Params().Get("path")
	userPath := fmt.Sprintf("./upload/%s/%s", username.Username, filePath)
	if !utils.FileIsExist(userPath) {
		ctx.StatusCode(iris.StatusBadRequest)
		ctx.SetErr(errors.New("目录不存在"))
		return
	}
	if info, _ := os.Stat(userPath); info.IsDir() {
		err := os.RemoveAll(userPath)
		if utils.ErrHandle(ctx, err) {
			return
		}
	} else {
		err := os.Remove(userPath)
		if utils.ErrHandle(ctx, err) {
			return
		}
	}
	err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", "success"))
	if utils.ErrHandle(ctx, err) {
		return
	}
}

// 上传头像
func uploadAvatar(ctx iris.Context) {
	username := utils.GetLoginUser(ctx)
	if utils.DataIsNil(username) {
		return
	}
	file, info, err := ctx.FormFile("file")
	if utils.ErrHandle(ctx, err) {
		return
	}
	defer func(file multipart.File) {
		err = file.Close()
		if utils.ErrHandle(ctx, err) {
			return
		}
	}(file)
	userPath := fmt.Sprintf("./static/%s", username.Username)
	if !utils.FileIsExist(userPath) {
		err = os.MkdirAll(userPath, 0755)
		if utils.ErrHandle(ctx, err) {
			return
		}
	}
	fileType := strings.Split(info.Filename, ".")[len(strings.Split(info.Filename, "."))-1]
	avatarName := fmt.Sprintf("./static/%s/avatar-%s.%s", username.Username, time.Now().Format("2006-01-02"), fileType)
	_, err = ctx.SaveFormFile(info, avatarName)
	if utils.ErrHandle(ctx, err) {
		return
	}
	err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", avatarName[1:]))
	if utils.ErrHandle(ctx, err) {
		return
	}
}

func uploadDir(ctx iris.Context) {
	username := utils.GetLoginUser(ctx)
	if utils.DataIsNil(username) {
		return
	}
	filePath := ctx.Params().Get("path")
	userPath := fmt.Sprintf("./upload/%s/%s", username.Username, filePath)
	if utils.FileIsExist(userPath) {
		ctx.StatusCode(iris.StatusInternalServerError)
		ctx.SetErr(errors.New("目录已存在"))
		return
	}
	err := os.MkdirAll(userPath, 0755)
	if utils.ErrHandle(ctx, err) {
		return
	}
	err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", "success"))
	if utils.ErrHandle(ctx, err) {
		return
	}
}

// 上传文件
func uploadFile(ctx iris.Context) {
	username := utils.GetLoginUser(ctx)
	if utils.DataIsNil(username) {
		return
	}
	filePath := ctx.Params().Get("path")
	file, info, err := ctx.FormFile("file")
	if utils.ErrHandle(ctx, err) {
		return
	}
	defer func(file multipart.File) {
		err = file.Close()
		if utils.ErrHandle(ctx, err) {
			return
		}
	}(file)
	userPath := fmt.Sprintf("./upload/%s/%s", username.Username, filePath)
	if !utils.FileIsExist(userPath) {
		err = os.MkdirAll(userPath, 0755)
		if utils.ErrHandle(ctx, err) {
			return
		}
	}
	_, err = ctx.SaveFormFile(info, fmt.Sprintf("./upload/%s/%s/%s", username.Username, filePath, info.Filename))
	if utils.ErrHandle(ctx, err) {
		return
	}
	err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", "success"))
	if utils.ErrHandle(ctx, err) {
		return
	}
}

// 文件下载，转到nginx-upload目录
func downloadFile(ctx iris.Context) {
	authToken := ctx.GetCookie("token")
	activeTime := time.Now().Add(-2 * time.Hour)
	var userToken model.JwtKeys
	db := database.GetInstance().GetMysqlDb()
	if err := db.Where("token = ? and created_at >= ?", authToken, activeTime).First(&userToken).Error; err != nil {
		logrus.Errorln("sql执行失败：", err)
	}
	if utils.DataIsNil(userToken.Username) {
		ctx.StatusCode(iris.StatusBadRequest)
		ctx.SetErr(errors.New("未登录"))
		return
	}
	filePath := ctx.Params().Get("path")
	userPath := fmt.Sprintf("./upload/%s/%s", userToken.Username, filePath)
	if !utils.FileIsExist(userPath) {
		ctx.StatusCode(iris.StatusBadRequest)
		ctx.SetErr(errors.New("文件不存在"))
		return
	}
	if info, _ := os.Stat(userPath); info.IsDir() {
		ctx.StatusCode(iris.StatusBadRequest)
		ctx.SetErr(errors.New("只可下载文件"))
		return
	}
	ctx.Recorder().Header().Add("X-Accel-Redirect", fmt.Sprintf("/upload/%s/%s", userToken.Username, filePath))
	ctx.Recorder().Header().Add("X-Accel-Charset", "utf-8")
	ctx.Recorder().Header().Add("Content-Disposition", "attachment")
	ctx.Recorder().Header().Add("Content-Type", "application/octet-stream; charset=utf-8")
	return
}

func getDownloadFileType(ctx iris.Context) {
	authToken := ctx.GetCookie("token")
	activeTime := time.Now().Add(-2 * time.Hour)
	var userToken model.JwtKeys
	var res videoM3u8
	db := database.GetInstance().GetMysqlDb()
	if err := db.Where("token = ? and created_at >= ?", authToken, activeTime).First(&userToken).Error; err != nil {
		logrus.Errorln("sql执行失败：", err)
	}
	if utils.DataIsNil(userToken.Username) {
		ctx.StatusCode(iris.StatusBadRequest)
		ctx.SetErr(errors.New("未登录"))
		return
	}
	username := userToken.Username
	filePath := ctx.Params().Get("path")
	userPath := fmt.Sprintf("./upload/%s/%s", username, filePath)
	currentPath, _ := filepath.Split(filePath)
	filename := strings.TrimSuffix(path.Base(userPath), path.Ext(userPath))
	res.Video = utils.GetFileType(userPath) == "video"
	res.M3u8 = utils.FileIsExist(fmt.Sprintf("./upload-video/%s/%s%s/%s.m3u8", username, currentPath, filename, filename))
	err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", res))
	if err != nil {
		return
	}
	return
}

func downloadVideo(ctx iris.Context) {
	authToken := ctx.GetCookie("token")
	activeTime := time.Now().Add(-2 * time.Hour)
	var userToken model.JwtKeys
	db := database.GetInstance().GetMysqlDb()
	if err := db.Where("token = ? and created_at >= ?", authToken, activeTime).First(&userToken).Error; err != nil {
		logrus.Errorln("sql执行失败：", err)
	}
	if utils.DataIsNil(userToken.Username) {
		ctx.StatusCode(iris.StatusBadRequest)
		ctx.SetErr(errors.New("未登录"))
		return
	}
	username := userToken.Username
	filePath := ctx.Params().Get("path")
	userPath := fmt.Sprintf("./upload/%s/%s", username, filePath)
	currentPath, _ := filepath.Split(filePath)
	filename := strings.TrimSuffix(path.Base(userPath), path.Ext(userPath))
	//fmt.Println(filePath, currentPath, filename)
	if path.Ext(userPath) != ".ts" && !utils.FileIsExist(userPath) {
		ctx.StatusCode(iris.StatusBadRequest)
		ctx.SetErr(errors.New("文件不存在"))
		return
	}
	if info, err := os.Stat(userPath); err == nil && info.IsDir() {
		ctx.StatusCode(iris.StatusBadRequest)
		ctx.SetErr(errors.New("只可下载文件"))
		return
	}
	if utils.GetFileType(userPath) == "video" && utils.FileIsExist(fmt.Sprintf("./upload-video/%s/%s%s/%s.m3u8", username, currentPath, filename, filename)) {
		ctx.Recorder().Header().Add("X-Accel-Redirect", fmt.Sprintf("/upload-video/%s/%s%s/%s.m3u8", username, currentPath, filename, filename))
	} else if utils.GetFileType(userPath) == "video" {
		ctx.Recorder().Header().Add("X-Accel-Redirect", fmt.Sprintf("/upload/%s/%s", username, filePath))
	} else {
		tsPath := fmt.Sprintf("./upload-video/%s/%s%s/%s.ts", username, currentPath, filename[:len(filename)-6], filename)
		ctx.Recorder().Header().Add("X-Accel-Redirect", tsPath[1:])
	}
	ctx.Recorder().Header().Add("X-Accel-Charset", "utf-8")
	ctx.Recorder().Header().Add("Content-Disposition", "attachment")
	ctx.Recorder().Header().Add("Content-Type", "application/octet-stream; charset=utf-8")
	return
}
