package controllers

import (
	"net/http"
	"spaceofcheng/services/models/model"
	"spaceofcheng/services/utils"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/config"
)

//BaseController 基础controller
type BaseController struct {
	beego.Controller
	Context  *utils.Context
	Configer map[string]config.Configer
	RunMode  string
}

//Prepare 继承beego的
func (c *BaseController) Prepare() {
	// 读取配置文件
	c.initConfig()

	// 初始化上下文
	c.initContext()

	// 鉴权
	c.authenticate()

	// 路由对应的实际 Controller 初始化
	c.initController()
}

// ResponseJSON 返回JSON数据
func (c *BaseController) ResponseJSON(data interface{}) {
	c.ResponseData(data, "", http.StatusOK)
}

// ResponseError 返回错误
func (c *BaseController) ResponseError(err error, code ...int) {
	if len(code) > 0 {
		c.ResponseData(nil, err, code[0])
	}

	c.ResponseData(nil, err, http.StatusBadRequest)
}

// ResponseData 自定义的JSON返回
func (c *BaseController) ResponseData(data interface{}, msg interface{}, code int) {
	status := code
	c.destroyContext(status < http.StatusMultipleChoices)

	sendMessage := ""
	switch msgVal := msg.(type) {
	case error:
		sendMessage = msgVal.Error()
	case string:
		sendMessage = msgVal
	default:
		sendMessage = ""
	}

	c.Data["json"] = JSONMessage{status, sendMessage, data}
	c.Ctx.Output.Header("Access-Control-Expose-Headers", "X-Token")

	c.crosPolicy()
	c.ServeJSON()
	c.StopRun()
}

// Options 解决跨域先发送 options
func (c *BaseController) Options() {
	c.ResponseJSON("")
}

// crosPolicy 跨域策略
func (c *BaseController) crosPolicy() {
	runMode := beego.AppConfig.String("runmode")
	allowMode := beego.AppConfig.String("cros::allowMode")
	allowMethods := beego.AppConfig.String("cros::allowMethods")
	allowOrigin := beego.AppConfig.String("cros::allowOrigin")
	allowCredentials := beego.AppConfig.String("cros::allowCredentials")

	if runMode == allowMode {
		c.Ctx.Output.Header("Access-Control-Allow-Origin", allowOrigin)
		c.Ctx.Output.Header("Access-Control-Allow-Methods", allowMethods)
		c.Ctx.Output.Header("Access-Control-Allow-Credentials", allowCredentials)
		c.Ctx.Output.Header("Access-Control-Allow-Headers", "X-Token,Authorization")
	}
}

// initAppController 执行当前路由请求对应的 Controller 初始化
func (c *BaseController) initController() {
	if ctrl, ok := c.AppController.(ControllerInterface); ok {
		ctrl.Constructor()
	}
}

// GetCaseIDs 获取案场IDs
func (c *BaseController) GetCaseIDs(cases []model.SysUserCase) string {
	caseIDs := ""
	for _, value := range cases {
		if caseIDs != "" {
			caseIDs = caseIDs + ","
		}
		caseIDs = caseIDs + value.CaseId
	}
	return caseIDs
}
