package controllers

import (
	service "doc-service/Service"
	models "doc-service/modes"
	"doc-service/modes/db"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"net/http"
)

type ApiController struct{}

func res(c *gin.Context, code int64, msg string, data interface{}) {
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  msg,
		"data": data,
	})
}

func (con ApiController) Index(c *gin.Context) {
	session := sessions.Default(c)
	session.Options(sessions.Options{
		MaxAge: 3600 * 6,
	})
	session.Set("username", "张三 111")
	_ = session.Save()

	c.JSON(http.StatusOK, gin.H{
		"msg": "我是一个msg",
		"t":   1629788418,
	})
}
func (con ApiController) Userlist(c *gin.Context) {
	c.String(200, "我是一个api接口-Userlist")
}
func (con ApiController) Plist(c *gin.Context) {
	c.String(200, "我是一个api接口-Plist")
}

// 发起文件转换
func (con ApiController) Conversion(c *gin.Context) {
	ret := make(map[string]interface{}, 0)
	ret["errcode"] = 0
	ret["errmsg"] = nil
	ret["base64"] = nil
	req := service.ConversionRequest{}
	req.ProjectName = c.PostForm("project_name")
	req.SourceType = c.PostForm("source_type")
	req.TargetType = c.PostForm("target_type")
	req.SourceURI = c.PostForm("source_url")
	req.TargetURI = c.PostForm("target_url")
	req.IsPrivate = false

	//创建项目
	createErr := service.NewConversion().CreateProject()
	if createErr != nil {
		ret["errmsg"] = createErr.Error()
		ret["errcode"] = 100010
		res(c, http.StatusOK, "成功", ret)
		return
	}

	//执行转换
	result, errs := service.NewConversion().DoConversion(req)
	if errs != nil {
		ret["errmsg"] = errs.Error()
		ret["errcode"] = 100011
	}
	ret["task_id"] = result

	//入库
	insertProject := &db.DocServerProject{}
	insertProject.ProjectName = req.ProjectName
	insertProject.SourceType = req.SourceType
	insertProject.TargetType = req.TargetType
	insertProject.SourceUrl = req.SourceURI
	insertProject.TargetUrl = req.TargetURI
	insertProject.Status = 0
	insertProject.AppId = 1
	insertProject.CreatedAt = models.GetDate()
	insertProject.TaskId = result
	models.DB.Create(insertProject)
	res(c, http.StatusOK, "成功", ret)
}

// 获取转换结果
func (con ApiController) GetTaskProject(c *gin.Context) {
	ret := make(map[string]interface{}, 0)
	req := service.GetTaskRequest{}
	req.ProjectName = c.Query("project_name")
	req.TaskId = c.Query("task_id")
	req.TaskType = c.Query("task_type")
	result, errs := service.NewConversion().GetTaskProject(req)
	if errs != nil {
		ret["errmsg"] = errs.Error()
		ret["errcode"] = 100011
	}
	ret["url"] = result
	res(c, http.StatusOK, "成功", ret)
	return
}
