package system

import (
	"context"
	"time"

	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/logs"
)

type RoleInfo struct {
	Id             int
	RoleName       string
	RoleUid        string
	ShowFirstMenu  string
	ShowFirstUid   string
	ShowSecondMenu string
	ShowSecondUid  string
	ShowPower      string
	ShowPowerUid   string
	Creater        string
	Status         string
	Remark         string
	CreateTime     time.Time
	UpdateTime     time.Time
}

const ROLE_INFO = "role_info"

func GetRoleLenByMap(ctx context.Context, params map[string]string) int {
	o := orm.NewOrm()
	qs := o.QueryTable(ROLE_INFO)
	for k, v := range params {
		if len(v) > 0 {
			qs = qs.Filter(k, v)
		}
	}
	cnt, err := qs.CountWithCtx(ctx)
	if err != nil {
		logs.Error("get role len by map fail: ", err)
	}
	return int(cnt)
}

func GetRole(ctx context.Context) []RoleInfo {
	o := orm.NewOrm()
	var roleInfo []RoleInfo
	_, err := o.QueryTable(ROLE_INFO).Limit(-1).OrderBy("-update_time").AllWithCtx(ctx, &roleInfo)
	if err != nil {
		logs.Error("get all role fail: ", err)
	}
	return roleInfo
}

func GetRoleByMap(ctx context.Context, params map[string]string, display, offset int) []RoleInfo {
	o := orm.NewOrm()
	var roleInfo []RoleInfo
	qs := o.QueryTable(ROLE_INFO)
	for k, v := range params {
		if len(v) > 0 {
			qs = qs.Filter(k, v)
		}
	}
	_, err := qs.Limit(display, offset).OrderBy("-update_time").AllWithCtx(ctx, &roleInfo)
	if err != nil {
		logs.Error("get role by map fail: ", err)
	}
	return roleInfo
}

func GetRoleByRoleUid(ctx context.Context, roleUid string) RoleInfo {
	o := orm.NewOrm()
	var roleInfo RoleInfo
	_, err := o.QueryTable(ROLE_INFO).Filter("role_uid", roleUid).Limit(1).AllWithCtx(ctx, &roleInfo)

	if err != nil {
		logs.Error("get role by role uid fail: ", err)
	}
	return roleInfo
}

func RoleNameExists(ctx context.Context, roleName string) bool {
	o := orm.NewOrm()
	exists := o.QueryTable(ROLE_INFO).Filter("role_name", roleName).ExistWithCtx(ctx)
	return exists
}

func InsertRole(ctx context.Context, roleInfo RoleInfo) bool {
	o := orm.NewOrm()
	_, err := o.InsertWithCtx(ctx, &roleInfo)
	if err != nil {
		logs.Error("insert role fail: ", err)
		return false
	}
	return true
}

func DeleteRoleByRoleUid(ctx context.Context, roleUid string) bool {
	o := orm.NewOrm()
	_, err := o.QueryTable(ROLE_INFO).Filter("role_uid", roleUid).DeleteWithCtx(ctx)
	if err != nil {
		logs.Error("delete role by role uid fail: ", err)
		return false
	}
	return true
}

func UpdateRoleInfo(ctx context.Context, roleInfo RoleInfo) bool {
	o := orm.NewOrm()
	_, err := o.UpdateWithCtx(ctx, &roleInfo)

	if err != nil {
		logs.Error("update role info fail: ", err)
		return false
	}
	return true
}
