<template>
  <div>
    <el-dialog v-model="exportDialogVisible" title="导出" width="500" center align-center @close="close" draggable>
      <div class="dialog-content" v-loading="fullscreenLoading">
        <el-form class="formStyle" :rules="rules" ref="formRef" :model="exportObject">
          <el-form-item prop="timeValue">
            <el-date-picker
              v-model="exportObject.timeValue"
              type="datetimerange"
              format="YYYY-MM-DD HH:mm:ss"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              date-format="YYYY/MM/DD ddd"
              time-format="A hh:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item prop="spiderType">
            <el-checkbox-group v-model="exportObject.spiderType" class="checkboxStyle">
              <el-checkbox label="DSN数据" value="dsn" id="dsn-checkbox" />
              <el-checkbox label="ITU数据" value="itu" id="itu-checkbox" />
              <el-checkbox label="ST数据" value="spaceTrack" id="st-checkbox" />
              <el-checkbox label="ESA数据" value="esa" id="esa-checkbox" />
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="handleExport"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch } from "vue";
import axios from "axios";
import { ElLoading, ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

// ---------- 表单类型 ----------
interface RuleForm {
  timeValue: string[];
  spiderType: string[];
}

const formRef = ref<FormInstance>();

// ---------- 表单验证 ----------
const rules = ref<FormRules<RuleForm>>({
  timeValue: [
    {
      required: true,
      message: "请选择时间段",
      trigger: "change",
      validator: (rule, value, callback) => {
        if (!Array.isArray(value) || value.length !== 2) {
          callback(new Error("请选择完整的时间段"));
        } else {
          const isValid = value.every((date) => /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(date));
          isValid ? callback() : callback(new Error("时间格式不正确"));
        }
      },
    },
  ],
  spiderType: [
    {
      type: "array",
      required: true,
      message: "请至少选择一种数据类型",
      trigger: "change",
    },
  ],
});

// ---------- 表单绑定对象 ----------
const exportObject = ref({
  timeValue: [],
  spiderType: [],
});

const fullscreenLoading = ref(false);

// ---------- 父传值 ----------
const props = defineProps({
  dialogVisible: { type: Boolean, default: false },
});
const emit = defineEmits(["update:dialogVisible"]);
const exportDialogVisible = ref(props.dialogVisible);

// ---------- 自动下载 Blob 文件 ----------
const downloadBlob = (blob: Blob, fileName: string) => {
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = fileName;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  window.URL.revokeObjectURL(url);
};

// ---------- 处理导出 ----------
const handleExport = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (!valid) return;

    const loading = ElLoading.service({
      lock: true,
      text: "正在导出文件...",
      background: "rgba(0, 0, 0, 0.7)",
    });

    try {
      // 请求后端 ZIP 文件
      const res = await axios.post(
        "/api/export/downloadFile",
        {
          times: exportObject.value.timeValue,
          filters: exportObject.value.spiderType,
        },
        {
          responseType: "blob",
          headers: {
            Token: localStorage.getItem("Admin-Token") || "",
          },
        }
      );

      // 获取后端文件名
      let fileName = "export.zip";
      const disposition = res.headers["content-disposition"];
      if (disposition) {
        const match = disposition.match(/filename="?([^"]+)"?/);
        if (match) fileName = decodeURIComponent(match[1]);
      }

      // 自动下载
      downloadBlob(res.data, fileName);

      loading.close();
      ElMessage.success("导出成功");
      close();
    } catch (e) {
      console.error("导出失败", e);
      loading.close();
      ElMessage.error("导出失败，请重试");
    }
  });
};

// ---------- 关闭弹窗 ----------
const close = () => {
  exportObject.value = {
    timeValue: [],
    spiderType: [],
  };
  formRef.value?.clearValidate();
  exportDialogVisible.value = false;
};

// ---------- 同步父组件的 v-model ----------
watch(
  () => props.dialogVisible,
  (newVal) => {
    exportDialogVisible.value = newVal;
  }
);

watch(
  () => exportDialogVisible.value,
  (newVal) => {
    emit("update:dialogVisible", newVal);
  }
);
</script>

<style lang="scss" scoped>
.formStyle {
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.checkboxStyle {
  display: flex;
  gap: 30px;
  /* 复选框之间的间距 */
}
</style>
