<script lang="ts" setup>
/**
 * 超管队列探针弹窗：投递普通 / 延迟 / 失败各一条，用于验证监控与 available_at
 */
import { reactive, ref } from 'vue';

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

import {
  Alert,
  Form,
  FormItem,
  InputNumber,
  Select,
  message,
} from 'ant-design-vue';

import { createQueueJobProbe } from '../api';

const emit = defineEmits<{
  success: [];
}>();

const submitting = ref(false);
const form = reactive({
  delay_amount: 1,
  delay_unit: 'minute' as 'second' | 'minute' | 'hour' | 'day',
});

const unitOptions = [
  { label: '秒', value: 'second' },
  { label: '分钟', value: 'minute' },
  { label: '小时', value: 'hour' },
  { label: '天', value: 'day' },
];

const [Modal, modalApi] = useVbenModal({
  title: '创建测试队列任务',
  draggable: true,
  confirmText: '投递 3 条测试任务',
  async onConfirm() {
    if (!form.delay_amount || form.delay_amount < 1) {
      message.warning('请填写有效的延迟数值');
      return;
    }
    submitting.value = true;
    modalApi.setState({ confirmLoading: true });
    try {
      const res = await createQueueJobProbe({
        delay_amount: Number(form.delay_amount),
        delay_unit: form.delay_unit,
      });
      const data = res?.data || res || {};
      const availableAt = Number(data.available_at || 0);
      const availableTxt = availableAt
        ? new Date(availableAt * 1000).toLocaleString()
        : '-';
      message.success(
        `已投递：普通#${data.normal_id}、延迟#${data.delayed_id}（执行 ${availableTxt}）、失败#${data.fail_id}`,
      );
      emit('success');
      modalApi.close();
    } finally {
      submitting.value = false;
      modalApi.setState({ confirmLoading: false });
    }
  },
});
</script>

<template>
  <Modal class="w-[520px]">
    <Alert
      type="info"
      show-icon
      class="mb-4"
      message="将同时投递 3 条业务队列探针"
      description="① 普通立即执行 ② 延迟执行（下方自定义时间，写入 available_at） ③ 故意失败（可验证失败统计/OA）。请确认 queue:work 正在消费。"
    />
    <Form layout="vertical">
      <FormItem label="延迟时间" required>
        <div class="flex gap-2">
          <InputNumber
            v-model:value="form.delay_amount"
            :min="1"
            :max="9999"
            class="flex-1"
            placeholder="数值"
          />
          <Select
            v-model:value="form.delay_unit"
            :options="unitOptions"
            class="w-[120px]"
          />
        </div>
      </FormItem>
    </Form>
  </Modal>
</template>
