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

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

import { useUserStore } from '@vben/stores';

import {
  Button,
  message,
  Popconfirm,
  Select,
  Space,
  Table,
  Tag,
} from 'ant-design-vue';

import {
  getWorkflowInstancesApi,
  InstanceStatus,
  resumeWorkflowInstanceApi,
  suspendWorkflowInstanceApi,
  withdrawWorkflowInstanceApi,
  type WorkflowInstanceDto,
} from '#/api/core';
import { requestClient } from '#/api/request';

const router = useRouter();
const userStore = useUserStore();
const userId = computed(() => userStore.userInfo?.userId ?? '');
const loading = ref(false);
const data = ref<WorkflowInstanceDto[]>([]);
const total = ref(0);
const pageIndex = ref(1);
const pageSize = ref(20);
const statusFilter = ref<number | null>(null);
const userMap = ref<Record<string, string>>({});

const instanceStatusMap: Record<number, { color: string; text: string }> = {
  [InstanceStatus.Pending]: { color: 'blue', text: '待启动' },
  [InstanceStatus.Running]: { color: 'green', text: '运行中' },
  [InstanceStatus.Suspended]: { color: 'orange', text: '已挂起' },
  [InstanceStatus.Completed]: { color: 'cyan', text: '已完成' },
  [InstanceStatus.Terminated]: { color: 'red', text: '已终止' },
};

const statusOptions = [
  { value: null, label: '全部状态' },
  { value: InstanceStatus.Pending, label: '待启动' },
  { value: InstanceStatus.Running, label: '运行中' },
  { value: InstanceStatus.Suspended, label: '已挂起' },
  { value: InstanceStatus.Completed, label: '已完成' },
  { value: InstanceStatus.Terminated, label: '已终止' },
];

const columns = [
  { title: '标题', dataIndex: 'title', key: 'title', ellipsis: true },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    customRender: ({ record }: { record: WorkflowInstanceDto }) => {
      const s = instanceStatusMap[record.status];
      return h(Tag, { color: s?.color }, () => s?.text ?? '未知');
    },
  },
  {
    title: '发起人',
    dataIndex: 'initiatorId',
    key: 'initiatorId',
    ellipsis: true,
    width: 200,
    customRender: ({ text }: { text: string }) => userMap.value[text] || text,
  },
  {
    title: '启动时间',
    dataIndex: 'startedAt',
    key: 'startedAt',
    width: 180,
    customRender: ({ text }: { text: string }) => new Date(text).toLocaleString(),
  },
  {
    title: '完成时间',
    dataIndex: 'completedAt',
    key: 'completedAt',
    width: 180,
    customRender: ({ text }: { text: string | null }) => text ? new Date(text).toLocaleString() : '-',
  },
  { title: '操作', key: 'actions', width: 240 },
];

async function loadUserNames(ids: string[]) {
  if (ids.length === 0) return;
  const missing = ids.filter((id) => !userMap.value[id]);
  if (missing.length === 0) return;
  try {
    const users = await requestClient.get<{ id: string; username: string }[]>('/users');
    for (const u of users) {
      userMap.value[u.id] = u.username;
    }
  } catch {
    // ignore — will show raw ID
  }
}

async function loadData() {
  loading.value = true;
  try {
    const res = await getWorkflowInstancesApi({
      pageIndex: pageIndex.value,
      pageSize: pageSize.value,
      status: statusFilter.value ?? undefined,
    });
    const items = res.items ?? [];
    const ids = [...new Set(items.map((d) => d.initiatorId))];
    await loadUserNames(ids);
    data.value = items;
    total.value = res.total ?? 0;
  } catch {
    message.error('加载流程实例失败');
  } finally {
    loading.value = false;
  }
}

function handleTableChange(pagination: any) {
  pageIndex.value = pagination.current ?? 1;
  pageSize.value = pagination.pageSize ?? 20;
  loadData();
}

function onFilterChange() {
  pageIndex.value = 1;
  loadData();
}

async function handleSuspend(id: string) {
  try {
    await suspendWorkflowInstanceApi(id);
    message.success('已挂起');
    loadData();
  } catch {
    message.error('挂起失败');
  }
}

async function handleResume(id: string) {
  try {
    await resumeWorkflowInstanceApi(id);
    message.success('已恢复');
    loadData();
  } catch {
    message.error('恢复失败');
  }
}

async function handleWithdraw(id: string) {
  try {
    await withdrawWorkflowInstanceApi(id, userId.value);
    message.success('已撤回');
    loadData();
  } catch {
    message.error('撤回失败');
  }
}

onMounted(() => loadData());
</script>

<template>
  <Page auto-content-height>
    <div class="mb-4 flex justify-between">
      <Space>
        <h3 class="text-lg font-semibold">流程实例</h3>
        <Select
          v-model:value="statusFilter"
          :options="statusOptions"
          style="width: 140px"
          @change="onFilterChange"
        />
      </Space>
      <Button type="primary" @click="router.push('/workflow/start')">发起流程</Button>
    </div>

    <Table
      :columns="columns"
      :data-source="data"
      :loading="loading"
      :pagination="{ current: pageIndex, pageSize, total, showSizeChanger: true, showTotal: (t: number) => `共 ${t} 条` }"
      row-key="id"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'actions'">
          <Space>
            <Button v-if="record.status === InstanceStatus.Running" size="small" @click="handleSuspend(record.id)">挂起</Button>
            <Button v-if="record.status === InstanceStatus.Suspended" size="small" type="primary" @click="handleResume(record.id)">恢复</Button>
            <Popconfirm
              v-if="record.status === InstanceStatus.Running || record.status === InstanceStatus.Suspended"
              title="确定撤回此流程？"
              @confirm="handleWithdraw(record.id)"
            >
              <Button size="small" danger>撤回</Button>
            </Popconfirm>
          </Space>
        </template>
      </template>
    </Table>

</Page>
</template>
