<script lang="ts" setup>
import { h, onMounted, ref } from 'vue';

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

import { Card, message, Statistic, Table } from 'ant-design-vue';

import {
  getOverdueTasksApi,
  getWorkflowMonitorApi,
  type WorkflowMonitorDto,
  type WorkflowTaskListItemDto,
} from '#/api/core';

const monitorLoading = ref(false);
const overdueLoading = ref(false);
const monitor = ref<WorkflowMonitorDto>({
  totalInstances: 0,
  runningInstances: 0,
  suspendedInstances: 0,
  completedInstances: 0,
  terminatedInstances: 0,
  pendingTasks: 0,
  overdueTasks: 0,
});
const overdueData = ref<WorkflowTaskListItemDto[]>([]);

const stats = computed(() => [
  { title: '总实例数', value: monitor.value.totalInstances, color: undefined },
  { title: '运行中', value: monitor.value.runningInstances, color: '#52c41a' },
  { title: '已挂起', value: monitor.value.suspendedInstances, color: '#faad14' },
  { title: '已完成', value: monitor.value.completedInstances, color: '#13c2c2' },
  { title: '已终止', value: monitor.value.terminatedInstances, color: '#ff4d4f' },
  { title: '待处理任务', value: monitor.value.pendingTasks, color: '#1890ff' },
  { title: '逾期任务', value: monitor.value.overdueTasks, color: '#ff4d4f' },
]);

import { computed } from 'vue';

const overdueColumns = [
  { title: '任务标题', dataIndex: 'title', key: 'title', ellipsis: true },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    customRender: () => h('span', { style: 'color: #ff4d4f' }, '逾期'),
  },
  {
    title: '处理人',
    dataIndex: 'assigneeId',
    key: 'assigneeId',
    ellipsis: true,
    width: 200,
  },
];

async function loadMonitor() {
  monitorLoading.value = true;
  try {
    const res = await getWorkflowMonitorApi();
    monitor.value = res;
  } catch {
    message.error('加载监控数据失败');
  } finally {
    monitorLoading.value = false;
  }
}

async function loadOverdue() {
  overdueLoading.value = true;
  try {
    const res = await getOverdueTasksApi({ pageIndex: 1, pageSize: 20 });
    overdueData.value = res.items ?? [];
  } catch {
    message.error('加载逾期任务失败');
  } finally {
    overdueLoading.value = false;
  }
}

onMounted(() => {
  loadMonitor();
  loadOverdue();
});
</script>

<template>
  <Page auto-content-height>
    <div class="mb-4">
      <h3 class="text-lg font-semibold">流程监控</h3>
    </div>

    <div class="mb-6 grid grid-cols-4 gap-4">
      <Card v-for="stat in stats" :key="stat.title" :loading="monitorLoading">
        <Statistic
          :title="stat.title"
          :value="stat.value"
          :value-style="stat.color ? { color: stat.color } : undefined"
        />
      </Card>
    </div>

    <div class="mb-2">
      <h4 class="text-base font-medium">逾期任务</h4>
    </div>

    <Table
      :columns="overdueColumns"
      :data-source="overdueData"
      :loading="overdueLoading"
      :pagination="false"
      row-key="id"
    />
  </Page>
</template>
