<template>
  <PageContainer title="导出任务中心">
    <QueryToolbar>
      <el-button v-if="canManage" type="primary" @click="openCreateDrawer">创建导出任务</el-button>
      <el-button v-if="canRead" @click="load">刷新</el-button>
    </QueryToolbar>

    <el-table :data="rows" class="mt-md" empty-text="暂无数据">
      <el-table-column prop="taskCode" label="任务编码" width="180" :formatter="taskCodeFormatter" />
      <el-table-column prop="bizType" label="业务类型" width="140" :formatter="bizTypeFormatter" />
      <el-table-column prop="bizId" label="业务ID" width="120" />
      <el-table-column prop="fileName" label="文件名" width="180" />
      <el-table-column prop="fileOssKey" label="文件OSS" />
      <el-table-column prop="status" label="状态" width="100" :formatter="statusFormatter" />
      <el-table-column prop="retryCount" label="重试" width="80" />
      <el-table-column prop="downloadCount" label="下载次数" width="90" />
      <el-table-column prop="tokenExpireAt" label="令牌过期" width="170" />
      <el-table-column prop="errorMessage" label="错误信息" />
      <el-table-column prop="createdAt" label="创建时间" width="170" />
      <el-table-column prop="finishedAt" label="完成时间" width="170" />
      <el-table-column label="操作" width="220">
        <template #default="{ row }">
          <el-button v-if="canManage" size="small" :disabled="row.status !== 'SUCCESS'" @click="handleRefreshToken(row)">刷新令牌</el-button>
          <el-button v-if="canRead" size="small" :disabled="!tokens[row.id]" @click="handleDownload(row)">下载</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-drawer v-model="createVisible" title="创建导出任务" :size="DRAWER_SIZE.md" destroy-on-close>
      <el-form ref="formRef" :model="form" label-position="left" :label-width="LABEL_WIDTH.md" :rules="formRules">
        <el-form-item label="任务编码" prop="taskCode"><el-input v-model="form.taskCode" /></el-form-item>
        <el-form-item label="业务类型" prop="bizType"><el-input v-model="form.bizType" /></el-form-item>
        <el-form-item label="业务ID" prop="bizId"><el-input v-model="form.bizId" /></el-form-item>
        <el-form-item label="文件名" prop="fileName"><el-input v-model="form.fileName" /></el-form-item>
        <el-form-item label="筛选JSON" prop="filtersJson"><el-input v-model="form.filtersJson" type="textarea" :rows="4" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createVisible = false">取消</el-button>
        <el-button v-if="canManage" type="primary" @click="handleCreate">创建</el-button>
      </template>
    </el-drawer>
  </PageContainer>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import PageContainer from "../../components/PageContainer.vue";
import QueryToolbar from "../../components/QueryToolbar.vue";
import { DRAWER_SIZE, LABEL_WIDTH } from "../../constants/ui";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { createExportTask, downloadExportTask, fetchExportTasks, refreshExportTaskToken } from "../../api/modules";
import { PERMS } from "../../constants/permissions";
import { useAuthStore } from "../../stores/auth";
import { toZhStatus } from "../../utils/status";

const TASK_CODE_TEXT_MAP: Record<string, string> = {
  EXPORT_LEDGER: "台账导出",
  PROJECT_EXPORT: "项目导出",
  USER_EXPORT: "用户导出",
  MEETING_EXPORT: "会议导出",
  NOTIFICATION_TASK_EXPORT: "通知任务导出",
  MEETING_MATERIAL_EXPORT: "会议资料包导出",
  MEETING_SUMMARY_GENERATE: "会议总结生成",
};

const BIZ_TYPE_TEXT_MAP: Record<string, string> = {
  FINANCE: "财务",
  PROJECT: "项目",
  USER: "用户",
  MEETING: "会议",
  MEETING_MATERIAL: "会议资料包",
  MEETING_SUMMARY: "会议总结",
  NOTIFICATION_TASK: "通知任务",
};

const authStore = useAuthStore();
const canRead = computed(() => authStore.hasPermission(PERMS.exportTask.read));
const canManage = computed(() => authStore.hasPermission(PERMS.exportTask.manage));
const rows = ref<any[]>([]);
const tokens = ref<Record<number, string>>({});
const createVisible = ref(false);
const form = ref({
  taskCode: "EXPORT_LEDGER",
  bizType: "FINANCE",
  bizId: "1001",
  fileName: "ledger-export.csv",
  filtersJson: "{\"projectId\":1001}",
});

const formRef = ref<FormInstance>();
const formRules = ref<FormRules>({
  taskCode: [{ required: true, message: "请输入任务编码", trigger: "blur" }],
  bizType: [{ required: true, message: "请输入业务类型", trigger: "blur" }],
  fileName: [{ required: true, message: "请输入文件名", trigger: "blur" }],
});

const statusFormatter = (_row: any, _column: any, value: unknown) => toZhStatus(value);
const taskCodeFormatter = (_row: any, _column: any, value: unknown) => TASK_CODE_TEXT_MAP[String(value || "").trim()] || String(value || "-");
const bizTypeFormatter = (_row: any, _column: any, value: unknown) => BIZ_TYPE_TEXT_MAP[String(value || "").trim()] || String(value || "-");

const openCreateDrawer = () => {
  form.value = {
    taskCode: "EXPORT_LEDGER",
    bizType: "FINANCE",
    bizId: "1001",
    fileName: "ledger-export.csv",
    filtersJson: "{\"projectId\":1001}",
  };
  createVisible.value = true;
};

const load = async () => {
  const resp = await fetchExportTasks();
  rows.value = resp?.data?.list || [];
};

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

  await createExportTask({
    idempotencyKey: `export-${Date.now()}`,
    taskCode: form.value.taskCode,
    bizType: form.value.bizType,
    bizId: form.value.bizId,
    fileName: form.value.fileName,
    filtersJson: form.value.filtersJson,
  });
  ElMessage.success("导出任务创建成功");
  createVisible.value = false;
  await load();
};

const handleRefreshToken = async (row: any) => {
  const resp = await refreshExportTaskToken(row.id);
  const token = resp?.data?.downloadToken || "";
  if (!token) {
    ElMessage.error("令牌刷新失败");
    return;
  }
  tokens.value[row.id] = token;
  ElMessage.success("下载令牌已刷新");
  await load();
};

const handleDownload = async (row: any) => {
  const token = tokens.value[row.id];
  if (!token) {
    ElMessage.warning("请先刷新下载令牌");
    return;
  }
  const resp = await downloadExportTask(row.id, { token });
  const signedUrl = String(resp?.data?.signedUrl || "").trim();
  if (!signedUrl) {
    ElMessage.error("下载地址生成失败");
    return;
  }
  window.open(signedUrl, "_blank", "noopener,noreferrer");
  ElMessage.success("下载地址已生成，已尝试打开新窗口");
  await load();
};

onMounted(async () => {
  if (canRead.value) {
    await load();
  }
});
</script>
