package system

import (
	"eta/eta_api/utils"
	"github.com/beego/beego/v2/client/orm"
	"github.com/rdlucklib/rdluck_tools/paging"
	"time"
)

type SysRoleAddReq struct {
	RoleName string `description:"角色名称"`
	RoleType string `description:"角色类型"`
}

type SysRole struct {
	RoleId       int       `orm:"column(role_id);pk" description:"角色ID"`
	RoleName     string    `description:"角色名称"`
	RoleType     string    `description:"角色类型"`
	RoleTypeCode string    `description:"角色类型编码"`
	CreateTime   time.Time `description:"创建时间"`
	ModifyTime   time.Time
}

type SysRoleItem struct {
	RoleId       int       `orm:"column(role_id);pk" description:"角色ID"`
	RoleName     string    `description:"角色名称"`
	RoleType     string    `description:"角色类型"`
	RoleTypeCode string    `description:"角色类型编码"`
	CreateTime   time.Time `description:"创建时间"`
	RoleLevel    int       `description:"角色等级：0-表示一级角色，每个账号只能绑定一个一级角色 ，1-表示二级角色，每个账号可以绑定多个二级 角色"`
}

func GetSysRoleCount(roleName string) (count int, err error) {
	sql := `SELECT COUNT(1) AS count FROM sys_role WHERE role_name=? `
	o := orm.NewOrm()
	err = o.Raw(sql, roleName).QueryRow(&count)
	return
}

func AddSysRole(item *SysRole) (lastId int64, err error) {
	o := orm.NewOrm()
	lastId, err = o.Insert(item)
	return
}

type SysRoleEditReq struct {
	RoleId   int    `description:"角色ID"`
	RoleName string `description:"角色名称"`
	RoleType string `description:"角色类型"`
}

func GetSysRoleById(roleId int) (item *SysRoleItem, err error) {
	sql := `SELECT * FROM sys_role WHERE role_id=? `
	o := orm.NewOrm()
	err = o.Raw(sql, roleId).QueryRow(&item)
	return
}

func GetSysRoleByName(roleName string) (item *SysRoleItem, err error) {
	sql := `SELECT * FROM sys_role WHERE role_name=? `
	o := orm.NewOrm()
	err = o.Raw(sql, roleName).QueryRow(&item)
	return
}

// GetSysRoleByRoleTypeCode role_type_code
func GetSysRoleByRoleTypeCode(roleTypeCode string) (item *SysRoleItem, err error) {
	sql := `SELECT * FROM sys_role WHERE role_type_code=? `
	o := orm.NewOrm()
	err = o.Raw(sql, roleTypeCode).QueryRow(&item)
	return
}
func ModifySysRole(roleName, roleType, roleTypeCode string, groupId int) (err error) {
	sql := `UPDATE sys_role SET role_name=?,role_type=?,role_type_code=?,modify_time=NOW() WHERE role_id=? `
	o := orm.NewOrm()
	_, err = o.Raw(sql, roleName, roleType, roleTypeCode, groupId).Exec()
	return
}

type SysRoleDeleteReq struct {
	RoleId int `description:"角色ID"`
}

func DeleteSysRole(roleId int) (err error) {
	sql := `DELETE FROM sys_role WHERE role_id=? `
	o := orm.NewOrm()
	_, err = o.Raw(sql, roleId).Exec()
	return
}

func GetSysRoleListCount(condition string, pars []interface{}) (count int, err error) {
	o := orm.NewOrm()
	sql := `SELECT COUNT(1) AS count FROM sys_role WHERE 1=1 `
	if condition != "" {
		sql += condition
	}
	err = o.Raw(sql, pars).QueryRow(&count)
	return
}

func GetSysRoleList(condition string, pars []interface{}, startSize, pageSize int) (items []*SysRoleItem, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM sys_role WHERE 1=1 `
	if condition != "" {
		sql += condition
	}
	sql += `ORDER BY modify_time DESC LIMIT ?,?`
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

type SysRoleListResp struct {
	List   []*SysRoleItem
	Paging *paging.PagingItem `description:"分页数据"`
}

type RoleMenu struct {
	MenuId int    `description:"导航唯一标识"`
	Name   string `description:"导航名称"`
}

type RoleMenuList struct {
	MenuId    int    `description:"导航唯一标识"`
	Name      string `description:"导航名称"`
	Child     []*RoleMenu
	CheckList []int
}

type RoleMenuListResp struct {
	List []*RoleMenuList
}

func GetRoleMenuList() (items []*RoleMenuList, err error) {
	sql := `SELECT * FROM sys_menu WHERE parent_id=0 ORDER BY sort ASC `
	_, err = orm.NewOrm().Raw(sql).QueryRows(&items)
	return
}

func GetRoleMenuByParentId(parentId int) (items []*RoleMenu, err error) {
	sql := `SELECT * FROM sys_menu WHERE parent_id=? ORDER BY sort ASC `
	_, err = orm.NewOrm().Raw(sql, parentId).QueryRows(&items)
	return
}

func GetCheckListRoleMenu(roleId, parentId int) (items []*RoleMenuList, err error) {
	sql := ` SELECT b.menu_id FROM sys_role_menu AS a
				INNER JOIN sys_menu AS b ON a.menu_id=b.menu_id
				WHERE a.role_id=? AND a.type = 0
				AND b.parent_id=? `
	_, err = orm.NewOrm().Raw(sql, roleId, parentId).QueryRows(&items)
	return
}

type RoleMenusAddReq struct {
	RoleId          int    `description:"角色ID"`
	MenuIdStr       string `description:"MenuId,多个用英文逗号隔开"`
	MenuButtonIdStr string `description:"menu_button_id,多个用英文逗号隔开"`
}

func DeleteRoleMenuByRoleId(roleId int) (err error) {
	sql := `DELETE FROM sys_role_menu WHERE role_id=? `
	_, err = orm.NewOrm().Raw(sql, roleId).Exec()
	return

}

type SysRoleMenu struct {
	RoleMenuId int `orm:"column(role_menu_id);pk" description:"关联id"`
	RoleId     int
	MenuId     int
	Type       int `description:"类型：0-全选；1-半选（此字段仅用于前端的回显）"`
}

func AddSysRoleMenu(item *SysRoleMenu) (lastId int64, err error) {
	o := orm.NewOrm()
	lastId, err = o.Insert(item)
	return
}

// CreateMultiSysRoleMenu 删除并新增角色权限
func CreateMultiSysRoleMenu(roleId int, items []*SysRoleMenu) (err error) {
	if roleId == 0 {
		return
	}
	o := orm.NewOrm()
	tx, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = tx.Rollback()
			return
		}
		_ = tx.Commit()
	}()

	sql := `DELETE FROM sys_role_menu WHERE role_id = ?`
	_, err = tx.Raw(sql, roleId).Exec()
	if err != nil {
		return
	}

	if len(items) > 0 {
		_, err = tx.InsertMulti(len(items), items)
	}
	return
}

func GetSysRoleAll(levelFlag bool) (items []*SysRoleItem, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM sys_role WHERE 1=1`
	if levelFlag {
		sql += ` and role_level = 0`
	}
	sql += ` ORDER BY create_time DESC `
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

type SysRoleAllResp struct {
	List []*SysRoleItem
}

// GetEnglishAuthRoleIds 获取英文权限角色IDs
func GetEnglishAuthRoleIds(roleCodes []string) (roleIds []int, err error) {
	if len(roleCodes) == 0 {
		return
	}
	o := orm.NewOrm()
	sql := `SELECT role_id FROM sys_role WHERE role_type_code IN (` + utils.GetOrmInReplace(len(roleCodes)) + `)`
	_, err = o.Raw(sql, roleCodes).QueryRows(&roleIds)
	return
}

// GetSysRoleMenuByRoleId 获取角色关联菜单
func GetSysRoleMenuByRoleId(roleId int) (items []*SysRoleMenu, err error) {
	sql := `SELECT
				*
			FROM
				sys_role_menu
			WHERE
				role_id = ?`
	_, err = orm.NewOrm().Raw(sql, roleId).QueryRows(&items)
	return
}

// GetEnglishAuthRoleItems 获取英文权限角色
func GetEnglishAuthRoleItems(roleCodes []string) (items []*SysRole, err error) {
	if len(roleCodes) == 0 {
		return
	}
	o := orm.NewOrm()
	sql := `SELECT * FROM sys_role WHERE role_type_code IN (` + utils.GetOrmInReplace(len(roleCodes)) + `)`
	_, err = o.Raw(sql, roleCodes).QueryRows(&items)
	return
}
