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

import { useRouter } from 'vue-router';

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

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

import {
  createWorkflowDefinitionApi,
  deleteWorkflowDefinitionApi,
  disableWorkflowDefinitionApi,
  getWorkflowDefinitionsApi,
  publishWorkflowDefinitionApi,
  startWorkflowInstanceApi,
  updateWorkflowDefinitionApi,
  DefinitionStatus,
  type WorkflowDefinitionDto,
} from '#/api/core';

const router = useRouter();

function openDesigner(record: WorkflowDefinitionDto) {
  router.push(`/workflow/designer/${record.id}`);
}

const loading = ref(false);
const data = ref<WorkflowDefinitionDto[]>([]);
const total = ref(0);
const pageIndex = ref(1);
const pageSize = ref(20);

const createVisible = ref(false);
const editVisible = ref(false);
const startVisible = ref(false);
const formState = ref({ name: '', code: '', description: '' });
const editingId = ref('');
const startFormState = ref({ title: '', variables: '' });
const startDef = 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: '已禁用' },
};

const columns = [
  { title: '流程名称', dataIndex: 'name', key: 'name' },
  { title: '编码', dataIndex: 'code', key: 'code' },
  { title: '描述', dataIndex: 'description', key: 'description', ellipsis: true },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    customRender: ({ record }: { record: WorkflowDefinitionDto }) => {
      const s = statusMap[record.status];
      return h(Tag, { color: s?.color }, () => s?.text ?? '未知');
    },
  },
  { title: '版本', dataIndex: 'version', key: 'version', width: 80 },
  {
    title: '启用',
    dataIndex: 'isEnabled',
    key: 'isEnabled',
    width: 80,
    customRender: ({ record }: { record: WorkflowDefinitionDto }) =>
      h(Tag, { color: record.isEnabled ? 'green' : 'default' }, () => record.isEnabled ? '是' : '否'),
  },
  { title: '操作', key: 'actions', width: 340 },
];

async function loadData() {
  loading.value = true;
  try {
    const res = await getWorkflowDefinitionsApi({
      pageIndex: pageIndex.value,
      pageSize: pageSize.value,
    });
    data.value = res.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 openCreate() {
  formState.value = { name: '', code: '', description: '' };
  createVisible.value = true;
}

async function handleCreate() {
  try {
    await createWorkflowDefinitionApi(formState.value);
    message.success('创建成功');
    createVisible.value = false;
    loadData();
  } catch {
    message.error('创建失败');
  }
}

function openEdit(record: WorkflowDefinitionDto) {
  editingId.value = record.id;
  formState.value = { name: record.name, code: record.code, description: record.description ?? '' };
  editVisible.value = true;
}

async function handleEdit() {
  try {
    await updateWorkflowDefinitionApi(editingId.value, {
      name: formState.value.name,
      description: formState.value.description || undefined,
    });
    message.success('更新成功');
    editVisible.value = false;
    loadData();
  } catch {
    message.error('更新失败');
  }
}

async function handlePublish(id: string) {
  try {
    await publishWorkflowDefinitionApi(id);
    message.success('发布成功');
    loadData();
  } catch {
    message.error('发布失败');
  }
}

async function handleDisable(id: string) {
  try {
    await disableWorkflowDefinitionApi(id);
    message.success('已禁用');
    loadData();
  } catch {
    message.error('禁用失败');
  }
}

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

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

async function handleDelete(id: string) {
  try {
    await deleteWorkflowDefinitionApi(id);
    message.success('删除成功');
    loadData();
  } catch {
    message.error('删除失败');
  }
}

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

<template>
  <Page auto-content-height>
    <div class="mb-4 flex justify-between">
      <h3 class="text-lg font-semibold">流程定义</h3>
      <Button type="primary" @click="openCreate">新建流程</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: record }">
        <template v-if="column.key === 'actions'">
          <Space>
            <Button size="small" @click="openDesigner(record as WorkflowDefinitionDto)">
              设计
            </Button>
            <Button
              v-if="(record as WorkflowDefinitionDto).status === DefinitionStatus.Published && (record as WorkflowDefinitionDto).isEnabled"
              size="small"
              type="primary"
              @click="openStartForm(record as WorkflowDefinitionDto)"
            >
              发起
            </Button>
            <Button v-if="(record as WorkflowDefinitionDto).status === DefinitionStatus.Draft" size="small" type="primary" @click="handlePublish((record as WorkflowDefinitionDto).id)">发布</Button>
            <Button v-if="(record as WorkflowDefinitionDto).status === DefinitionStatus.Published" size="small" @click="handleDisable((record as WorkflowDefinitionDto).id)">禁用</Button>
            <Button size="small" @click="openEdit(record as WorkflowDefinitionDto)">编辑</Button>
            <Popconfirm title="确定删除此流程定义？" @confirm="handleDelete((record as WorkflowDefinitionDto).id)">
              <Button size="small" danger>删除</Button>
            </Popconfirm>
          </Space>
        </template>
      </template>
    </Table>

    <Modal v-model:open="createVisible" title="新建流程定义" @ok="handleCreate">
      <Form layout="vertical">
        <Form.Item label="流程名称" required>
          <Input v-model:value="formState.name" placeholder="请输入流程名称" />
        </Form.Item>
        <Form.Item label="流程编码" required>
          <Input v-model:value="formState.code" placeholder="请输入流程编码（英文）" />
        </Form.Item>
        <Form.Item label="描述">
          <Input.TextArea v-model:value="formState.description" placeholder="可选" :rows="3" />
        </Form.Item>
      </Form>
    </Modal>

    <Modal v-model:open="editVisible" title="编辑流程定义" @ok="handleEdit">
      <Form layout="vertical">
        <Form.Item label="流程名称" required>
          <Input v-model:value="formState.name" />
        </Form.Item>
        <Form.Item label="描述">
          <Input.TextArea v-model:value="formState.description" :rows="3" />
        </Form.Item>
      </Form>
    </Modal>

    <Modal
      v-model:open="startVisible"
      :title="`发起流程 - ${startDef?.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>
