<template>
  <!--引用表格-->
  <BasicTable @register="registerTable">
    <!--插槽:table标题-->
    <template #tableTitle>
      <a-upload
        name="file"
        :showUploadList="false"
        :action="minioAction"
        :headers="tokenHeader"
        :beforeUpload="beforeUpload"
        @change="handleChange"
      >
        <c-button v-show="hasPermission('system:ossfile:upload')" type="primary" preIcon="ant-design:upload-outlined"
          >文件上传</c-button
        >
      </a-upload>
    </template>
    <!--操作栏-->
    <template #action="{ record }">
      <TableAction :actions="getTableAction(record)" />
    </template>
  </BasicTable>
  <office-preview v-if="officePreviewVisible" :file="officePreviewRow" :status="officePreviewVisible" @close="close" />
</template>

<script lang="ts" name="system-file" setup>
  import { ref, computed } from 'vue';
  import { BasicTable, TableAction, Button as CButton, createImgPreview, useListPage } from '@jdlinker/ui';
  import { useMessage, getToken, useGlobSetting, usePermission } from '@jdlinker/func';
  import { columns, searchFormSchema } from './ossfile.data';
  import { list, deleteFile, getMinioUrl } from './ossfile.api';
  import { suffix, mitt } from '@jdlinker/utils';

  const { hasPermission } = usePermission();
  const { createMessage } = useMessage();
  const glob = useGlobSetting();
  const tokenHeader = { Authorization: getToken() };
  const textPreviewVisible = ref<boolean>(false);
  const textPreviewRow = ref();
  const videoPreviewVisible = ref<boolean>(false);
  const videoPreviewRow = ref();
  const officePreviewVisible = ref<boolean>(false);
  const officePreviewRow = ref();

  //注册table数据
  const { tableContext } = useListPage({
    designScope: 'category-template',
    tableProps: {
      title: '对象存储',
      api: list,
      columns,
      formConfig: {
        schemas: searchFormSchema
      }
    }
  });

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

  /**
   * 上传url
   */
  const minioAction = computed(() => `${glob.uploadUrl}${getMinioUrl}`);

  /**
   * 预览
   */
  function handleView(record) {
    if (record.contentType.startsWith('image')) {
      // 图片
      const imageList: any = [];
      const onImgLoad = ({ index, url, dom }) => {
        console.log(`第${index + 1}张图片已加载，URL为：${url}`, dom);
      };
      imageList.push(record.url);
      createImgPreview({ imageList: imageList, defaultWidth: 400, rememberState: true, onImgLoad });
    }
    if (suffix.simText.includes(record.contentType)) {
      // 文本文件
      textPreviewRow.value = record;
      textPreviewVisible.value = true;
    }
    if (record.contentType.indexOf('video') > -1) {
      // 视频文件
      videoPreviewVisible.value = true;
      videoPreviewRow.value = record;
    }
    if (record.contentType.indexOf('audio') > -1) {
      // 音频文件
      mitt.$emit('onAddAudio', record, record.url);
    }
    if (suffix.compressedFile.includes(record.contentType)) {
      // 压缩文件
      // openCompressionVisible.value = true;
    }
    if (
      record.contentType.indexOf('office') > -1 ||
      record.contentType.indexOf('pdf') > -1 ||
      suffix.officeFile.includes(record.ext)
    ) {
      // office文件
      officePreviewVisible.value = true;
      officePreviewRow.value = record;
    }
  }
  const close = (e) => {
    console.log('ossfile', e);
    officePreviewVisible.value = e;
  };

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

  /**
   * 上传前事件
   */
  function beforeUpload(file) {
    var fileType = file.type;
    if (fileType === 'image') {
      if (fileType.indexOf('image') < 0) {
        createMessage.warning('请上传图片');
        return false;
      }
    } else if (fileType === 'file') {
      if (fileType.indexOf('image') >= 0) {
        createMessage.warning('请上传文件');
        return false;
      }
    }
    return true;
  }

  /**
   * 文件上传事件
   */
  function handleChange(info) {
    if (info.file.status === 'done') {
      if (info.file.response.success) {
        reload();
        createMessage.success(`${info.file.name} 上传成功!`);
      } else {
        createMessage.error(`${info.file.response.message}`);
      }
    } else if (info.file.status === 'error') {
      createMessage.error(`${info.file.response.message}`);
    }
  }
  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        icon: 'ant-design:folder-view-outlined',
        tooltip: '预览',
        onClick: handleView.bind(null, record),
        ifShow: () => hasPermission('system:ossfile:preview')
      },
      {
        icon: 'ant-design:delete-outlined',
        tooltip: '删除',
        color: 'error',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record)
        },
        ifShow: () => hasPermission('system:ossfile:delete')
      }
    ];
  }
</script>
