<!--权限按钮组件-->
<template>
  <el-button v-if="hasPerms()" :size="size" :type="type"
    :loading="loading"
    :disabled="disabled"
    :title="title"
    :icon="icon"
    @click="handleClick">
    {{label}}
  </el-button>
</template>

<script>
// 水波纹指令
// import waves from './waves.js'
export default {
  name: 'AuthButton',
  inheritAttrs: false,
  // directives: {
  //   waves
  // },
  props: {
    menuCode: { // 所属菜单Code-->全局唯一
      type: String,
      default: null
    },
    label: { // 按钮显示文本
      type: String,
      default: ''
    },
    size: { // 按钮尺寸
      type: String,
      default: 'mini'
    },
    type: { // 按钮类型
      type: String,
      default: null
    },
    loading: { // 按钮加载标识
      type: Boolean,
      default: false
    },
    disabled: { // 按钮是否禁用
      type: Boolean,
      default: false
    },
    perms: { // 按钮权限标识，外部使用者传入
      type: String,
      default: null
    },
    icon: { // 图标
      type: String,
      default: ''
    },
    // 是否开启鉴权，默认开启
    openPerms: {
      type: Boolean,
      default () {
        return false
      }
    },
    title: { // 按钮提示
      type: String,
      default: ''
    }
  },
  data () {
    return {
    }
  },
  methods: {
    handleClick: function () {
      // 按钮操作处理函数
      this.$emit('click', {})
    },
    hasPerms: function () {
      // 根据权限标识进行权限判断
      return !this.openPerms || this.hasOperatorPermission(this.menuCode, this.perms)
    },
    hasOperatorPermission (menuId, perms) {
      let hasPermission = false
      if (!menuId || !perms) {
        return hasPermission
      }
      let curMenu = this.getMenuByMenuId(this.$store.getters.menus, menuId)
      if (curMenu && curMenu.operationList && curMenu.operationList.length > 0) {
        curMenu.operationList.some(op => {
          if (perms === op.operationCode && op.authStatus === 0) { // authStatus：授权状态(0：已授权 / 1：未授权 / 2：过期)
            hasPermission = true
          }
        })
      }
      return hasPermission
    },
    getMenuByMenuId (menus, menuId) {
      if (!menus || !menuId) {
        return null
      }
      let curMenu = null
      for (var menu of menus) {
        if (menuId === menu.keyId) {
          return menu
        } else if (menu.children && menu.children.length > 0) {
          curMenu = this.getMenuByMenuId(menu.children, menuId)
          if (curMenu) {
            return curMenu
          }
        }
      }
      return null
    }
  },
  mounted () {
  }
}
</script>
