<template>
  <w-dialog ref="dialogRef" :title="$t('re.resources.dialog.attachment.title')" width="900px" :can-maximize="false">
    <div class="px-2">
      <w-grid
        ref="gridRef"
        :height="400"
        :title="$t('re.resources.dialog.attachment.grid.title')"
        selection="multiple"
        :config-button="false"
        :full-screen-button="false"
        :toolbar-configure="{ noIcon: false }"
        :toolbar-actions="[
          'refresh',
          'separator',
          {
            extend: 'add',
            click: () => {
              addAttachmentDialogRef.open();
            },
          },
          'remove',
          'separator',
          {
            name: 'download',
            label: $t('download'),
            icon: 'bi-download',
            enableIf: (arg) => {
              return arg.selected;
            },
            click: (arg) => {
              download(arg.selected.id);
            },
          },
        ]"
        :query-form-fields="[]"
        :auto-fetch-data="false"
        :fetch-data-url="fetchDataUrl + '?' + foreignKey + '=' + foreignValue"
        :data-url="dataUrl"
        :columns="[
          { width: 120, name: 'id', label: $t('id'), hidden: true },
          {
            width: '100%',
            name: 'name',
            label: $t('name'),
            format: (value, row) => {
              return value;
            },
          },
          { width: 200, name: 'description', label: $t('description') },
          { width: 100, name: 'lastModifier', label: $t('lastModifier') },
          { width: 120, name: 'lastModifyDate', label: $t('lastModifyDate'), format: Formater.dateOnly() },
        ]"
      ></w-grid>
      <AddAttachmentDialog
        ref="addAttachmentDialogRef"
        :foreign-key="foreignKey"
        :foreign-value="foreignValue"
        @after-add="gridRef.refresh()"
      ></AddAttachmentDialog>
    </div>
  </w-dialog>
</template>
<script setup lang="ts">
import { ref, nextTick } from 'vue';
import { Environment, Formater, Downloader } from 'platform-core';
import AddAttachmentDialog from './AddAttachmentDialog.vue';

const props = defineProps({
  opener: { type: Object, default: undefined },
  fetchDataUrl: { type: String, default: '' },
  dataUrl: { type: String, default: '' },
  foreignKey: { type: String, default: '' },
  foreignValue: { type: String, default: '' },
});

const dialogRef = ref();
const gridRef = ref();
const addAttachmentDialogRef = ref();

const download = (id) => {
  Downloader.get(Environment.apiContextPath('/api/system/attachment/download/') + id);
};

const open = () => {
  dialogRef.value.show();
  nextTick(() => {
    gridRef.value.refresh();
  });
};

const close = () => {
  dialogRef.value.hide();
};

defineExpose({
  open,
  close,
});
</script>
