<script setup lang="ts">
import { $t } from '@/locales';
import { useAuth } from '@/hooks/business/auth';

defineOptions({
  name: 'TableHeaderOperation'
});

interface Props {
  itemAlign?: NaiveUI.Align;
  disabledDelete?: boolean;
  loading?: boolean;
  showAddBtn?: boolean;
  showDeleteBtn?: boolean;
  hasPerm?: [string | null | undefined, string | null | undefined]; // 传递空字符串、null、undefined，则不检查权限，默认显示， 第一个新增，第二个删除
}

interface Emits {
  (e: 'add'): void;
  (e: 'delete'): void;
  (e: 'refresh'): void;
}

const { showAddBtn = true, showDeleteBtn = true, hasPerm } = defineProps<Props>();

const emit = defineEmits<Emits>();

const { hasAuth } = useAuth();

const columns = defineModel<NaiveUI.TableColumnCheck[]>('columns', {
  default: () => []
});

function getHasPerm(index: number) {
  if (!hasPerm) return true;
  if (hasPerm[index]) {
    return hasAuth(hasPerm[index]);
  }
  return true;
}

function add() {
  emit('add');
}

function batchDelete() {
  emit('delete');
}

function refresh() {
  emit('refresh');
}
</script>

<template>
  <NSpace :align="itemAlign" wrap justify="end" class="lt-sm:w-200px">
    <slot name="prefix"></slot>
    <slot name="default">
      <NButton v-if="showAddBtn && getHasPerm(0)" size="small" ghost type="primary" @click="add">
        <template #icon>
          <icon-ic-round-plus class="text-icon" />
        </template>
        {{ $t('common.add') }}
      </NButton>
      <NPopconfirm v-if="showDeleteBtn && getHasPerm(1)" @positive-click="batchDelete">
        <template #trigger>
          <NButton size="small" ghost type="error" :disabled="disabledDelete">
            <template #icon>
              <icon-ic-round-delete class="text-icon" />
            </template>
            {{ $t('common.batchDelete') }}
          </NButton>
        </template>
        {{ $t('common.confirmDelete') }}
      </NPopconfirm>
    </slot>
    <slot name="middle"></slot>
    <NButton size="small" @click="refresh">
      <template #icon>
        <icon-mdi-refresh class="text-icon" :class="{ 'animate-spin': loading }" />
      </template>
      {{ $t('common.refresh') }}
    </NButton>
    <TableColumnSetting v-model:columns="columns" />
    <slot name="suffix"></slot>
  </NSpace>
</template>

<style scoped></style>
