package models

import (
	"LAPP_LF_MOM_BACKEND/db"
	"LAPP_LF_MOM_BACKEND/utils"
	"fmt"
	"log"
)

/***
*CreateBy:lou
*Date:2020/5/15
*TableName:角色关联表
**********/

type RoleMenu struct {
	RoleId         int    `xorm:"int(11) pk comment('角色ID')" form:"role_id" json:"role_id"`
	MenuId         int    `xorm:"int(11) pk comment('菜单ID')" form:"menu_id" json:"menu_id"`
	RoleName       string `xorm:"comment('角色代码') VARCHAR(14)" form:"rolename" json:"rolename"`
	Createtime     string `xorm:"comment('创建时间') VARCHAR(14)" form:"createtime" json:"createtime"`
	Lastmodifytime string `xorm:"comment('最近一次更新时间') VARCHAR(14)" form:"lastmodifytime" json:"lastmodifytime"`
	Lastmodify     string `xorm:"comment('最近一次更新人员') VARCHAR(40)" form:"lastmodify" json:"lastmodify"`
}

type MenuPath struct {
	Path string `json:"path"`
}

func (rm *RoleMenu) TableName() string {
	return "role_menu"
}

func (rm *RoleMenu) Get() ([]RoleMenu, error) {
	var r []RoleMenu
	e := db.Eloquent.Master()
	table := e.Table("role_menu")
	if rm.RoleId != 0 {
		table = table.Where("role_id = ?", rm.RoleId)

	}
	if _, err := table.Get(&r); err != nil {
		return nil, err
	}
	return r, nil
}

func (rm *RoleMenu) GetPermis() ([]string, error) {
	var r []Menu

	e := db.Eloquent.Master()
	err := e.SQL("select menu.permission from menu left join role_menu on role_menu.menu_id=menu.menu_id where role_menu.role_id=? and menu.menu_type in ('F','C')", rm.RoleId).Find(&r)

	if err != nil {
		return nil, err
	}
	var list []string
	for i := 0; i < len(r); i++ {
		list = append(list, r[i].Permission)
	}
	return list, nil
}

func (rm *RoleMenu) GetIDS() ([]MenuPath, error) {
	var r []MenuPath
	e := db.Eloquent.Master()
	table := e.Select("menu.path").Table("role_menu")
	table = table.Join("LEFT", "roletab", "roletab.role_id=role_menu.role_id")
	table = table.Join("LEFT", "menu", "menu.id=role_menu.menu_id")
	table = table.Where("roletab.role_name = ? and menu.type=1", rm.RoleName)
	if err := table.Find(&r); err != nil {
		return nil, err
	}
	return r, nil
}
func (rm *RoleMenu) DeleteRoleMenu(roleId int) (bool, error) {
	e := db.Eloquent.Master()
	if _, err := e.Table("role_menu").Where("role_id = ?", roleId).Delete(&RoleMenu{}); err != nil {
		return false, err
	}
	var role Roletab
	if _, err := e.Table("roletab").Where("role_id = ?", roleId).Get(&role); err != nil {
		return false, err
	}
	//删除casbin_rule
	sql3 := "delete from casbin_rule where v0= '" + role.RoleKey + "'"
	_, err := e.Exec(sql3)
	if err != nil {
		return false, err
	}
	return true, nil

}

func (rm *RoleMenu) BatchDeleteRoleMenu(roleIds []int, rolekeys []string) (bool, error) {
	e := db.Eloquent.Master()
	roleIds_str := utils.IDsToStringIn(roleIds)
	if _, err := e.Table("role_menu").Where("role_id in (" + roleIds_str + ")").Delete(&RoleMenu{}); err != nil {
		return false, err
	}
	//添加到casbin_rule中
	str := utils.IDsToStrings(rolekeys)
	sql := "delete from casbin_rule where v0 in (" + str + ")"
	_, err := e.Exec(sql)
	if err != nil {
		return false, err
	}
	return true, nil

}
func (rm *RoleMenu) Insert(roleId int, menuId []int) (bool, error) {
	var role Roletab
	e := db.Eloquent.Master()
	if _, err := e.Table("roletab").Where("role_id = ?", roleId).Get(&role); err != nil {
		log.Printf("查询错误err1:%v", err)
		return false, err
	}
	var menu []Menu
	menustr := utils.IDsToStringIn(menuId)

	log.Println(menustr)
	if err := e.SQL("select * from menu where menu_id in (" + menustr + ")").Find(&menu); err != nil {
		return false, err
	}
	//ORM不支持批量插入所以需要拼接 sql 串
	sql := "INSERT INTO `role_menu` (`role_id`,`menu_id`,`role_name`) VALUES "

	sql2 := "INSERT INTO casbin_rule  (`p_type`,`v0`,`v1`,`v2`) VALUES "
	for i := 0; i < len(menu); i++ {
		if len(menu)-1 == i {
			//最后一条数据 以分号结尾
			sql += fmt.Sprintf("(%d,%d,'%s')", role.RoleId, menu[i].MenuId, role.RoleKey)
			if menu[i].MenuType == "A" {
				sql2 += fmt.Sprintf("('p','%s','%s','%s');", role.RoleKey, menu[i].Path, menu[i].Action)
			} else {
				sql2 = sql2[:len(sql2)- 1]
			}
		} else {
			sql += fmt.Sprintf("(%d,%d,'%s'),", role.RoleId, menu[i].MenuId, role.RoleKey)
			if menu[i].MenuType == "A" {
				sql2 += fmt.Sprintf("('p','%s','%s','%s'),", role.RoleKey, menu[i].Path, menu[i].Action)
			}
		}
	}
	_, err := e.Exec(sql)
	if err != nil {
		log.Printf("role添加错误:%v", err)
	}
	_, err = e.Exec(sql2)
	if err != nil {
		log.Printf("casbin_role添加错误:%v", err)
	}
	return true, nil
}
func (rm *RoleMenu) Delete(RoleId string, MenuID string) (bool, error) {
	e := db.Eloquent.Master()
	rm.RoleId = utils.ValueToInt(RoleId, 0)
	table := e.Table("role_menu").Where("role_id = ?", RoleId)
	if MenuID != "" {
		table = table.Where("menu_id = ?", MenuID)
	}
	if _, err := table.Delete(&rm); err != nil {
		return false, err
	}
	return true, nil
}
