import { useState } from "react";
import { useSelector } from "react-redux";

/**
 * @author {温华}
 * @description 用于包裹需要鉴权的行为按钮
 * @example <Authenticationbtn permission="["system:list"]"><Button>新增</Button></Authenticationbtn>
 * @param {permission: string[]} 
 */

export default function Authenticationbtn({ permission, children }: any) {
  // 还需从缓存中获取用户权限数组
  const authInfo = useSelector((store: any) => store.auth)
  const [visible, setVisible] = useState(true)
  const allPermission: string = "*:*:*"
  const authPermissions: Array<string> = authInfo.permissions
  if(permission && permission instanceof Array && permission.length > 0) {
    const permissiosFlag = permission
    const hasPermission = authPermissions.some((perm: string)=>{
      return allPermission === perm || permissiosFlag.includes(perm)
    })
    setVisible(hasPermission)
  }

  if(visible) return children
  return null
}