<template>
  <div>
    <n-space vertical>


      <n-space justify="space-between" style="margin-bottom: 10px;">
        <n-space>
          <n-button
            type="info"
            :disabled="selectedFiles.length === 0"
            @click="batchDownload"
          >
            <template #icon>
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18">
                <path fill="currentColor" d="M5,20H19V18H5M19,9H15V3H9V9H5L12,16L19,9Z"/>
              </svg>
            </template>
            批量下载 ({{ selectedFiles.length }})
          </n-button>
          <n-button
            type="error"
            :disabled="selectedFiles.length === 0 || isReadonly"
            @click="batchDelete"
          >
            <template #icon>
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18">
                <path fill="currentColor" d="M9,3V4H4V6H5V19A2,2 0 0,0 7,21H17A2,2 0 0,0 19,19V6H20V4H15V3H9M7,6H17V19H7V6M9,8V17H11V8H9M13,8V17H15V8H13Z"/>
              </svg>
            </template>
            批量删除 ({{ selectedFiles.length }})
          </n-button>
        </n-space>

        <n-space>
          <n-upload
            ref="uploadRef"
            action="#"
            :custom-request="handleBatchUpload"
            :show-file-list="true"
            :multiple="true"
            accept="*/*"
            :max="10"
            list-type="text"
            :file-list="uploadFileList"
            @update:file-list="updateFileList"
            :auto-upload="false"
          >
            <n-button type="primary" :disabled="isReadonly">
              <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>
              选择文件
            </n-button>
          </n-upload>

          <n-button
            type="success"
            :disabled="uploadFileList.length === 0 || batchUploading || isReadonly"
            :loading="batchUploading"
            @click="startBatchUpload"
          >
            <template #icon>
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18">
                <path fill="currentColor" d="M9,16V10H5L12,3L19,10H15V16H9M5,20V18H19V20H5Z"></path>
              </svg>
            </template>
            批量上传
          </n-button>
        </n-space>
      </n-space>

      <n-data-table
        :columns="columns"
        :data="fileData"
        :bordered="false"
        :loading="loading"
        max-height="500px"
        :row-key="(row: FileItem) => row.Kvid"
        v-model:checked-row-keys="selectedFileKeys"
        @update:checked-row-keys="handleSelectionChange"
      ></n-data-table>
    </n-space>

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

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

interface FileItem {
  Kvid: string;
  OwnerKvid: string;
  Name: string;
  Extension: string;
  Length: number;
  PublishTime: string;
  DbFolderKvid: string;
  DbFolderPath: string;
  Provider: string;
  Path: string;
  Version: number;
  CreatorKvid: string;
  CreatorName: string;
  CreateTime: string;
  UpdateTime: string;
  Status: number;
  [key: string]: any;
}

interface OwnerItem {
  Kvid?: string;
  [key: string]: any;
}

// 定义props
const props = withDefaults(
  defineProps<{
    ownerItem?: OwnerItem;
  }>(),
  {
    ownerItem: () => ({})
  }
);

// 定义 emits
const emit = defineEmits(['close', 'update-files']);

// 主体框架内置的第三方方法通过window对象暴露、供外部组件使用
const axios = (window as any).$axios;
// 获取主题状态
const themeStore = (window as any).$themeStore;
// 获取消息提示
const message = (window as any).$message;
const dialog = (window as any).$dialog;
// 通过计算属性确定当前的主体色
const isDarkMode = computed(() => themeStore?.darkMode || false);
// 根据主题计算文字颜色
const textColor = computed(() => (isDarkMode.value ? 'rgba(255, 255, 255, 0.85)' : 'rgba(0, 0, 0, 0.85)'));
const legendTextColor = computed(() => (isDarkMode.value ? 'rgba(255, 255, 255, 0.65)' : 'rgba(0, 0, 0, 0.65)'));
const borderColor = computed(() => (isDarkMode.value ? '#303030' : '#ffffff'));
// CSS变量
const cssVars = computed(() => ({
    '--text-color': textColor.value,
    '--bg-color': isDarkMode.value ? '#1f1f1f' : '#f5f5f5',
    '--panel-bg': isDarkMode.value ? '#262626' : '#ffffff',
    '--card-bg': isDarkMode.value ? '#303030' : '#ffffff',
    '--border-color': isDarkMode.value ? '#434343' : '#e8e8e8'
}));
// 状态变量
const fileData = ref<FileItem[]>([]);
const loading = ref<boolean>(false);
const showPreviewModal = ref<boolean>(false);
const currentFile = ref<FileItem | null>(null);

// 状态相关计算属性
const currentStatus = computed(() => props.ownerItem?.Status || 0);
const isReadonly = computed(() => currentStatus.value > 150);

// 状态映射
const getStatusInfo = (status: number) => {
  const statusMap = {
    0: { label: '草稿', color: '#909399', type: 'default' },
    100: { label: '待上传', color: '#E6A23C', type: 'warning' },
    150: { label: '已上传', color: '#409EFF', type: 'info' },
    200: { label: '审核中', color: '#F56C6C', type: 'error' },
    250: { label: '待复核', color: '#722ED1', type: 'warning' },
    300: { label: '不通过', color: '#FF7A45', type: 'error' },
    2147483647: { label: '已通过', color: '#67C23A', type: 'success' } // int.MaxValue
  };

  return statusMap[status as keyof typeof statusMap] || {
    label: `状态${status}`,
    color: '#909399',
    type: 'default'
  };
};

// 防止重复请求的标志
const isLoading = ref<boolean>(false);
const currentOwnerKvid = ref<string>('');

// 封装获取文件列表的方法
async function getFiles(ownerItem?: OwnerItem) {
  if (!ownerItem || !ownerItem.Kvid) {
    return;
  }

  // 防止重复请求相同的数据
  if (isLoading.value || currentOwnerKvid.value === ownerItem.Kvid) {
    return;
  }

  try {
    isLoading.value = true;
    loading.value = true;
    currentOwnerKvid.value = ownerItem.Kvid;

    const response = await axios.get('/Restful/Kivii.Storages.Entities.DbFile/Query.json', {
      params: {
        FolderPath: '/TestRecords/Records',
        OwnerKvid: ownerItem.Kvid
      }
    });

        if (response.data && response.data.Results) {
      // 直接使用API返回的数据，因为字段已匹配
      fileData.value = response.data.Results;

      message.success(`成功加载 ${fileData.value.length} 个文件`);
    } else {
      fileData.value = [];
      message.info('暂无文件数据');
    }
  } catch (error) {
    message.error('获取文件列表失败，请稍后重试');
    fileData.value = [];
  } finally {
    isLoading.value = false;
    loading.value = false;
  }
}

// 格式化日期
function formatDate(dateString: string): string {
  if (!dateString) return '';
  try {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    }).replace(/\//g, '-');
  } catch (error) {
    return dateString;
  }
}

// 表格列定义
const columns: DataTableColumns<FileItem> = [
  {
    type: 'selection' as const,
    width: '50px'
  },
  {
    title: '序号',
    key: 'index',
    width: '60px',
    align: 'center' as const,
    render(row: FileItem, index: number) {
      return index + 1;
    }
  },
  {
    title: '文件名称',
    key: 'Name',
    width: '35%'
  },
  {
    title: '文件大小',
    key: 'Length',
    align: 'center' as const,
    width: '12%',
    render(row: FileItem) {
      return formatFileSize(row.Length);
    }
  },
  {
    title: '上传时间',
    key: 'CreateTime',
    align: 'center' as const,
    width: '15%',
    render(row: FileItem) {
      return formatDate(row.CreateTime);
    }
  },
  {
    title: '操作',
    key: 'actions',
    align: 'center' as const,
    width: '18%',
    render(row: FileItem) {
      const buttons = [
        // 下载按钮 - 总是显示
        h(
          resolveComponent('n-button'),
          {
            size: 'small',
            style: {
              backgroundColor: '#52c41a',
              color: '#fff',
              border: 'none',
              borderRadius: '4px',
              padding: '4px 12px',
              fontSize: '12px',
              fontWeight: '500'
            },
            onClick: () => downloadSingleFile(row)
          },
          { default: () => '下载' }
        )
      ];

      // 删除按钮 - 只在非只读状态下显示
      if (!isReadonly.value) {
        buttons.push(
          h(
            resolveComponent('n-button'),
            {
              size: 'small',
              style: {
                backgroundColor: '#ff4d4f',
                color: '#fff',
                border: 'none',
                borderRadius: '4px',
                padding: '4px 12px',
                fontSize: '12px',
                fontWeight: '500'
              },
              onClick: () => {
                dialog.warning({
                  title: '确认删除',
                  content: `确定要删除文件"${row.Name}"吗？此操作不可撤销。`,
                  positiveText: '确定删除',
                  negativeText: '取消',
                  onPositiveClick: () => deleteSingleFile(row)
                });
              }
            },
            { default: () => '删除' }
          )
        );
      }

      return h('div', { style: 'display: flex; gap: 8px; justify-content: center;' }, buttons);
    }
  }
];

// 监听 ownerItem 变化
watch(
  () => props.ownerItem,
  (newOwnerItem) => {
    if (newOwnerItem && newOwnerItem.Kvid) {
      getFiles(newOwnerItem);
    } else {
      // 清空当前数据
      fileData.value = [];
      currentOwnerKvid.value = '';
    }
  },
  { immediate: true, deep: true }
);

// 在组件卸载时传递数据
onBeforeUnmount(() => {
  // 组件卸载前传递最新的文件数据
  emit('update-files', fileData.value);
});



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

// 删除文件 - 通用方法
async function deleteFiles(files: FileItem[]) {
  if (!files || files.length === 0) {
    message.error('没有要删除的文件');
    return false;
  }

  const kvids = files.map(file => file.Kvid).filter(Boolean);
  if (kvids.length === 0) {
    message.error('文件ID不存在，无法删除');
    return false;
  }

  try {
    loading.value = true;

    // 调用文件删除接口
    const response = await axios.post('/Restful/Kivii.Storages.Entities.DbFile/Delete.json', {
      FolderPath: '/TestRecords/Records',
      Kvids: kvids
    });

    if (response.data && response.data.Results && response.data.Results.length > 0) {
      // 从列表中移除已删除的文件
      fileData.value = fileData.value.filter(item => !kvids.includes(item.Kvid));
      // 清空选择
      selectedFileKeys.value = [];

      const fileNames = files.map(f => f.Name).join('、');
      message.success(`文件"${fileNames}"删除成功`);

      // 传递更新后的文件列表
      emit('update-files', fileData.value);

      return true;
    } else {
      message.error('删除失败，请稍后重试');
      return false;
    }
  } catch (error) {
    message.error('删除文件失败，请稍后重试');
    return false;
  } finally {
    loading.value = false;
  }
}

// 下载文件 - 通用方法
async function downloadFiles(files: FileItem[]) {
  if (!files || files.length === 0) {
    message.error('没有要下载的文件');
    return false;
  }

  const kvids = files.map(file => file.Kvid).filter(Boolean);
  if (kvids.length === 0) {
    message.error('文件ID不存在，无法下载');
    return false;
  }

  try {
    // 调用文件下载接口
    const response = await axios.post('/Storages/Zip', {
      Kvids: kvids,
      FolderPath: '/TestRecords/Records'
    }, {
      responseType: 'blob' // 重要：指定响应类型为blob
    });

    // 创建下载链接
    const blob = new Blob([response.data]);
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;

    // 设置下载文件名
    const fileName = files.length === 1 ? files[0].Name : `批量下载_${files.length}个文件.zip`;
    link.download = fileName;

    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    const fileNames = files.map(f => f.Name).join('、');
    message.success(`文件"${fileNames}"下载成功`);
    return true;
  } catch (error) {
    message.error('文件下载失败，请稍后重试');
    return false;
  }
}

// 单个文件删除
async function deleteSingleFile(file: FileItem) {
  if (isReadonly.value) {
    message.warning('当前状态不允许删除操作（状态值 > 150）');
    return;
  }
  await deleteFiles([file]);
}

// 单个文件下载
async function downloadSingleFile(file: FileItem) {
  await downloadFiles([file]);
}

// 批量删除
async function batchDelete() {
  if (selectedFiles.value.length === 0) {
    message.warning('请先选择要删除的文件');
    return;
  }

  if (isReadonly.value) {
    message.warning('当前状态不允许删除操作（状态值 > 150）');
    return;
  }

  const fileNames = selectedFiles.value.map(f => f.Name).join('、');
  dialog.warning({
    title: '确认批量删除',
    content: `确定要删除以下文件吗？此操作不可撤销。\n\n${fileNames}`,
    positiveText: '确定删除',
    negativeText: '取消',
    onPositiveClick: () => deleteFiles(selectedFiles.value)
  });
}

// 批量下载
async function batchDownload() {
  if (selectedFiles.value.length === 0) {
    message.warning('请先选择要下载的文件');
    return;
  }

  await downloadFiles(selectedFiles.value);
}

// 上传状态跟踪
const uploadRef = ref();
const uploadFileList = ref<any[]>([]);
const batchUploading = ref(false);

// 选择状态跟踪
const selectedFileKeys = ref<(string | number)[]>([]);
const selectedFiles = computed(() => fileData.value.filter(file => selectedFileKeys.value.includes(file.Kvid)));

// 处理选择变化
function handleSelectionChange(keys: (string | number)[]) {
  selectedFileKeys.value = keys;
}

// 更新文件列表
function updateFileList(files: any[]) {
  uploadFileList.value = files;
}

// 批量上传文件
async function handleBatchUploadFiles(files: any[]) {
  if (!props.ownerItem?.Kvid) {
    message.error('缺少必要的上传参数');
    return;
  }

  if (isReadonly.value) {
    message.warning('当前状态不允许上传操作（状态值 > 150）');
    return;
  }

  try {
    batchUploading.value = true;

    // 创建 FormData 对象，支持多文件
    const formData = new FormData();

    // 添加多个文件
    files.forEach(fileItem => {
      if (fileItem.file) {
        formData.append('file', fileItem.file);
      }
    });

    // 添加其他参数
    formData.append('OwnerKvid', props.ownerItem.Kvid);
    formData.append('FolderPath', '/TestRecords/Records');
    formData.append('Tags', props.ownerItem.Title || '');

    // 调用批量文件上传接口
    const response = await axios.post('/Storages.json', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    if (response.data && response.data.Results && response.data.Results.length > 0) {
      message.success(`成功上传 ${files.length} 个文件!`);

      // 清理上传列表并重新加载文件列表
      uploadFileList.value = [];
      currentOwnerKvid.value = '';
      await getFiles(props.ownerItem);

      // 传递更新后的文件列表
      emit('update-files', fileData.value);
    } else {
      message.error(`批量上传失败: ${response.data?.Message || '未知错误'}`);
      // 清理上传列表
      uploadFileList.value = [];
    }
  } catch (error) {
    console.error('批量上传失败:', error);
    message.error('批量上传失败，请稍后重试');
    // 清理上传列表
    uploadFileList.value = [];
  } finally {
    batchUploading.value = false;
  }
}

// 开始批量上传
async function startBatchUpload() {
  if (uploadFileList.value.length === 0) {
    message.warning('请先选择要上传的文件');
    return;
  }

  if (isReadonly.value) {
    message.warning('当前状态不允许上传操作（状态值 > 150）');
    return;
  }

  await handleBatchUploadFiles(uploadFileList.value);
}

// NaiveUI上传组件的自定义请求处理（单个文件触发，但我们改为批量处理）
async function handleBatchUpload(options: any) {
  // 这个函数现在只是为了兼容NaiveUI的接口，实际逻辑在startBatchUpload中处理
  const { onFinish } = options;
  onFinish();
}

// 格式化文件大小
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`;
}

// 关闭并传递文件数据
function closeWithFileData() {
  emit('update-files', fileData.value);
  emit('close');
}
</script>

<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>
