<template>
  <!-- 表格 -->
  <ele-pro-table
    ref="tableRef"
    row-key="id"
    :columns="columns"
    :datasource="datasource"
    :customRow="customRow"
    :scroll="{ x: 800 }"
    cache-key="proAppAnnexTable"
  >
    <template #toolbar>
      <a-space>
        <a-upload :show-upload-list="false" :customRequest="onUpload">
          <a-button class="ele-btn-icon">
            <template #icon>
              <UploadOutlined />
            </template>
            <span>上传文件</span>
          </a-button>
        </a-upload>
        <a-button
          danger
          type="primary"
          class="ele-btn-icon"
          v-if="selection.length > 0"
          @click="removeBatch"
        >
          <template #icon>
            <delete-outlined />
          </template>
          <span>删除</span>
        </a-button>
        <a-input-search
          allow-clear
          v-model:value="searchText"
          placeholder="请输入关键词"
          @search="reload"
          @pressEnter="reload"
        />
      </a-space>
    </template>
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'name'">
        <span>{{ record.name }}</span>
        <a-tooltip :title="`复制链接地址`">
          <copy-outlined
            style="padding-left: 4px"
            @click="copyText(record.downloadUrl)"
          />
        </a-tooltip>
      </template>
      <template v-if="column.key === 'action'">
        <a @click="openPreview(record.downloadUrl)">预览</a>
        <a-divider type="vertical" />
        <a :href="record.downloadUrl" target="_blank">下载</a>
        <a-divider type="vertical" />
        <a @click="openEdit(record)">修改</a>
        <a-divider type="vertical" />
        <a-popconfirm
          placement="topRight"
          title="确定要删除此文件吗？"
          @confirm="remove(record)"
        >
          <a class="ele-text-danger">删除</a>
        </a-popconfirm>
      </template>
    </template>
  </ele-pro-table>
  <!-- 编辑弹窗 -->
  <app-annex-edit v-model:visible="showEdit" :data="current" @done="reload" />
</template>

<script lang="ts" setup>
  import { createVNode, ref, watch } from 'vue';
  import { message, Modal } from 'ant-design-vue/es';
  import {
    UploadOutlined,
    DeleteOutlined,
    CopyOutlined,
    ExclamationCircleOutlined
  } from '@ant-design/icons-vue';
  import type { EleProTable } from 'ele-admin-pro/es';
  import type {
    DatasourceFunction,
    ColumnItem
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import { messageLoading, toDateString } from 'ele-admin-pro/es';
  import AppAnnexEdit from './app-annex-edit.vue';
  import {
    pageFiles,
    removeFile,
    removeFiles,
    uploadOssByAppId
  } from '@/api/system/file';
  import type { FileRecord, FileRecordParam } from '@/api/system/file/model';
  import { copyText, openPreview } from '@/utils/common';
  import { FILE_SERVER } from '@/config/setting';

  const props = defineProps<{
    appId: any;
    data: any;
  }>();

  // 表格实例
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);
  // 表格选中数据
  const selection = ref<FileRecord[]>([]);
  // 当前编辑数据
  const current = ref<FileRecord | null>(null);
  // 是否显示编辑弹窗
  const showEdit = ref(false);
  const type = ref('name');
  const groupId = ref<number>(0);
  const searchText = ref('');
  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      key: 'index',
      width: 48,
      align: 'center',
      fixed: 'left',
      hideInSetting: true,
      customRender: ({ index }) => index + (tableRef.value?.tableIndex ?? 0)
    },
    {
      title: '文件名称',
      dataIndex: 'name',
      ellipsis: true
    },
    {
      title: '描述',
      dataIndex: 'comments',
      ellipsis: true
    },
    {
      title: '文件大小',
      dataIndex: 'length',
      sorter: true,
      showSorterTooltip: false,
      ellipsis: true,
      customRender: ({ text }) => {
        if (text < 1024) {
          return text + 'B';
        } else if (text < 1024 * 1024) {
          return (text / 1024).toFixed(1) + 'KB';
        } else if (text < 1024 * 1024 * 1024) {
          return (text / 1024 / 1024).toFixed(1) + 'M';
        } else {
          return (text / 1024 / 1024 / 1024).toFixed(1) + 'G';
        }
      },
      width: 120
    },
    {
      title: '上传者',
      width: 120,
      dataIndex: 'createNickname'
    },
    {
      title: '上传时间',
      dataIndex: 'createTime',
      sorter: true,
      width: 180,
      showSorterTooltip: false,
      ellipsis: true,
      customRender: ({ text }) => toDateString(text)
    },
    {
      title: '操作',
      key: 'action',
      width: 260,
      align: 'center'
    }
  ]);

  // 表格数据源
  const datasource: DatasourceFunction = ({ page, limit, where, orders }) => {
    where = {};
    if (type.value == 'name') {
      where.name = searchText.value;
    }
    if (type.value == 'createNickname') {
      where.createNickname = searchText.value;
    }
    if (groupId.value > 0) {
      where.groupId = groupId.value;
    }
    // where.contentType = 'application';
    where.appId = props.appId;
    return pageFiles({ ...where, ...orders, page, limit });
  };

  /* 搜索 */
  const reload = (where?: FileRecordParam) => {
    selection.value = [];
    tableRef?.value?.reload({ page: 1, where });
  };

  /* 打开编辑弹窗 */
  const openEdit = (row?: FileRecord) => {
    current.value = row ?? null;
    showEdit.value = true;
  };

  /* 删除单个 */
  const remove = (row: FileRecord) => {
    const hide = messageLoading('请求中..', 0);
    removeFile(row.id)
      .then((msg) => {
        hide();
        message.success(msg);
        reload();
      })
      .catch((e) => {
        hide();
        message.error(e.message);
      });
  };

  /* 批量删除 */
  const removeBatch = () => {
    if (!selection.value.length) {
      message.error('请至少选择一条数据');
      return;
    }
    Modal.confirm({
      title: '提示',
      content: '确定要删除选中的文件吗?',
      icon: createVNode(ExclamationCircleOutlined),
      maskClosable: true,
      onOk: () => {
        const hide = messageLoading('请求中..', 0);
        removeFiles(selection.value.map((d) => d.id))
          .then((msg) => {
            hide();
            message.success(msg);
            reload();
          })
          .catch((e) => {
            hide();
            message.error(e.message);
          });
      }
    });
  };

  // 上传文件
  const onUpload = (item) => {
    const { file } = item;
    if (file.size / 1024 / 1024 > 100) {
      message.error('大小不能超过 100MB');
      return;
    }
    const hide = messageLoading({
      content: '上传中..',
      duration: 0,
      mask: true
    });
    uploadOssByAppId(file, props.data.appId)
      .then((data) => {
        console.log(data);
        hide();
        message.success('上传成功');
        reload();
      })
      .catch((e) => {
        message.error(e.message);
        hide();
      });
  };

  /* 自定义行属性 */
  const customRow = (record: FileRecord) => {
    return {
      // 行点击事件
      onClick: () => {
        // console.log(record);
      },
      // 行双击事件
      onDblclick: () => {
        openPreview(FILE_SERVER + record.downloadUrl);
      }
    };
  };

  watch(
    () => props.appId,
    (appId) => {
      if (appId) {
        reload();
      }
    },
    { immediate: true }
  );
</script>

<script lang="ts">
  export default {
    name: 'AppAnnexIndex'
  };
</script>
