<template>
  <!--引用表格-->
  <BasicTable @register="registerTable">
    <!--插槽:table标题-->
    <template #tableTitle>
      <BasicUpload
        :max-size="20"
        :max-number="10"
        :empty-hide-preview="true"
        :upload-params="uploadParams"
        :api="uploadApi2"
        class="my-5"
        :accept="['*']"
        @change="handleChange"
      />
    </template>
    <!--操作栏-->
    <template #action="{ record }">
      <TableAction :actions="getTableAction(record)" />
    </template>
  </BasicTable>
</template>

<script lang="ts" name="system-file" setup>
  import { ref } from 'vue';
  import { BasicUpload, BasicTable, TableAction, useListPage } from '@jdlinker/ui';
  import { columns, searchFormSchema } from './file.data';
  import { list, deleteFile } from './file.api';
  import { getToken, downloadByUrl, uploadApi2, usePermission } from '@jdlinker/func';
  import { Base64 } from 'js-base64';

  const uploadParams = ref({
    Authorization: `${getToken()}`
  });
  const { hasPermission } = usePermission();

  //注册table数据
  const { tableContext } = useListPage({
    tableProps: {
      api: list,
      columns,
      formConfig: {
        schemas: searchFormSchema
      }
    }
  });

  //注册table数据
  const [registerTable, { reload }] = tableContext;

  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteFile({ id: record.id }, reload);
  }

  /**
   * 文件上传事件
   */
  function handleChange() {
    reload();
  }
  /**
   * 下载
   * @param record
   */
  const handleDownload = (record) => {
    downloadByUrl({
      url: window.location.origin + '/' + record.downloadUrl,
      target: '_self'
    });
  };

  async function handlePreview(record) {
    const previewUrl = `${(import.meta as any).env.VITE_GLOB_FILE_URL}${record.downloadUrl}`;
    window.open(`${(import.meta as any).env.VITE_FILE_PREVIEW_HOST}/onlinePreview?url=` + encodeURIComponent(Base64.encode(previewUrl)));
  }
  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        icon: 'ant-design:delete-outlined',
        tooltip: '删除',
        color: 'error',
        popConfirm: {
          placement: 'left',
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record)
        },
        ifShow: () => hasPermission('system:ossfile:delete')
      },
      {
        icon: 'ant-design:download',
        tooltip: '下载',
        onClick: handleDownload.bind(null, record)
      },
      {
        icon: 'ant-design:eye-outlined',
        tooltip: '预览',
        onClick: handlePreview.bind(null, record)
      }
    ];
  }
</script>
