<template>
  <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body @close="cancel">
    <el-form ref="structuresFormRef" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="盲注表名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入盲注表名称" />
      </el-form-item>

      <el-form-item label="上传盲注表" prop="file">
        <div class="upload-container">
          <el-upload
            class="upload-demo"
            action="#"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :file-list="fileList"
            :auto-upload="false"
            :limit="1"
            accept=".xlsx,.xls"
          >
            <!-- 触发上传按钮 -->
            <template #trigger>
              <el-button type="primary">点击上传盲注表</el-button>
            </template>

            <!-- 自定义文件列表 -->
            <template #file="{ file }">
              <div style="display: flex; align-items: center">
                <span class="el-upload__tip">{{ file.name }}</span>
                <el-button type="text" icon="el-icon-delete" @click.stop="() => handleFileRemove(file)" style="margin-left: auto"> 删除 </el-button>
              </div>
            </template>

            <!-- 提示信息 -->
            <template #tip>
              <div class="el-upload__tip">
                <el-link type="primary" @click="downloadTemplate"> <i class="el-icon-download"></i> 模板下载 </el-link>
                |
                <el-button link @click="openPreview"> <i class="el-icon-document"></i> 预 览 </el-button>
              </div>
            </template>
          </el-upload>
        </div>
      </el-form-item>

      <el-form-item label="盲注表备注" prop="description">
        <el-input v-model="form.description" type="textarea" placeholder="请输入盲注表备注" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 预览弹窗 -->
  <el-dialog title="预览" v-model="previewVisible" width="70%" append-to-body>
    <div style="max-height: 500px; overflow-y: auto">
      <el-table :data="previewData" border v-if="previewData.length > 0">
        <!-- 使用动态表头 -->
        <el-table-column v-for="(header, index) in previewHeaders" :key="index" :label="header">
          <template #default="scope">
            {{ scope.row[index] }}
          </template>
        </el-table-column>
      </el-table>
      <p v-else>暂无数据可预览</p>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closePreview">关 闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="BlindStructureDialog" lang="ts">
import { ref, reactive, toRefs, watch } from 'vue';
import { ElMessage } from 'element-plus';
import * as XLSX from 'xlsx';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  mode: {
    type: String,
    default: 'add'
  },
  initialFormData: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['update:visible', 'submit']);

const dialog = reactive({
  visible: props.visible,
  title: props.mode === 'add' ? '新增盲注表' : '修改盲注表'
});

const buttonLoading = ref(false);
const fileList = ref([]);
const previewData = ref<any[]>([]);
const previewHeaders = ref<string[]>([]);
const previewVisible = ref(false);

const initFormData = {
  id: undefined,
  name: undefined,
  description: undefined
};

const data = reactive({
  form: { ...initFormData, ...props.initialFormData },
  rules: {
    name: [{ required: true, message: '盲注表名称不能为空', trigger: 'blur' }]
  }
});

const { form, rules } = toRefs(data);

watch(
  () => props.visible,
  (newVal) => {
    dialog.visible = newVal;
    if (!newVal) {
      reset();
    }
  }
);

const structuresFormRef = ref();

const cancel = () => {
  reset();
  emit('update:visible', false);
};

const reset = () => {
  Object.assign(data.form, initFormData);
  structuresFormRef.value?.resetFields();
  fileList.value = [];
  previewData.value = [];
  previewHeaders.value = [];
};

const submitForm = () => {
  structuresFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;

      try {
        const formData = new FormData();

        // 如果有文件，添加文件字段
        if (fileList.value.length > 0 && fileList.value[0].raw) {
          formData.append('file', fileList.value[0].raw); // 假设后端接收字段名为 'file'
        } else {
          buttonLoading.value = false;
          return ElMessage.error('文件内容为空');
        }

        // 添加常规字段
        formData.append('name', form.value.name || '');
        formData.append('description', form.value.description || '');

        emit('submit', formData);

        buttonLoading.value = false;
      } catch (error) {
        ElMessage.error('提交失败');
      }
    }
  });
};

const handleFileChange = (file) => {
  const index = fileList.value.findIndex((f) => f.uid === file.uid);

  // 如果文件不存在于列表中，则添加进去
  if (index === -1) {
    fileList.value.push(file);
  }
};

// 删除文件处理函数
const handleFileRemove = (file) => {
  const index = fileList.value.findIndex((f) => f.uid === file.uid);
  if (index > -1) {
    const newFileList = [...fileList.value];
    newFileList.splice(index, 1);
    fileList.value = newFileList;
  }
};

// 预览数据
const openPreview = () => {
  if (fileList.value.length === 0) {
    return;
  }

  const file = fileList.value[0].raw;
  const isValidType = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel'].includes(file.type);
  if (!isValidType) {
    return;
  }

  const reader = new FileReader();
  reader.onload = (e) => {
    const data = new Uint8Array(e.target?.result as ArrayBuffer);
    const workbook = XLSX.read(data, { type: 'array' });

    const sheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[sheetName];

    // 获取表头（第二行）
    const headerRow = XLSX.utils.decode_range(worksheet['!ref']).e.r + 1;
    const headerRange = `A2:E2`; // 假设最多5列
    const headerCells = XLSX.utils.decode_range(headerRange);
    previewHeaders.value = [];
    for (let C = headerCells.s.c; C <= headerCells.e.c; ++C) {
      const cellAddress = XLSX.utils.encode_cell({ c: C, r: 0 });
      const cell = worksheet[cellAddress];
      if (cell && cell.v) {
        previewHeaders.value.push(cell.v.toString());
      }
    }

    // 获取数据（第三行开始）
    const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1, range: 1 }); // 从第3行开始读取
    previewData.value = jsonData;
    previewVisible.value = true;
  };
  reader.readAsArrayBuffer(file);
};

const closePreview = () => {
  previewVisible.value = false;
};

const downloadTemplate = async () => {
  // 实现模板下载逻辑
};
</script>
