<script setup lang="ts">
import { computed, h, ref, resolveComponent } from 'vue';
import type { UploadCustomRequestOptions } from 'naive-ui';

interface FileItem {
  id: number;
  name: string;
  remark: string;
  uploadTime?: string;
  size?: string;
}

// 主体框架内置的第三方方法通过window对象暴露、供外部组件使用
// 获取消息提示
const message = (window as any).$message;
// 状态变量
const fileData = ref<FileItem[]>([
  {
    id: 1,
    name: '2023年度财务报表.xlsx',
    remark: '年度财务总结文件',
    uploadTime: '2023-12-15',
    size: '2.3MB'
  },
  {
    id: 2,
    name: '产品设计方案.docx',
    remark: '产品设计初稿，待审核',
    uploadTime: '2023-12-20',
    size: '1.5MB'
  },
  {
    id: 3,
    name: '市场调研报告.pdf',
    remark: '2023第四季度市场调研',
    uploadTime: '2023-12-18',
    size: '3.7MB'
  }
]);
const loading = ref<boolean>(false);
const showPreviewModal = ref<boolean>(false);
const currentFile = ref<FileItem | null>(null);

// 表格列定义
const columns = ref([
  {
    title: '文件名称',
    key: 'name',
    width: '50%'
  },
  {
    title: '上传日期',
    key: 'uploadTime',
    align: 'center' as const,
    width: '30%'
  },
  {
    title: '操作',
    key: 'actions',
    align: 'center' as const,
    width: '20%',
    render(row: FileItem) {
      return h('div', { style: 'display: flex; gap: 8px; justify-content: center;' }, [
        h(
          resolveComponent('n-button'),
          {
            size: 'small',
            type: 'info',
            onClick: () => viewFile(row)
          },
          { default: () => '预览' }
        ),
        h(
          resolveComponent('n-button'),
          {
            size: 'small',
            type: 'error',
            onClick: () => deleteFile(row)
          },
          { default: () => '删除' }
        )
      ]);
    }
  }
]);

// 查看文件
function viewFile(file: FileItem) {
  currentFile.value = file;
  showPreviewModal.value = true;
}

// 删除文件
function deleteFile(file: FileItem) {
  message.success(`文件"${file.name}"已删除`);
  fileData.value = fileData.value.filter(item => item.id !== file.id);
}

// 下载文件
function downloadFile(file: FileItem) {
  message.success(`开始下载文件: ${file.name}`);
  // 实际项目中这里应该调用后端API进行文件下载
}

// 处理文件上传
function handleUpload(options: UploadCustomRequestOptions) {
  const { file } = options;

  if (file) {
    loading.value = true;

    // 模拟上传延迟
    setTimeout(() => {
      const newFile: FileItem = {
        id: Date.now(),
        name: file.name,
        remark: '新上传文件',
        uploadTime: new Date().toISOString().split('T')[0],
        size: formatFileSize(file.file?.size || 0)
      };

      fileData.value.unshift(newFile);
      message.success(`文件"${file.name}"上传成功!`);
      loading.value = false;
    }, 1500);
  }
}

// 格式化文件大小
function formatFileSize(size: number): string {
  if (size < 1024) {
    return `${size}B`;
  } else if (size < 1024 * 1024) {
    return `${(size / 1024).toFixed(1)}KB`;
  }
  return `${(size / (1024 * 1024)).toFixed(1)}MB`;
}
</script>

<template>
  <div>
    <NSpace vertical>
      <NSpace justify="end" style="margin-bottom: 10px">
        <NUpload action="#" :custom-request="handleUpload" :show-file-list="false">
          <NButton type="primary">
            <template #icon>
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18">
                <path
                  fill="currentColor"
                  d="M19.35,10.04C18.67,6.59 15.64,4 12,4C9.11,4 6.6,5.64 5.35,8.04C2.34,8.36 0,10.91 0,14A6,6 0 0,0 6,20H19A5,5 0 0,0 24,15C24,12.36 21.95,10.22 19.35,10.04M19,18H6A4,4 0 0,1 2,14C2,11.95 3.53,10.24 5.56,10.03L6.63,9.92L7.13,8.97C8.08,7.14 9.94,6 12,6C14.62,6 16.88,7.86 17.39,10.43L17.69,11.93L19.22,12.04C20.78,12.14 22,13.45 22,15A3,3 0 0,1 19,18M8,13H10.55V16H13.45V13H16L12,9L8,13Z"
                ></path>
              </svg>
            </template>
            上传文件
          </NButton>
        </NUpload>
      </NSpace>

      <NDataTable
        :columns="columns"
        :data="fileData"
        :bordered="false"
        :loading="loading"
        max-height="500px"
      ></NDataTable>
    </NSpace>

    <!-- 文件预览对话框 -->
    <NModal v-model:show="showPreviewModal" preset="card" title="文件预览" style="width: 50%" :mask-closable="true">
      <div v-if="currentFile">
        <NDescriptions label-placement="left" bordered>
          <NDescriptionsItem label="文件名称">
            {{ currentFile.name }}
          </NDescriptionsItem>
          <NDescriptionsItem label="上传日期">
            {{ currentFile.uploadTime || '未记录' }}
          </NDescriptionsItem>
        </NDescriptions>
        <div class="modal-footer">
          <NButton type="primary" @click="downloadFile(currentFile)">下载文件</NButton>
          <NButton @click="showPreviewModal = false">关闭</NButton>
        </div>
      </div>
    </NModal>
  </div>
</template>

<style scoped>
.section-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 16px;
  color: #333;
}

.section-icon {
  margin-right: 8px;
  color: #333;
  display: flex;
  align-items: center;
  justify-content: center;
}

.file-preview-content {
  margin: 20px 0;
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed #ccc;
  border-radius: 4px;
}

.no-preview-message {
  text-align: center;
  color: #999;
}

.file-icon {
  font-size: 48px;
  opacity: 0.6;
}

.modal-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
