<template>
  <el-dialog v-model="visible" title="批量导入气象数据" width="450px" :close-on-click-modal="false">
    <el-upload
      ref="uploadRef"
      class="upload-demo"
      drag
      action="#"
      :auto-upload="false"
      :on-change="handleChange"
      :http-request="uploadFileRequest"
      :limit="1"
      :on-exceed="handleExceed"
      accept=".xlsx, .xls"
      :disabled="loading"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">将文件拖到此处，或 <em>点击选择</em></div>
      <template #tip>
        <div class="el-upload__tip" style="text-align: center;">
          只能上传 Excel 文件
        </div>
      </template>
    </el-upload>

    <template #footer>
      <span class="dialog-footer">
        <el-button :disabled="loading" @click="visible = false">取消</el-button>
        <el-button type="primary" :loading="loading" @click="dataFormSubmitHandle">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import baseService from "@/service/baseService";
import { useImportTaskStore } from "@/store/importTasks";

const taskStore = useImportTaskStore();
const POLL_INTERVAL = 3000;

const visible = ref(false);
const loading = ref(false);
const uploadRef = ref();
const fileRaw = ref<File | null>(null);
const emit = defineEmits(['refreshDataList']);

const init = () => {
  visible.value = true;
  fileRaw.value = null;
  if(uploadRef.value) uploadRef.value.clearFiles();
};

const handleChange = (file: any) => {
  fileRaw.value = file.raw;
};

const handleExceed = (files: any) => {
  uploadRef.value!.clearFiles();
  const file = files[0];
  uploadRef.value!.handleStart(file);
};

function pollProgress(taskId: string, localTaskId: string) {
  const timer = setInterval(async () => {
    try {
      const res = await baseService.get(`/dailyweather/weatherdailydata/import/progress/${taskId}`);
      if (res?.code === 0 && res.data) {
        const { totalRows, processedRows, errorMessage } = res.data;
        const st = (res.data.status || "").toUpperCase();
        taskStore.updateTask(localTaskId, {
          totalRows: totalRows || 0,
          processedRows: typeof processedRows === "object" ? 0 : (processedRows || 0)
        });
        if (st === "COMPLETED") {
          clearInterval(timer);
          taskStore.updateTask(localTaskId, { status: "success", message: "导入成功", completedAt: Date.now() });
          emit("refreshDataList");
        } else if (st === "FAILED" || st === "ERROR") {
          clearInterval(timer);
          taskStore.updateTask(localTaskId, { status: "error", message: errorMessage || "导入失败", completedAt: Date.now() });
        } else {
          const processed = typeof processedRows === "object" ? 0 : (processedRows || 0);
          const total = totalRows || 0;
          const pct = total > 0 ? Math.round((processed / total) * 100) : 0;
          taskStore.updateTask(localTaskId, { message: `正在导入数据 ${pct}% (${processed}/${total})` });
        }
      }
    } catch {
      // keep polling on network error
    }
  }, POLL_INTERVAL);
  return timer;
}

const dataFormSubmitHandle = () => {
  if (!fileRaw.value) {
    return ElMessage.warning("请先选择文件");
  }

  const localTaskId = Date.now().toString() + Math.random().toString(36).slice(2, 6);
  taskStore.addTask({
    id: localTaskId,
    fileName: fileRaw.value.name,
    status: "uploading",
    message: "正在上传文件...",
    totalRows: 0,
    processedRows: 0,
    createdAt: Date.now(),
    completedAt: null,
    backendTaskId: ""
  });

  visible.value = false;
  ElMessage.success("导入已开始，可在通知中心查看进度");

  const formData = new FormData();
  formData.append("file", fileRaw.value);

  baseService.upload("/dailyweather/weatherdailydata/import", formData)
    .then((res: any) => {
      if (res?.code === 0) {
        const backendTaskId = res.data?.taskId || res.data?.toString() || "";
        if (backendTaskId) {
          taskStore.updateTask(localTaskId, {
            status: "processing",
            message: "正在导入数据...",
            backendTaskId
          });
          pollProgress(backendTaskId, localTaskId);
        } else {
          taskStore.updateTask(localTaskId, { status: "success", message: "导入成功", completedAt: Date.now() });
          emit("refreshDataList");
        }
      } else {
        taskStore.updateTask(localTaskId, { status: "error", message: res?.msg || "导入失败", completedAt: Date.now() });
        ElMessage.error(res?.msg || "导入失败");
      }
    })
    .catch((err: any) => {
      taskStore.updateTask(localTaskId, { status: "error", message: err?.message || "网络错误", completedAt: Date.now() });
      console.error("上传细节错误:", err);
    });
};

defineExpose({ init });
</script>
