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

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

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

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

import {
  approveTaskApi,
  delegateTaskApi,
  getHistoryTasksApi,
  getPendingTasksApi,
  rejectTaskApi,
  TaskStatus,
  transferTaskApi,
  type WorkflowTaskListItemDto,
} from '#/api/core';

const userStore = useUserStore();
const userId = computed(() => userStore.userInfo?.userId ?? '');

const activeTab = ref('pending');

// ── Pending ──

const pendingLoading = ref(false);
const pendingData = ref<WorkflowTaskListItemDto[]>([]);
const pendingTotal = ref(0);
const pendingPageIndex = ref(1);
const pendingPageSize = ref(20);

const pendingColumns = [
  { title: '任务标题', dataIndex: 'title', key: 'title', ellipsis: true },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    customRender: () => h(Tag, { color: 'orange' }, () => '待处理'),
  },
  {
    title: '处理人',
    dataIndex: 'assigneeId',
    key: 'assigneeId',
    ellipsis: true,
    width: 200,
  },
  { title: '操作', key: 'actions', width: 280 },
];

async function loadPending() {
  pendingLoading.value = true;
  try {
    const res = await getPendingTasksApi({
      userId: userId.value,
      pageIndex: pendingPageIndex.value,
      pageSize: pendingPageSize.value,
    });
    pendingData.value = res.items ?? [];
    pendingTotal.value = res.total ?? 0;
  } catch {
    message.error('加载待办任务失败');
  } finally {
    pendingLoading.value = false;
  }
}

function handlePendingTableChange(pagination: any) {
  pendingPageIndex.value = pagination.current ?? 1;
  pendingPageSize.value = pagination.pageSize ?? 20;
  loadPending();
}

// ── History ──

const historyLoading = ref(false);
const historyData = ref<WorkflowTaskListItemDto[]>([]);
const historyTotal = ref(0);
const historyPageIndex = ref(1);
const historyPageSize = ref(20);

const taskStatusMap: Record<number, { color: string; text: string }> = {
  [TaskStatus.Approved]: { color: 'green', text: '已通过' },
  [TaskStatus.Rejected]: { color: 'red', text: '已拒绝' },
  [TaskStatus.Transferred]: { color: 'blue', text: '已转办' },
  [TaskStatus.Delegated]: { color: 'purple', text: '已委派' },
  [TaskStatus.Pending]: { color: 'orange', text: '待处理' },
};

const historyColumns = [
  { title: '任务标题', dataIndex: 'title', key: 'title', ellipsis: true },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    customRender: ({ record }: { record: WorkflowTaskListItemDto }) => {
      const s = taskStatusMap[record.status];
      return h(Tag, { color: s?.color }, () => s?.text ?? '未知');
    },
  },
  {
    title: '处理人',
    dataIndex: 'assigneeId',
    key: 'assigneeId',
    ellipsis: true,
    width: 200,
  },
  {
    title: '完成时间',
    dataIndex: 'completedAt',
    key: 'completedAt',
    width: 180,
    customRender: ({ text }: { text: string | null }) =>
      text ? new Date(text).toLocaleString() : '-',
  },
];

async function loadHistory() {
  historyLoading.value = true;
  try {
    const res = await getHistoryTasksApi({
      userId: userId.value,
      pageIndex: historyPageIndex.value,
      pageSize: historyPageSize.value,
    });
    historyData.value = res.items ?? [];
    historyTotal.value = res.total ?? 0;
  } catch {
    message.error('加载已办任务失败');
  } finally {
    historyLoading.value = false;
  }
}

function handleHistoryTableChange(pagination: any) {
  historyPageIndex.value = pagination.current ?? 1;
  historyPageSize.value = pagination.pageSize ?? 20;
  loadHistory();
}

// ── Tab switch ──

function handleTabChange(key: string) {
  activeTab.value = key;
  if (key === 'pending' && pendingData.value.length === 0) loadPending();
  if (key === 'history' && historyData.value.length === 0) loadHistory();
}

// ── Action modals ──

const approveVisible = ref(false);
const rejectVisible = ref(false);
const delegateVisible = ref(false);
const transferVisible = ref(false);
const taskId = ref('');
const commentText = ref('');
const targetUserId = ref('');

function openApprove(id: string) {
  taskId.value = id;
  commentText.value = '';
  approveVisible.value = true;
}

async function handleApprove() {
  try {
    await approveTaskApi(
      taskId.value,
      userId.value,
      commentText.value || undefined,
    );
    message.success('审批通过');
    approveVisible.value = false;
    loadPending();
  } catch {
    message.error('审批失败');
  }
}

function openReject(id: string) {
  taskId.value = id;
  commentText.value = '';
  rejectVisible.value = true;
}

async function handleReject() {
  try {
    await rejectTaskApi(
      taskId.value,
      userId.value,
      commentText.value || undefined,
    );
    message.success('已拒绝');
    rejectVisible.value = false;
    loadPending();
  } catch {
    message.error('拒绝失败');
  }
}

function openDelegate(id: string) {
  taskId.value = id;
  targetUserId.value = '';
  delegateVisible.value = true;
}

async function handleDelegate() {
  if (!targetUserId.value) {
    message.warning('请输入目标用户 ID');
    return;
  }
  try {
    await delegateTaskApi(taskId.value, userId.value, targetUserId.value);
    message.success('已委派');
    delegateVisible.value = false;
    loadPending();
  } catch {
    message.error('委派失败');
  }
}

function openTransfer(id: string) {
  taskId.value = id;
  targetUserId.value = '';
  transferVisible.value = true;
}

async function handleTransfer() {
  if (!targetUserId.value) {
    message.warning('请输入目标用户 ID');
    return;
  }
  try {
    await transferTaskApi(taskId.value, userId.value, targetUserId.value);
    message.success('已转办');
    transferVisible.value = false;
    loadPending();
  } catch {
    message.error('转办失败');
  }
}

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

<template>
  <Page auto-content-height>
    <Tabs v-model:activeKey="activeTab" @change="handleTabChange">
      <Tabs.TabPane key="pending" tab="我的待办">
        <Table
          :columns="pendingColumns"
          :data-source="pendingData"
          :loading="pendingLoading"
          :pagination="{
            current: pendingPageIndex,
            pageSize: pendingPageSize,
            total: pendingTotal,
            showSizeChanger: true,
            showTotal: (t: number) => `共 ${t} 条`,
          }"
          row-key="id"
          @change="handlePendingTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'actions'">
              <Space>
                <Button
                  size="small"
                  type="primary"
                  @click="openApprove(record.id)"
                >
                  审批
                </Button>
                <Button size="small" danger @click="openReject(record.id)">
                  拒绝
                </Button>
                <Button size="small" @click="openDelegate(record.id)">
                  委派
                </Button>
                <Button size="small" @click="openTransfer(record.id)">
                  转办
                </Button>
              </Space>
            </template>
          </template>
        </Table>
      </Tabs.TabPane>

      <Tabs.TabPane key="history" tab="我的已办">
        <Table
          :columns="historyColumns"
          :data-source="historyData"
          :loading="historyLoading"
          :pagination="{
            current: historyPageIndex,
            pageSize: historyPageSize,
            total: historyTotal,
            showSizeChanger: true,
            showTotal: (t: number) => `共 ${t} 条`,
          }"
          row-key="id"
          @change="handleHistoryTableChange"
        />
      </Tabs.TabPane>
    </Tabs>

    <Modal v-model:open="approveVisible" title="审批通过" @ok="handleApprove">
      <Form layout="vertical">
        <Form.Item label="审批意见">
          <Input.TextArea
            v-model:value="commentText"
            placeholder="可选"
            :rows="3"
          />
        </Form.Item>
      </Form>
    </Modal>

    <Modal v-model:open="rejectVisible" title="拒绝任务" @ok="handleReject">
      <Form layout="vertical">
        <Form.Item label="拒绝原因">
          <Input.TextArea
            v-model:value="commentText"
            placeholder="可选"
            :rows="3"
          />
        </Form.Item>
      </Form>
    </Modal>

    <Modal
      v-model:open="delegateVisible"
      title="委派任务"
      @ok="handleDelegate"
    >
      <Form layout="vertical">
        <Form.Item label="目标用户 ID" required>
          <Input
            v-model:value="targetUserId"
            placeholder="请输入用户 GUID"
          />
        </Form.Item>
      </Form>
    </Modal>

    <Modal
      v-model:open="transferVisible"
      title="转办任务"
      @ok="handleTransfer"
    >
      <Form layout="vertical">
        <Form.Item label="目标用户 ID" required>
          <Input
            v-model:value="targetUserId"
            placeholder="请输入用户 GUID"
          />
        </Form.Item>
      </Form>
    </Modal>
  </Page>
</template>
