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

package ctrl_v1

import (
	"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"
	"time"

	"gd_management_gateway/common.in/httper"
	"gd_management_gateway/common.in/task"
	"gd_management_gateway/common.in/utils"
	"github.com/astaxie/beego"
	"go.uber.org/zap"
	"golang.org/x/net/context"
)

// 用户行为日志
type ActionLogController struct {
	metadata interface{} // 中继元数据
	beego.Controller
	LogID string
}

// @Title add base api
// @Description 添加基础api
// @Param   token    header   string true "token"
// @Param   uid    header   string true "uid"
// @Param	search	query	string	false	"搜索"
// @Param	page_num	query	int	false	"页码"
// @Param	page_size	query	int	false	"每页条数"
// @Success 200 	{object} params.param_v1_0.GetActionLogResp "响应信息"
// @Failure 500 	服务器错误
// @router / [get]
func (p *ActionLogController) GetActionLog() {
	p.LogID = fmt.Sprintf("ManagementAddBaseApi[%d]", time.Now().UnixNano())

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

	handleDataTask := func() error {
		mreq := gd_admin.GetLogReq{
			Search:   req.Search,
			PageNum:  req.PageNum,
			PageSize: req.PageSize,
		}

		reply, err := rpc_apis.Admin.GetActionLog(utils.NewContextFromBeegoCtx(p.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "Admin.GetActionLog"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}

		resp := param_v1_0.GetActionLogResp{
			SimpleResp: param_base.SimpleResp{
				Code: 0,
				Msg:  "SUCCESS",
			},
			Data: reply,
		}

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

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

// AddActionLog 添加用户行为日志
func AddActionLog(req gd_admin.AddActionLogReq) error {
	if _, err := rpc_apis.Admin.AddActionLog(context.Background(), &req); err != nil {
		l.Error("rpc",
			zap.String("call", "DataApiAddApi"),
			zap.String("args", utils.MarshalJsonString(req)),
			zap.String("error", err.Error()))
		return err
	}
	return nil
}
