<script lang="ts" setup>
/**
 * 队列任务操作记录弹窗：展示取消 / 重跑审计
 * 由列表点击标题打开
 */
import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Empty, Tag, Timeline } from 'ant-design-vue';

import { getQueueJobOpLogList } from '../api';
import { opTypeTagColor } from '../config/constants';

const title = ref('操作记录');
const items = ref<Record<string, any>[]>([]);
const loading = ref(false);

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  showConfirmButton: false,
  cancelText: '关闭',
  onCancel() {
    modalApi.close();
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      items.value = [];
      title.value = '操作记录';
      return;
    }
    const payload = modalApi.getData<{
      id?: number;
      title?: string;
    }>();
    const id = Number(payload?.id || 0);
    const jobTitle = String(payload?.title || '');
    title.value = jobTitle
      ? `操作记录 · #${id} ${jobTitle}`
      : `操作记录 · #${id}`;
    if (id <= 0) {
      items.value = [];
      return;
    }
    loading.value = true;
    modalApi.setState({ loading: true });
    try {
      const res = await getQueueJobOpLogList(id);
      const data = res?.data || res || {};
      items.value = Array.isArray(data.items) ? data.items : [];
      if (data.title) {
        title.value = `操作记录 · #${id} ${data.title}`;
      }
    } catch {
      items.value = [];
    } finally {
      loading.value = false;
      modalApi.setState({ loading: false });
    }
  },
});
</script>

<template>
  <Modal class="w-[90%] md:w-[560px]" :title="title">
    <Empty v-if="!loading && items.length === 0" description="暂无取消/重跑记录" />
    <Timeline v-else>
      <Timeline.Item v-for="row in items" :key="row.id">
        <div class="mb-1 flex items-center gap-2">
          <Tag :color="opTypeTagColor(Number(row.op_type))">
            {{ row.op_type_txt || row.op_type }}
          </Tag>
          <span class="text-xs text-gray-400">{{ row.created_at || '-' }}</span>
        </div>
        <div class="text-sm">
          操作人：{{ row.operator_name || '-' }}
          <span class="text-gray-400">（ID: {{ row.operator_id || 0 }}）</span>
        </div>
        <div v-if="Number(row.related_job_id) > 0" class="text-sm text-gray-600">
          关联任务：#{{ row.related_job_id }}
        </div>
        <div v-if="row.remark" class="text-xs text-gray-500">
          {{ row.remark }}
        </div>
      </Timeline.Item>
    </Timeline>
  </Modal>
</template>
