// Copyright 2019 getensh.com. All rights reserved.
// Use of this source code is governed by getensh.com.

package ctrl_v1

import (
	"gd_management_gateway/common.in/httper"
	"gd_management_gateway/common.in/task"
	"gd_management_gateway/common.in/utils"
	"gd_management_gateway/errors"
	"gd_management_gateway/params/param_base"
	"gd_management_gateway/params/param_v1_0"
	"gd_management_gateway/rpc_apis"
	"gd_management_gateway/rpc_apis/gd_admin"
	"fmt"
	"github.com/astaxie/beego"
	"go.uber.org/zap"
	"time"
)

// Operations about auth api
type AuthController struct {
	metadata interface{} // 中继元数据
	beego.Controller
	LogID string
}

// @Title oss sts 授权
// @Description oss sts 授权
// @Param   token    header   string true "token"
// @Param   uid    header   int64 true "admin id"
// @Success 200 	{object} params.param_v1_0.AuthGetOSSInfoResp "响应信息"
// @Failure 500 	服务器错误
// @router /oss [get]
func (u *AuthController) AuthGetOSSInfo() {
	u.LogID = fmt.Sprintf("AdminRegister[%d]", time.Now().UnixNano())

	req := &param_v1_0.AuthGetOSSInfoReq{}
	getParamsTask := func() error {
		httper.FillRequireParams(u.Ctx, req, u.LogID)
		return nil
	}

	handleTokenCheck := func() error {
		uid, _, err := utils.ParseToken(req.Token)
		if err != nil {
			return err
		}

		if uid != req.Uid {
			return errors.UserTokenillegality
		}

		return nil
	}

	handleDataTask := func() error {
		mreq := gd_admin.AuthGetOSSInfoReq{
			Uid: req.Uid,
		}

		reply, err := rpc_apis.Admin.AuthGetOSSInfo(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "AuthGetOSSInfo"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}
		resp := param_v1_0.AuthGetOSSInfoResp{
			SimpleResp: param_base.SimpleResp{
				Code: 0,
				Msg:  "SUCCESS",
			},
			Data: reply,
		}

		httper.JSON(u.Ctx, resp, u.LogID)
		return nil
	}

	// 执行以上定义的任务
	task.Do(&task.PanicRecover{
		Ctx:   u.Ctx,
		LogID: u.LogID}, u.Ctx,
		getParamsTask, handleTokenCheck, handleDataTask,
	)
}
