<template>
  <div v-if="getIsShow" class="tableAction" :style="`justify-content: ${getAlign}`">
    <template v-for="(action, index) in getActions" :key="`${index}-${action.label}`">
      <n-button
        v-if="!action.type || action.type === 'button'"
        class="tableAction__item"
        v-bind="action.props"
      >{{ action.label }}</n-button>
      <n-popconfirm
        v-if="action.type === 'popconfirm'"
        v-bind="action.props"
      >
        <template #trigger>
          <n-button v-bind="action.ButtonProps" class="tableAction__item">{{ action.label }}</n-button>
        </template>
        {{ action.tip }}
      </n-popconfirm>
    </template>
  </div>
</template>

<script>
import { defineComponent, computed, toRaw, reactive } from 'vue'
import { usePermissionStore } from '@/store/modules/permission'
export default defineComponent({
  name: 'TableAction',
  props: {
    actions: {
      type: Array,
      default: null,
      required: true
    },
    align: {
      type: String,
      default: 'center',
      validator: (value) => {
        return ['left', 'right', 'center'].indexOf(value) !== -1
      }
    },
    show: {
      type: Boolean,
      default: true
    }
  },
  setup(props, { emit }) {
    const permissionStore = usePermissionStore()
    const data = reactive({
      permissionList: permissionStore.accessPermissionCodes
    })

    const getPermissionLabel = (code) => {
      return permissionStore.accessPermissions.find((item) => {
        return item.code === code
      })?.name || ''
    }

    const getActions = computed(() => {
      return (toRaw(props.actions) || [])
        .filter((action) => {
          if (!Object.keys(action).includes('show')) {
            action.show = Object.keys(action).includes('hidden') ? !action.hidden : true
          }
          action.label = action.label || getPermissionLabel(action.auth)
          return (data.permissionList.includes(action.auth) || action.auth === '') && action.show
        })
    })

    const getAlign = computed(() => {
      return toRaw(props.align)
    })

    const getIsShow = computed(() => {
      return toRaw(props.show)
    })

    return {
      getActions,
      getAlign,
      getIsShow
    }
  }
})

</script>
<style scoped lang='scss'>
.tableAction{
  display: flex;
  align-items: center;
  .tableAction__item{
    margin: 0 5px;
  }
  // justify-content: center;
}
</style>
