<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate" v-auth="'excel:add'">{{
          t('新增')
        }}</a-button>
        <a-upload
          :before-upload="beforeUpload"
          :showUploadList="false"
          accept=".xlsx"
          v-auth="'excel:upload'"
        >
          <a-button type="primary"> 上传 </a-button>
        </a-upload>
        <a-button
          @click="handleMulDownload"
          v-auth="'excel:multipleDownload'"
          type="primary"
          class="!mr-4"
        >
          下载
        </a-button></template
      >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'fileName'">
          <div class="flex items-center">
            <img :src="excelPng" class="w-15px mr-1" /> {{ record.fileName }}
          </div>
        </template>
        <template v-if="column.dataIndex === 'action'">
          <TableAction
            :actions="[
              {
                label: '下载',
                auth: 'excel:download',
                onClick: handleDownload.bind(null, record),
              },
              {
                label: '权限',
                auth: 'excel:auth',
                onClick: handleAuth.bind(null, record),
              },
              {
                label: '重命名',
                auth: 'excel:rename',
                onClick: handleRename.bind(null, record),
              },
              {
                label: '编辑',
                auth: 'excel:edit',
                onClick: handleEdit.bind(null, record),
              },
              {
                label: '删除',
                auth: 'excel:delete',
                color: 'error',
                popConfirm: {
                  title: t('是否确认删除'),
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <LuckysheetModal @register="registerLuckysheetModal" @success="reload" />
    <RenameModal @register="registerRenameModal" @success="handleNameSuccess" />
    <AuthModal @register="registerAuthModal" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { BasicTable, useTable, TableAction, FormSchema, BasicColumn } from '/@/components/Table';
  import {
    getExcelPageList,
    deleteExcel,
    updateExcelName,
    getExcelInfo,
    addExcelFile,
  } from '/@/api/system/excel';
  import { exportExcel } from '/@/utils/export';
  import { PageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useModal } from '/@/components/Modal';
  import LuckyExcel from 'luckyexcel';
  import luckysheet from 'luckysheet';
  import LuckysheetModal from './components/LuckysheetModal.vue';
  import RenameModal from './components/RenameModal.vue';
  import AuthModal from './components/AuthModal.vue';
  import { cloneDeep } from 'lodash-es';
  import { usePermission } from '/@/hooks/web/usePermission';
  import excelPng from '/@/assets/excel/excel.png';
  import bgPng from '/@/assets/excel/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: 'createUserName',
      align: 'center',
      resizable: true,
    },
    {
      title: '更新时间',
      dataIndex: 'modifyDate',
      align: 'center',
      // sorter: true,
      resizable: true,
    },
  ];
  const { notification } = useMessage();
  const { hasPermission } = usePermission();

  const [registerLuckysheetModal, { openModal: openLuckysheetModal }] = useModal();
  const [registerRenameModal, { openModal: openRenameModal }] = useModal();
  const [registerAuthModal, { openModal: openAuthModal }] = useModal();

  const [registerTable, { reload, getSelectRows }] = useTable({
    title: '在线excel',
    api: getExcelPageList,
    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('excel:edit')) {
            handleEdit(record);
          }
        },
      };
    },
    trBgUrl: bgPng,
  });

  const handleCreate = () => {
    openLuckysheetModal(true, {
      isUpdate: false,
    });
  };

  const handleEdit = (record: Recordable) => {
    openLuckysheetModal(true, {
      id: record.id,
      isUpdate: true,
    });
  };

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

  const handleNameSuccess = async (info) => {
    await updateExcelName(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, {
      isRename: true,
      fileName: record.fileName,
      id: record.id,
      title: '重命名',
    });
  };

  const handleDownload = async (record) => {
    const luckysheetName = record.fileName;
    const info = await getExcelInfo(record.id);
    exportExcel(JSON.parse(info.fileJson), luckysheetName);
  };

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

  const beforeUpload = (file) => {
    LuckyExcel.transformExcelToLucky(file, async function (exportJson: any) {
      const sheetFile = cloneDeep(exportJson.sheets);
      sheetFile.forEach((item) => {
        item.data = luckysheet.transToData(item.celldata);
      });
      const name = exportJson.info.name;
      const jsonContent = JSON.stringify(exportJson.sheets);
      const fileName = name.endsWith('.xlsx') ? name.substr(0, name.length - 5) : name;
      await addExcelFile({
        jsonContent,
        fileJson: JSON.stringify(sheetFile), //列表页下载所需数据
        fileName,
      });
      reload();
    });
    return false;
  };
</script>
