package api

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

func getNotesList(ctx iris.Context) {
	username := utils.GetLoginUser(ctx)
	if utils.DataIsNil(username) {
		return
	}
	var notes []model.UserNotes
	var res []noteParam
	db := database.GetInstance().GetMysqlDb()
	if err := db.Where("username = ?", username.Username).Select("id", "content").Find(&notes).Error; err != nil {
		logrus.Errorln("sql执行失败：", err)
	}
	for _, item := range notes {
		if len(item.Content) > 100 {
			item.Content = item.Content[:30] + "\n......"
		}
		res = append(res, noteParam{
			ID:      item.ID,
			Content: item.Content,
		})
	}
	err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", res))
	if utils.ErrHandle(ctx, err) {
		return
	}
}

func addNote(ctx iris.Context) {
	username := utils.GetLoginUser(ctx)
	if utils.DataIsNil(username) {
		return
	}
	var note noteParam
	err := ctx.ReadJSON(&note)
	if utils.ErrHandle(ctx, err) {
		return
	}
	db := database.GetInstance().GetMysqlDb()
	if err1 := db.Create(&model.UserNotes{
		Username: username.Username,
		Content:  note.Content,
	}).Error; err1 != nil {
		logrus.Errorln("sql执行失败：", err1)
	}
	var newNote model.UserNotes
	if err1 := db.Where("username = ?", username.Username).Order("id desc").First(&newNote).Error; err1 != nil {
		logrus.Errorln("sql执行失败：", err)
	}
	err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", newNote.ID))
	if utils.ErrHandle(ctx, err) {
		return
	}
}

func getNote(ctx iris.Context) {
	username := utils.GetLoginUser(ctx)
	if utils.DataIsNil(username) {
		return
	}
	db := database.GetInstance().GetMysqlDb()
	var note model.UserNotes
	if err := db.Where("username = ? and id = ?", username.Username, ctx.Params().Get("id")).Find(&note).Error; err != nil {
		logrus.Errorln("sql执行失败：", err)
	}
	if utils.DataIsNil(note) {
		ctx.StatusCode(iris.StatusInternalServerError)
		ctx.SetErr(errors.New("not found"))
		return
	}
	err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", note))
	if utils.ErrHandle(ctx, err) {
		return
	}
}

func deleteNote(ctx iris.Context) {
	username := utils.GetLoginUser(ctx)
	if utils.DataIsNil(username) {
		return
	}
	var note model.UserNotes
	db := database.GetInstance().GetMysqlDb()
	if err := db.Where("username = ? and id = ?", username.Username, ctx.Params().Get("id")).Find(&note).Error; err != nil {
		logrus.Errorln("sql执行失败：", err)
	}
	if utils.DataIsNil(note) {
		ctx.StatusCode(iris.StatusInternalServerError)
		ctx.SetErr(errors.New("not found"))
		return
	}
	if err := db.Delete(&note).Error; err != nil {
		logrus.Errorln("sql执行失败：", err)
	}
	err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", "success"))
	if utils.ErrHandle(ctx, err) {
		return
	}
}

func updateNote(ctx iris.Context) {
	username := utils.GetLoginUser(ctx)
	if utils.DataIsNil(username) {
		return
	}
	var note model.UserNotes
	db := database.GetInstance().GetMysqlDb()
	if err := db.Where("username = ? and id = ?", username.Username, ctx.Params().Get("id")).Find(&note).Error; err != nil {
		logrus.Errorln("sql执行失败：", err)
	}
	if utils.DataIsNil(note) {
		ctx.StatusCode(iris.StatusInternalServerError)
		ctx.SetErr(errors.New("not found"))
		return
	}
	var newNote noteParam
	err := ctx.ReadJSON(&newNote)
	if utils.ErrHandle(ctx, err) {
		return
	}
	if err1 := db.Model(&note).Updates(model.UserNotes{
		Content: newNote.Content,
	}).Error; err1 != nil {
		logrus.Errorln("sql执行失败：", err)
	}
	err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", "success"))
	if utils.ErrHandle(ctx, err) {
		return
	}
}

func uploadNoteFile(ctx iris.Context) {
	username := utils.GetLoginUser(ctx)
	if utils.DataIsNil(username) {
		return
	}
	noteId := ctx.Params().Get("id")
	userPath := fmt.Sprintf("./upload-note/%s/%s", username.Username, noteId)
	if !utils.FileIsExist(userPath) {
		err := os.MkdirAll(userPath, 0755)
		if utils.ErrHandle(ctx, err) {
			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)
	filePath := fmt.Sprintf("%s/%s", userPath, info.Filename)
	_, err = ctx.SaveFormFile(info, filePath)
	if utils.ErrHandle(ctx, err) {
		return
	}
	err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", fmt.Sprintf("/api/notes/%s/file/%s", noteId, info.Filename)))
	if utils.ErrHandle(ctx, err) {
		return
	}
}

func getNoteFile(ctx iris.Context) {
	noteId := ctx.Params().Get("id")
	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
	}
	filename := ctx.Params().Get("filename")
	userPath := fmt.Sprintf("./upload-note/%s/%s/%s", userToken.Username, noteId, filename)
	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", userPath[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
}
