package controllers

import (
	"sparrow/pkg/models"
	"sparrow/services/knowoapi/services"

	"github.com/kataras/iris/v12"
)

// RoleController role
type RoleController struct {
	Ctx     iris.Context
	Service services.RoleService
	Token   Token
}

// Post “
// POST /admin/role
func (a *RoleController) Post() {
	role := new(models.Role)
	if err := parseBody(a.Ctx, role); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	if err := a.Service.Create(role); err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, role)
}

// Delete delete
// DELETE /admin/role
func (a *RoleController) Delete() {
	role := new(models.Role)
	// ID为1的不允许删除
	if role.ID == 1 {
		responseError(a.Ctx, ErrNormal, "普通用户角色不允许删除")
		return
	}
	if err := parseBody(a.Ctx, role); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	if err := a.Service.Delete(role); err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, role)
}

// Put delPutete
// Put /admin/role
func (a *RoleController) Put() {
	role := new(models.Role)
	if err := parseBody(a.Ctx, role); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	if err := a.Service.Update(role); err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, role)
}

// Get get roles
// GET /admin/role?pi=&ps=&name
func (a *RoleController) Get() {
	pi, err := a.Ctx.URLParamInt("pi")
	if err != nil {
		badRequest(a.Ctx, err)
		return
	}
	ps, err := a.Ctx.URLParamInt("ps")
	if err != nil {
		badRequest(a.Ctx, err)
		return
	}
	name := a.Ctx.URLParam("name")
	datas, total, err := a.Service.QueryAll(pi, ps, name)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}

	done(a.Ctx, map[string]interface{}{
		"list":  datas,
		"total": total,
	})
}

// GetBy get role by id
func (a *RoleController) GetBy(id int) {
	role, err := a.Service.QueryRole(id)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, role)
}
