<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button @click="handleUpload" type="primary" v-auth="'file:upload'"> 上传</a-button>
        <a-button
          @click="handleMulDownload"
          type="primary"
          v-auth="'file:multipleDownload'"
          class="!mr-4"
        >
          下载
        </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'fileName'">
          <div class="flex items-center">
            <img :src="getImg(record.fileType)" class="w-15px mr-1" /> {{ record.fileName }}
          </div>
        </template>
        <template v-if="column.dataIndex === 'action'">
          <TableAction
            :actions="[
              {
                label: '查看',
                auth: 'file:view',
                onClick: handleView.bind(null, record),
              },
              {
                label: '下载',
                auth: 'file:download',
                onClick: handleDownload.bind(null, record),
              },
              {
                label: '权限',
                auth: 'file:auth',
                onClick: handleAuth.bind(null, record),
              },
              {
                label: '重命名',
                auth: 'file:rename',
                onClick: handleRename.bind(null, record),
              },
              {
                label: '删除',
                auth: 'file:delete',
                color: 'error',
                popConfirm: {
                  title: t('是否确认删除'),
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <PreviewModal @register="registerPreviewModal" @success="reload" />
    <RenameModal @register="registerRenameModal" @success="handleNameSuccess" />
    <AuthModal @register="registerAuthModal" />
    <ImportModal
      @register="registerImportModal"
      importUrl="/system/file-management"
      accept=""
      @success="reload"
      :isDefaultModal="true"
    />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { BasicTable, useTable, TableAction, FormSchema, BasicColumn } from '/@/components/Table';
  import { getFilePageList, deleteFile, updateFileName } from '/@/api/system/fileManagement';
  import { downloadByUrl } from '/@/utils/file/download';
  import { ImportModal } from '/@/components/Import';
  import { PageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useModal } from '/@/components/Modal';
  import PreviewModal from './components/PreviewModal.vue';
  import RenameModal from './components/RenameModal.vue';
  import AuthModal from './components/AuthModal.vue';
  import { usePermission } from '/@/hooks/web/usePermission';
  import pdfPng from '/@/assets/file/pdf.png';
  import wordPng from '/@/assets/file/word.png';
  import txtPng from '/@/assets/file/txt.png';
  import imgPng from '/@/assets/file/img.png';
  import excelPng from '/@/assets/file/excel.png';
  import bgPng from '/@/assets/file/bg.png';

  const { t } = useI18n();
  const searchFormSchema: FormSchema[] = [
    {
      field: 'keyword',
      label: '',
      component: 'Input',
      colProps: { span: 8 },
      componentProps: {
        placeholder: '请输入文件名称',
      },
    },
  ];

  const columns: BasicColumn[] = [
    {
      title: '名称',
      dataIndex: 'fileName',
      align: 'center',
      width: 350,
      resizable: true,
    },
    {
      title: '大小',
      dataIndex: 'fileSize',
      align: 'center',
      width: 200,
      resizable: true,
      customRender: ({ record }) => {
        return !!record.fileSize ? (record.fileSize / 1024).toFixed(1) + 'KB' : record.fileSize;
      },
    },
    {
      title: '创建者',
      dataIndex: 'createUserName',
      align: 'center',
      resizable: true,
    },
    {
      title: '更新时间',
      dataIndex: 'modifyDate',
      align: 'center',
      /// sorter: true,
      resizable: true,
    },
  ];
  const { notification } = useMessage();
  const { hasPermission } = usePermission();

  const [registerPreviewModal, { openModal: openPreviewModal }] = useModal();
  const [registerRenameModal, { openModal: openRenameModal }] = useModal();
  const [registerAuthModal, { openModal: openAuthModal }] = useModal();
  const [registerImportModal, { openModal: openImportModal }] = useModal();
  const [registerTable, { reload, getSelectRows }] = useTable({
    title: '文件管理',
    api: getFilePageList,
    rowKey: 'id',
    columns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
    },
    useSearchForm: true,
    striped: false,
    showIndexColumn: false,
    actionColumn: {
      width: 240,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    rowSelection: {
      type: 'checkbox',
    },
    customRow: (record) => {
      return {
        ondblclick: () => {
          if (hasPermission('file:view')) {
            handleView(record);
          }
        },
      };
    },
    trBgUrl: bgPng,
  });

  const getImg = (type) => {
    switch (type) {
      case 'pdf':
        return pdfPng;
      case 'doc':
      case 'docx':
        return wordPng;
      case 'txt':
        return txtPng;
      case 'png':
      case 'jpg':
      case 'jpeg':
        return imgPng;
      default:
        return excelPng;
    }
  };

  const handleUpload = () => {
    openImportModal(true, {
      title: '文件上传',
    });
  };

  const handleView = async (record) => {
    openPreviewModal(true, {
      fileUrl: record.fileUrl,
      fileName: record.fileName,
    });
  };

  const handleDelete = (record: Recordable) => {
    deleteFile([record.id]).then(() => {
      reload();
      notification.success({
        message: t('提示'),
        description: t('删除成功'),
      }); //提示消息
    });
  };

  const handleNameSuccess = async (info) => {
    await updateFileName(info);
    reload();
  };

  const handleMulDownload = async () => {
    if (!getSelectRows().length) {
      notification.warning({
        message: t('警告'),
        description: t('必须选中一行！'),
      });
      return false;
    }
    getSelectRows().forEach((item) => {
      handleDownload(item);
    });
  };

  const handleRename = (record) => {
    openRenameModal(true, {
      fileName: record.fileName,
      id: record.id,
      title: '重命名',
    });
  };

  const handleDownload = async (record) => {
    downloadByUrl({ url: record.fileUrl, fileName: record.fileName });
  };

  const handleAuth = (record) => {
    openAuthModal(true, {
      id: record.id,
    });
  };
</script>
