import store from '@/store'

/**
 * 字符权限校验
 * @param {Array} value 校验值
 * @returns {Boolean}
 */
export function checkPermi(value) {
	console.log("permisssion checkPermi", value)
	if (value && value instanceof Array && value.length > 0) {
		const permissions = store.getters && store.getters.permissions
		console.log("permissions", permissions)
		const permissionDatas = value
		const all_permission = "*:*:*"

		const hasPermission = permissions.some(permission => {
			return all_permission === permission || permissionDatas.includes(permission)
		})

		if (!hasPermission) {
			return false
		}
		return true
	} else {
		console.error(`need roles! Like checkPermi="['system:user:add','system:user:edit']"`)
		return false
	}
}

/**
 * 角色权限校验
 * @param {Array} value 校验值
 * @returns {Boolean}
 */
export function checkRole(value) {
	console.log("permisssion checkRole", value)
	if (value && value instanceof Array && value.length > 0) {
		const roles = store.getters && store.getters.roles
		const permissionRoles = value
		const super_admin = "admin"

		const hasRole = roles.some(role => {
			return super_admin === role || permissionRoles.includes(role)
		})

		if (!hasRole) {
			return false
		}
		return true
	} else {
		console.error(`need roles! Like checkRole="['admin','editor']"`)
		return false
	}
}

/**
 * 权限信息
 * @param {Array} powers 权限信息格式化
 * @returns {Array} 编号集合
 */
export function generatePower(powers) {
	const userPowers = powers.map(power => {
		return power.code
	})
	return userPowers;
}

/** 路由信息格式化 */
export function generateRoute(menus){
  const userRoutes = menus.map(menu => {
    const { parent, icon, component, children = [], path, hidden = false, title, i18n, id,remark } = menu
    const currentMenu = { title,name:component, path, parent,icon,color:remark, children: children.length === 0 ? [] : generateRoute(children) }
    if (children.length <= 0) {
      delete currentMenu.children
    }
    return currentMenu
  })
  return userRoutes
}

/**
 * 获取权限允许的路由信息
 * @param {Array} powers 权限信息格式化
 * @returns {Array} 编号集合
 */
export function getPermissionRoutes(componentName) {
	//todo 从权限文档中找是否有权限，有就添加，没有就不渲染
	// let route = permissionRoutes[componentName];
	// if (route == undefined) route = wmsRoutes[componentName];
	// if (route == undefined) route = permissionRoutes['error-404']
	// return route;
	return componentName;
}