package controller

import (
	"github.com/gin-gonic/gin"
	"github.com/mhaya/game/game_cluster/internal/code"
	"github.com/mhaya/game/game_cluster/nodes/webadmin/common"
	"github.com/mhaya/game/game_cluster/nodes/webadmin/entity"
	"github.com/mhaya/game/game_cluster/nodes/webadmin/service"
)

type Admin struct {
	sev *service.Admin
}

func NewAdmin() *Admin {
	return &Admin{
		sev: service.NewAdmin(),
	}
}

// Login login
func (a *Admin) Login(ctx *gin.Context) {
	var req entity.AdminLoginReq
	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.PackOkResult(ctx, code.ParamError)
		return
	}

	resp, err := a.sev.Login(ctx, req.Username, req.Password)
	if err != nil {
		common.PackOkResult(ctx, err.Code)
		return
	}

	common.PackOkResult(ctx, code.OK, resp)
}

// Add 添加管理员
func (a *Admin) Add(ctx *gin.Context) {
	var req entity.AdminAddReq
	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.PackOkResult(ctx, code.ParamError)
		return
	}

	err := a.sev.Add(ctx, req.Username, req.Password, req.RealName, req.Pid, req.RoleId, req.Status)
	if err != nil {
		common.PackOkResult(ctx, err.Code)
		return
	}

	common.PackOkResult(ctx, code.OK, nil)
}

// ChangePassword 修改密码
func (a *Admin) ChangePassword(ctx *gin.Context) {
	var req entity.AdminChangePasswordReq
	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.PackOkResult(ctx, code.ParamError)
		return
	}

	err := a.sev.ChangePassword(ctx, req.Username, req.Password)
	if err != nil {
		common.PackOkResult(ctx, err.Code)
		return
	}

	common.PackOkResult(ctx, code.OK, nil)
}

// Del 删除管理员
func (a *Admin) Del(ctx *gin.Context) {
	var req entity.AdminDelReq
	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.PackOkResult(ctx, code.ParamError)
		return
	}

	err := a.sev.Delete(ctx, req.Username)
	if err != nil {
		common.PackOkResult(ctx, err.Code)
		return
	}

	common.PackOkResult(ctx, code.OK, nil)
}

// FindAll 获取所有管理员
func (a *Admin) FindAll(ctx *gin.Context) {
	var req entity.AdminFindAllReq
	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.PackOkResult(ctx, code.ParamError)
		return
	}

	resp, err := a.sev.FindAll(ctx, req)
	if err != nil {
		common.PackOkResult(ctx, err.Code)
		return
	}

	common.PackOkResult(ctx, code.OK, resp)
}

func (a *Admin) UpdateStatus(ctx *gin.Context) {
	var req entity.AdminUpdateStatusReq
	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.PackOkResult(ctx, code.ParamError)
		return
	}

	err := a.sev.UpdateStatus(ctx, req.Username, req.Status)
	if err != nil {
		common.PackOkResult(ctx, err.Code)
		return
	}

	common.PackOkResult(ctx, code.OK, nil)
}

// GetServerStatus

func (a *Admin) GetServerStatus(ctx *gin.Context) {
	resp, err := a.sev.GetServerStatus(ctx)
	if err != nil {
		common.PackOkResult(ctx, err.Code)
		return
	}

	common.PackOkResult(ctx, code.OK, resp)
}
