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

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

import {
  Button,
  Card,
  Form,
  Input,
  message,
  Modal,
  Spin,
  Tag,
} from 'ant-design-vue';

import {
  getWorkflowDefinitionsApi,
  startWorkflowInstanceApi,
  DefinitionStatus,
  type WorkflowDefinitionDto,
} from '#/api/core';

const loading = ref(false);
const definitions = ref<WorkflowDefinitionDto[]>([]);

const startVisible = ref(false);
const startFormState = ref({ title: '', variables: '' });
const currentDef = ref<WorkflowDefinitionDto | null>(null);

const statusMap: Record<number, { color: string; text: string }> = {
  [DefinitionStatus.Draft]: { color: 'blue', text: '草稿' },
  [DefinitionStatus.Published]: { color: 'green', text: '已发布' },
  [DefinitionStatus.Disabled]: { color: 'red', text: '已禁用' },
};

async function loadDefinitions() {
  loading.value = true;
  try {
    const res = await getWorkflowDefinitionsApi({ pageSize: 100 });
    definitions.value = (res.items ?? []).filter(
      (d) => d.status === DefinitionStatus.Published && d.isEnabled,
    );
  } catch {
    message.error('加载流程定义失败');
  } finally {
    loading.value = false;
  }
}

function openStartForm(def: WorkflowDefinitionDto) {
  currentDef.value = def;
  startFormState.value = { title: def.name, variables: '' };
  startVisible.value = true;
}

async function handleStart() {
  if (!currentDef.value) return;
  if (!startFormState.value.title.trim()) {
    message.warning('请填写流程标题');
    return;
  }
  try {
    await startWorkflowInstanceApi({
      definitionCode: currentDef.value.code,
      title: startFormState.value.title,
      variables: startFormState.value.variables.trim() || undefined,
    });
    message.success(`「${startFormState.value.title}」流程已发起`);
    startVisible.value = false;
  } catch {
    message.error('发起失败');
  }
}

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

<template>
  <Page auto-content-height>
    <div class="mb-4">
      <h3 class="text-lg font-semibold">发起流程</h3>
      <p class="mt-1 text-sm text-gray-500">选择需要发起的流程，填写信息后提交</p>
    </div>

    <Spin :spinning="loading">
      <div v-if="definitions.length > 0" class="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
        <Card
          v-for="def in definitions"
          :key="def.id"
          class="transition-shadow hover:shadow-md"
        >
          <template #title>
            <span class="text-base">{{ def.name }}</span>
          </template>
          <template #extra>
            <Tag color="green">v{{ def.version }}</Tag>
          </template>
          <p class="text-sm text-gray-500">
            {{ def.description || '暂无描述' }}
          </p>
          <div class="mt-3 text-right">
            <Button type="primary" size="small" @click="openStartForm(def)">发起</Button>
          </div>
        </Card>
      </div>
      <div v-else-if="!loading" class="py-12 text-center text-gray-400">
        暂无可发起的流程
      </div>
    </Spin>

    <Modal
      v-model:open="startVisible"
      :title="`发起流程 - ${currentDef?.name ?? ''}`"
      @ok="handleStart"
    >
      <Form layout="vertical">
        <Form.Item label="流程标题" required>
          <Input v-model:value="startFormState.title" placeholder="请输入流程标题" />
        </Form.Item>
        <Form.Item label="流程变量（JSON）">
          <Input.TextArea
            v-model:value="startFormState.variables"
            placeholder='可选，例如：{"reason": "出差申请", "amount": 5000}'
            :rows="4"
          />
        </Form.Item>
      </Form>
    </Modal>
  </Page>
</template>
