<script lang="ts" setup>
import { reactive, ref } from 'vue';

import { ElMessage } from 'element-plus';

// 表单数据
const formData = reactive({
  floorPlansAndMonitoring: [], // 各平面图及监控信息
  otherMaterials: [], // 其他资料
});

// 上传文件列表
const uploadedFiles = ref<Map<string, any[]>>(
  new Map([
    ['floorPlansAndMonitoring', []],
    ['otherMaterials', []],
  ]),
);

// 移除了表单相关配置，直接使用响应式数据

// 上传前的校验
const handleBeforeUpload = (file: File, fileList: File[]) => {
  const maxSize = 50 * 1024 * 1024; // 50MB
  if (file.size > maxSize) {
    ElMessage.error(`文件大小不能超过50MB`);
    return false;
  }
  return true;
};

// 上传成功处理
const handleUploadSuccess = (
  response: any,
  uploadFile: any,
  uploadFiles: any[],
  field: string,
) => {
  // 模拟上传成功处理
  const fileData = {
    name: uploadFile.name,
    url: URL.createObjectURL(uploadFile.raw),
    size: uploadFile.size,
    type: uploadFile.type,
    uploadTime: new Date().toLocaleString(),
  };

  const currentFiles = uploadedFiles.value.get(field) || [];
  currentFiles.push(fileData);
  uploadedFiles.value.set(field, currentFiles);

  ElMessage.success(`文件上传成功: ${uploadFile.name}`);
};

// 移除文件
const handleRemoveFile = (file: any, field: string) => {
  const currentFiles = uploadedFiles.value.get(field) || [];
  const index = currentFiles.findIndex((item) => item.name === file.name);
  if (index !== -1) {
    currentFiles.splice(index, 1);
    uploadedFiles.value.set(field, currentFiles);
  }
};

// 获取上传组件的Props
const getUploadProps = (field: string) => {
  return {
    beforeUpload: handleBeforeUpload,
    onSuccess: (response: any, uploadFile: any, uploadFiles: any[]) => {
      handleUploadSuccess(response, uploadFile, uploadFiles, field);
    },
    onRemove: (file: any) => {
      handleRemoveFile(file, field);
    },
    fileList: uploadedFiles.value.get(field) || [],
    // 模拟上传接口
    action: '/api/upload', // 实际使用时需要替换为真实的上传接口
  };
};

// 文件选择变化处理
const handleFileChange = (event: Event, field: string) => {
  const target = event.target as HTMLInputElement;
  if (target.files && target.files.length > 0) {
    const currentFiles = uploadedFiles.value.get(field) || [];
    const maxFiles = 10;

    // 检查文件数量限制
    if (currentFiles.length + target.files.length > maxFiles) {
      ElMessage.error(`最多只能上传${maxFiles}个文件`);
      target.value = '';
      return;
    }

    // 模拟文件上传
    [...target.files].forEach((file) => {
      // 检查文件大小
      const maxSize = 50 * 1024 * 1024; // 50MB
      if (file.size > maxSize) {
        ElMessage.error(`文件大小不能超过50MB: ${file.name}`);
        return;
      }

      // 模拟上传成功
      const fileData = {
        name: file.name,
        url: URL.createObjectURL(file),
        size: file.size,
        type: file.type,
        uploadTime: new Date().toLocaleString(),
      };

      currentFiles.push(fileData);
    });

    uploadedFiles.value.set(field, currentFiles);
    ElMessage.success(`成功选择${target.files.length}个文件`);
    target.value = ''; // 清空input，允许重复选择相同文件
  }
};

// 提交表单
const onSubmit = async () => {
  // const values = await submit();
  // 这里可以调用API提交数据
};
</script>

<template>
  <!-- 附件上传组件 - 左右两栏布局 -->
  <div class="grid grid-cols-1 gap-6 md:grid-cols-2">
    <!-- 各平面图及监控信息 -->
    <div>
      <label class="mb-2 block text-sm font-medium text-gray-700">
        各平面图及监控信息
      </label>
      <div
        class="hover:border-primary flex h-20 w-full items-center justify-center rounded border border-dashed border-gray-300 transition-colors"
      >
        <div class="flex flex-col items-center justify-center">
          <div class="text-sm text-gray-500">点击或拖拽文件到此区域上传</div>
          <div class="mt-1 text-xs text-gray-400">
            支持PDF、Word、Excel、PowerPoint、图片等格式，最多10个文件
          </div>
          <input
            type="file"
            class="hidden"
            multiple
            accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.jpg,.jpeg,.png,.gif"
            @change="handleFileChange($event, 'floorPlansAndMonitoring')"
          />
          <button
            type="button"
            class="bg-primary hover:bg-primary/90 mt-2 rounded px-4 py-1 text-xs text-white transition-colors"
            @click="
              ($event) => {
                $event.stopPropagation();
                $el.previousElementSibling?.click();
              }
            "
          >
            选择文件
          </button>
        </div>
      </div>

      <!-- 已上传文件列表 -->
      <div
        v-if="uploadedFiles.get('floorPlansAndMonitoring')?.length"
        class="mt-4"
      >
        <div class="text-sm font-medium text-gray-700">已上传文件:</div>
        <div class="mt-2 space-y-2">
          <div
            v-for="(file, index) in uploadedFiles.get(
              'floorPlansAndMonitoring',
            )"
            :key="`floor-${index}`"
            class="flex items-center justify-between rounded bg-gray-50 px-3 py-2 text-sm"
          >
            <div class="flex items-center truncate">
              <svg
                class="mr-2 h-5 w-5 text-gray-400"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
                xmlns="http://www.w3.org/2000/svg"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
                />
              </svg>
              <span class="truncate">{{ file.name }}</span>
              <span class="ml-2 text-xs text-gray-500">
                {{ (file.size / 1024 / 1024).toFixed(2) }}MB
              </span>
            </div>
            <button
              type="button"
              class="ml-2 text-red-500 hover:text-red-700"
              @click="handleRemoveFile(file, 'floorPlansAndMonitoring')"
            >
              删除
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 其他资料 -->
    <div>
      <label class="mb-2 block text-sm font-medium text-gray-700">
        其他资料
      </label>
      <div
        class="hover:border-primary flex h-20 w-full items-center justify-center rounded border border-dashed border-gray-300 transition-colors"
      >
        <div class="flex flex-col items-center justify-center">
          <div class="text-sm text-gray-500">点击或拖拽文件到此区域上传</div>
          <div class="mt-1 text-xs text-gray-400">
            支持PDF、Word、Excel、PowerPoint、图片等格式，最多10个文件
          </div>
          <input
            type="file"
            class="hidden"
            multiple
            accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.jpg,.jpeg,.png,.gif"
            @change="handleFileChange($event, 'otherMaterials')"
          />
          <button
            type="button"
            class="bg-primary hover:bg-primary/90 mt-2 rounded px-4 py-1 text-xs text-white transition-colors"
            @click="
              ($event) => {
                $event.stopPropagation();
                $el.previousElementSibling?.click();
              }
            "
          >
            选择文件
          </button>
        </div>
      </div>

      <!-- 已上传文件列表 -->
      <div v-if="uploadedFiles.get('otherMaterials')?.length" class="mt-4">
        <div class="text-sm font-medium text-gray-700">已上传文件:</div>
        <div class="mt-2 space-y-2">
          <div
            v-for="(file, index) in uploadedFiles.get('otherMaterials')"
            :key="`other-${index}`"
            class="flex items-center justify-between rounded bg-gray-50 px-3 py-2 text-sm"
          >
            <div class="flex items-center truncate">
              <svg
                class="mr-2 h-5 w-5 text-gray-400"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
                xmlns="http://www.w3.org/2000/svg"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
                />
              </svg>
              <span class="truncate">{{ file.name }}</span>
              <span class="ml-2 text-xs text-gray-500">
                {{ (file.size / 1024 / 1024).toFixed(2) }}MB
              </span>
            </div>
            <button
              type="button"
              class="ml-2 text-red-500 hover:text-red-700"
              @click="handleRemoveFile(file, 'otherMaterials')"
            >
              删除
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
