package base

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"net/http"
	config2 "nginx-ui/server/config"
	"nginx-ui/server/models"
	"nginx-ui/server/utils"
	"strings"
)

type ErrorController struct {
	beego.Controller
	WebPath string
	WebDir  string
}

func getWebPath() string {
	config := config2.Config
	p := config.ContextPath
	if !strings.HasPrefix(p, "/") {
		p = "/" + p
	}
	if !strings.HasSuffix(p, "/") {
		p = p + "/"
	}
	return p
}

func (c *ErrorController) Error404() {

	if c.WebPath == "" {
		c.WebPath = getWebPath()
	}
	if c.WebDir == "" {
		c.WebDir = utils.GetStaticDir()
	}

	c.EnableRender = false
	request := c.Ctx.Request

	accept := request.Header.Get("accept")
	logs.Warn("404", request.RequestURI, accept)
	if strings.Contains(accept, "json") {
		c.Ctx.Output.SetStatus(http.StatusOK)
		c.Data["json"] = models.RespData{
			Code: 404,
			Msg:  "API NOT FOUND!",
		}
		c.ServeJSON()
	} else if c.WebPath != request.RequestURI {
		c.EnableRender = true
		//c.Redirect(c.WebPath, http.StatusMovedPermanently)
		// 适配vue的history模式
		c.Ctx.Output.SetStatus(http.StatusOK)
		c.TplName = "index.html"
	} else {
		c.Data["json"] = models.RespData{
			Code: 404,
			Msg:  "Not Found",
		}
		c.ServeJSON()
	}
}