import {
  CheckOutlined,
  DeleteOutlined,
  EditOutlined,
  FormOutlined,
  PlusOutlined,
  ReloadOutlined,
  SendOutlined,
  SyncOutlined,
  TeamOutlined,
  WarningOutlined,
} from '@ant-design/icons'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import {
  App,
  Alert,
  Button,
  Card,
  Descriptions,
  Drawer,
  Form,
  Input,
  InputNumber,
  Modal,
  Select,
  Space,
  Statistic,
  Switch,
  Table,
  Tabs,
  Tag,
  Typography,
} from 'antd'
import type { TableColumnsType } from 'antd'
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router'

import JsonPreview from '@/components/admin/JsonPreview'
import ImageUpload from '@/components/files/ImageUpload'
import ImagePreviewList from '@/components/files/ImagePreviewList'
import PageHeader from '@/components/admin/PageHeader'
import {
  acceptAdminWorkOrder,
  createAdminMockWorkOrder,
  creditAdminWorkerWallet,
  deductAdminWorkOrderPendingDeposit,
  deleteAdminWorkCategory,
  deleteAdminWorkOrder,
  deleteAdminWorkerLevel,
  fetchAdminWorkerFinanceConfig,
  fetchAdminWorkerFinanceRequests,
  fetchAdminWorkCategories,
  fetchAdminWorkOrderSharing,
  fetchAdminWorkProductRules,
  fetchAdminWorkerLevels,
  fetchAdminWorkerPlatformSummary,
  fetchAdminWorkerUsers,
  fetchAdminWorkOrders,
  markAdminWorkOrderProblem,
  publishAdminWorkOrder,
  reviewAdminWorkerFinanceRequest,
  resolveAdminProblemWorkOrder,
  reviewAdminWorkerUser,
  saveAdminWorkerFinanceConfig,
  saveAdminWorkCategory,
  saveAdminWorkProductRule,
  saveAdminWorkerLevel,
  submitAdminWorkOrderMaterial,
  syncAdminWorkerOrdersFromSource,
  unpublishAdminWorkOrder,
  updateAdminWorkOrder,
  updateAdminWorkOrderSharing,
} from '@/services/admin'
import type {
  CollectField,
  UploadedFile,
  WorkCategory,
  WorkOrder,
  WorkOrderShare,
  WorkProductRule,
  WorkerFinanceConfig,
  WorkerFinanceRequest,
  WorkerLevel,
  WorkerUser,
} from '@/types/worker-platform'
import {
  ADMIN_DEFAULT_PAGE_SIZE,
  buildAdminTablePagination,
} from '@/utils/admin-pagination'
import { formatAdminDateTime } from '@/utils/admin-time'
import {
  DeadlineCountdown,
  formatTimeoutPolicyLabel,
  getAcceptanceFiles,
  getAcceptanceImageUrls,
  getAcceptanceSubmittedAt,
  getMaterialFields,
  getMaterialDetailItems,
  getMaterialScreenshots,
  getRequirementFields,
  renderDetailFieldValues,
  renderMaterialSummary,
  renderRequirementFieldValues,
  formatMoney,
  formatSharingShareStatus,
  formatStatus,
  resolveSharingShareStatusColor,
  resolveStatusColor,
  type DetailFieldItem,
} from './shared'

export default function WorkOrdersPanel() {
  const { message, modal } = App.useApp()
  const navigate = useNavigate()
  const queryClient = useQueryClient()
  const [status, setStatus] = useState('')
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(ADMIN_DEFAULT_PAGE_SIZE)
  const [detailOrder, setDetailOrder] = useState<WorkOrder | null>(null)
  const [problemOrder, setProblemOrder] = useState<WorkOrder | null>(null)
  const [resolutionOrder, setResolutionOrder] = useState<WorkOrder | null>(null)
  const [materialOrder, setMaterialOrder] = useState<WorkOrder | null>(null)
  const [materialScreenshots, setMaterialScreenshots] = useState<UploadedFile[]>([])
  const [sharingOrder, setSharingOrder] = useState<WorkOrder | null>(null)
  const [editOrder, setEditOrder] = useState<WorkOrder | null>(null)
  const [deductOrder, setDeductOrder] = useState<WorkOrder | null>(null)
  const [problemForm] = Form.useForm()
  const [resolutionForm] = Form.useForm()
  const [materialForm] = Form.useForm()
  const [deductForm] = Form.useForm<{ amount?: number; note?: string }>()
  const [editForm] = Form.useForm<{
    productName?: string
    platformOrderId?: string
    categoryId?: number | null
    rewardAmount?: number
    requiredDepositAmount?: number
    fieldsText?: string
    timeoutMinutes?: number
    timeoutPolicy?: string
  }>()
  const [sharingForm] = Form.useForm<{
    enabled?: boolean
    totalQuantity?: number
    unitReward?: number
    totalAmount?: number
  }>()

  const ordersQuery = useQuery({
    queryKey: ['admin-worker-platform-orders', status, page, pageSize],
    queryFn: () => fetchAdminWorkOrders({ status, page, pageSize }),
  })
  const ordersPagination = ordersQuery.data?.data.pagination
  const categoriesQuery = useQuery({
    queryKey: ['admin-worker-platform-categories'],
    queryFn: () => fetchAdminWorkCategories(),
  })
  const sharingQuery = useQuery({
    queryKey: ['admin-worker-platform-order-sharing', sharingOrder?.workOrderId],
    queryFn: () => fetchAdminWorkOrderSharing(Number(sharingOrder?.workOrderId)),
    enabled: Boolean(sharingOrder),
  })

  function openSharingConfigModal(row: WorkOrder) {
    setSharingOrder(row)
    const unitRewardFen = Number(row.sharing?.unitReward || 0)
    const totalQuantity = Number(row.sharing?.totalQuantity || 1)
    const unitRewardYuan = unitRewardFen / 100
    sharingForm.setFieldsValue({
      enabled: row.sharing?.enabled,
      totalQuantity,
      unitReward: unitRewardYuan,
      totalAmount: unitRewardYuan * totalQuantity,
    })
  }

  function syncSharingForm(next: {
    totalQuantity?: number
    unitReward?: number
    totalAmount?: number
  }) {
    const values = sharingForm.getFieldsValue()
    const unitReward = Number(next.unitReward ?? values.unitReward ?? 0)
    const totalQuantity = Number(next.totalQuantity ?? values.totalQuantity ?? 1)
    const totalAmount = Number(next.totalAmount ?? values.totalAmount ?? 0)
    if (next.totalAmount !== undefined) {
      const quantity = unitReward > 0 ? Math.max(1, Math.round(totalAmount / unitReward)) : 1
      sharingForm.setFieldsValue({
        totalQuantity: quantity,
        totalAmount: quantity * unitReward,
      })
      return
    }
    sharingForm.setFieldsValue({
      totalAmount: unitReward * totalQuantity,
    })
  }

  async function submitSharingConfig(values: {
    enabled?: boolean
    totalQuantity?: number
    unitReward?: number
    totalAmount?: number
  }) {
    if (!sharingOrder) return
    const succeeded = await runAction(
      () =>
        updateAdminWorkOrderSharing(sharingOrder.workOrderId, {
          enabled: values.enabled !== false,
          totalQuantity: Number(values.totalQuantity || 1),
          unitReward: Number(values.unitReward || 0),
          totalAmount: Number(values.totalAmount || 0),
        }),
      '拼单配置已保存',
    )
    if (!succeeded) return
    setSharingOrder(null)
    sharingForm.resetFields()
  }

  async function refreshAll() {
    await Promise.all([
      queryClient.invalidateQueries({
        queryKey: ['admin-worker-platform-orders'],
      }),
      queryClient.invalidateQueries({
        queryKey: ['admin-worker-platform-summary'],
      }),
    ])
  }

  async function runAction(
    action: () => Promise<unknown>,
    successMessage: string,
  ) {
    try {
      await action()
      message.success(successMessage)
      await refreshAll()
      return true
    } catch (error) {
      message.error(error instanceof Error ? error.message : '操作失败')
      return false
    }
  }

  async function submitProblem(values: { note?: string }) {
    if (!problemOrder) return
    const succeeded = await runAction(
      () =>
        markAdminWorkOrderProblem(problemOrder.workOrderId, values.note || ''),
      '已标记问题单',
    )
    if (!succeeded) return
    setProblemOrder(null)
    problemForm.resetFields()
  }

  async function submitResolution(values: {
    action?: 'return_to_worker' | 'reopen' | 'cancel_release' | 'cancel_deduct'
    note?: string
  }) {
    if (!resolutionOrder || !values.action) return
    const action = values.action
    const succeeded = await runAction(
      () =>
        resolveAdminProblemWorkOrder(resolutionOrder.workOrderId, {
          action,
          note: values.note || '',
        }),
      '问题单已处置',
    )
    if (!succeeded) return
    setResolutionOrder(null)
    resolutionForm.resetFields()
  }

  async function submitMaterial(values: {
    fields?: Record<string, string>
    screenshots?: UploadedFile[]
  }) {
    if (!materialOrder) return
    const succeeded = await runAction(
      () =>
        submitAdminWorkOrderMaterial(
          materialOrder.workOrderId,
          values.fields || {},
          values.screenshots || [],
        ),
      '订单资料已保存',
    )
    if (!succeeded) return
    setMaterialOrder(null)
    materialForm.resetFields()
    setMaterialScreenshots([])
  }

  async function submitSourceSync(values: { platformOrderId?: string }) {
    try {
      const result = await syncAdminWorkerOrdersFromSource({
        platformOrderId: String(values.platformOrderId || '').trim(),
      })
      message.success(
        `同步完成，新增 ${result.data.createdCount} 个，跳过 ${result.data.skippedCount} 个`,
      )
      await refreshAll()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '同步失败')
    }
  }

  function openMaterialModal(row: WorkOrder) {
    setMaterialOrder(row)
    materialForm.setFieldsValue({ fields: getMaterialFields(row) })
    setMaterialScreenshots([])
  }

  function openDetailDrawer(row: WorkOrder) {
    setDetailOrder(row)
  }

  function openEditModal(row: WorkOrder) {
    setEditOrder(row)
    editForm.setFieldsValue({
      productName: row.productName,
      platformOrderId: row.platformOrderId || '',
      categoryId: row.categoryId ?? undefined,
      rewardAmount: Math.round(Number(row.rewardAmount || 0)) / 100,
      requiredDepositAmount:
        Math.round(Number(row.requiredDepositAmount || 0)) / 100,
      fieldsText: formatRequirementFieldsText(getRequirementFields(row)),
      timeoutMinutes: Number(row.timeoutMinutes || 0),
      timeoutPolicy: row.timeoutPolicy || 'reopen',
    })
  }

  function openDeductModal(row: WorkOrder) {
    setDeductOrder(row)
    deductForm.setFieldsValue({
      amount: Math.round(Number(row.pendingUnfreezeAmount || 0)) / 100,
      note: '',
    })
  }

  async function submitDeduct(values: { amount?: number; note?: string }) {
    if (!deductOrder) return
    const succeeded = await runAction(
      () =>
        deductAdminWorkOrderPendingDeposit(deductOrder.workOrderId, {
          amount: Number(values.amount || 0),
          note: String(values.note || '').trim(),
        }),
      '待解冻押金已扣减',
    )
    if (!succeeded) return
    setDeductOrder(null)
    deductForm.resetFields()
  }

  async function submitEdit(values: {
    productName?: string
    platformOrderId?: string
    categoryId?: number | null
    rewardAmount?: number
    requiredDepositAmount?: number
    fieldsText?: string
    timeoutMinutes?: number
    timeoutPolicy?: string
  }) {
    if (!editOrder) return
    const succeeded = await runAction(
      () =>
        updateAdminWorkOrder(editOrder.workOrderId, {
          productName: String(values.productName || '').trim(),
          platformOrderId: String(values.platformOrderId || '').trim(),
          categoryId: values.categoryId || null,
          rewardAmount: Number(values.rewardAmount || 0),
          requiredDepositAmount: Number(values.requiredDepositAmount || 0),
          fieldsText: String(values.fieldsText || ''),
          timeoutMinutes: Math.max(0, Number(values.timeoutMinutes || 0)),
          timeoutPolicy: values.timeoutPolicy || 'reopen',
        }),
      '工单信息已保存',
    )
    if (!succeeded) return
    setEditOrder(null)
    editForm.resetFields()
  }

  function requestDeleteWorkOrder(row: WorkOrder) {
    modal.confirm({
      title: `确认删除工单 ${row.workOrderNo}？`,
      content:
        '删除后工单将从列表中移除，且不可恢复。仅未分配、待完善或已取消且无拼单参与的工单可删除。',
      okText: '确认删除',
      okButtonProps: { danger: true },
      cancelText: '取消',
      onOk: () =>
        runAction(
          () => deleteAdminWorkOrder(row.workOrderId),
          '工单已删除',
        ),
    })
  }

  const columns: TableColumnsType<WorkOrder> = [
    {
      title: '订单',
      minWidth: 300,
      render: (_, row) => (
        <div className="cell-stack">
          <Typography.Link onClick={() => openDetailDrawer(row)}>
            {row.productName || row.workOrderNo}
          </Typography.Link>
          <Space size={[6, 6]} wrap>
            {row.categoryName ? <Tag>{row.categoryName}</Tag> : null}
            {row.orderId ? (
              <Typography.Text type="secondary">
                源订单 #{row.orderId}
              </Typography.Text>
            ) : null}
          </Space>
          <Typography.Text type="secondary">
            {row.platformOrderId} · {row.workOrderNo}
          </Typography.Text>
        </div>
      ),
    },
    {
      title: '金额',
      width: 110,
      render: (_, row) => formatMoney(row.rewardAmount),
    },
    {
      title: '押金',
      width: 110,
      render: (_, row) => formatMoney(row.requiredDepositAmount),
    },
    {
      title: '时限',
      width: 190,
      render: (_, row) => {
        const minutes = Number(row.timeoutMinutes || 0)
        if (minutes <= 0) {
          return <Typography.Text type="secondary">不限时</Typography.Text>
        }
        return (
          <div className="cell-stack">
            <Space wrap size={6}>
              <Tag color="blue">{minutes} 分钟</Tag>
              <Typography.Text type="secondary">
                {formatTimeoutPolicyLabel(row.timeoutPolicy)}
              </Typography.Text>
            </Space>
            {row.status === 'in_progress' && row.deadlineAt ? (
              <DeadlineCountdown deadlineAt={row.deadlineAt} showExpired />
            ) : null}
            {row.deadlineAt ? (
              <Typography.Text type="secondary">
                截止 {formatAdminDateTime(row.deadlineAt)}
              </Typography.Text>
            ) : null}
          </div>
        )
      },
    },
    {
      title: '拼单',
      width: 190,
      render: (_, row) =>
        row.sharing?.enabled ? (
          <div className="cell-stack">
            <Tag color="purple">
              单价 {formatMoney(row.sharing.unitReward)} / 共 {row.sharing.totalQuantity} 份
            </Tag>
            <Typography.Text type="secondary">
              已拼 {row.sharingProgress?.joinedQuantity || 0} / {row.sharing.totalQuantity} 份
              {row.sharingProgress?.pendingSubmissionCount
                ? ` · ${row.sharingProgress.pendingSubmissionCount} 人待提交`
                : ''}
            </Typography.Text>
          </div>
        ) : (
          <Typography.Text type="secondary">未启用</Typography.Text>
        ),
    },
    {
      title: '状态',
      width: 130,
      render: (_, row) => (
        <Tag color={resolveStatusColor(row.status)}>
          {formatStatus(row.status)}
        </Tag>
      ),
    },
    {
      title: '打手',
      width: 140,
      render: (_, row) =>
        row.worker?.displayName || row.worker?.username || '-',
    },
    {
      title: '资料',
      width: 160,
      render: (_, row) => renderMaterialSummary(row),
    },
    {
      title: '验收图',
      width: 170,
      render: (_, row) => (
        <ImagePreviewList
          files={getAcceptanceFiles(row)}
          imageUrls={getAcceptanceImageUrls(row)}
          size={44}
        />
      ),
    },
    {
      title: '操作',
      width: 400,
      render: (_, row) => (
        <Space wrap>
          <Button onClick={() => openDetailDrawer(row)}>详情</Button>
          {['pending_material', 'unassigned', 'open'].includes(row.status) ? (
            <Button
              icon={<EditOutlined />}
              onClick={() => openEditModal(row)}
            >
              编辑
            </Button>
          ) : null}
          {['pending_material', 'unassigned', 'cancelled'].includes(row.status) ? (
            <Button
              danger
              icon={<DeleteOutlined />}
              onClick={() => requestDeleteWorkOrder(row)}
            >
              删除
            </Button>
          ) : null}
          {['pending_material', 'unassigned', 'open'].includes(row.status) ? (
            <Button
              icon={<TeamOutlined />}
              onClick={() => openSharingConfigModal(row)}
            >
              拼单配置
            </Button>
          ) : null}
          {row.status === 'pending_material' ? (
            <Button
              icon={<FormOutlined />}
              onClick={() => openMaterialModal(row)}
            >
              补资料
            </Button>
          ) : null}
          {row.status === 'unassigned' ? (
            <Button
              icon={<SendOutlined />}
              onClick={() =>
                runAction(
                  () => publishAdminWorkOrder(row.workOrderId),
                  '已发布到大厅',
                )
              }
            >
              发布
            </Button>
          ) : null}
          {row.status === 'open' ? (
            <Button
              danger
              onClick={() => {
                modal.confirm({
                  title: '确认下架该订单？',
                  content: '下架后订单会回到未分配状态，不再在抢单大厅展示。',
                  okText: '确认下架',
                  cancelText: '取消',
                  onOk: () =>
                    runAction(
                      () => unpublishAdminWorkOrder(row.workOrderId),
                      '订单已撤回到未分配',
                    ),
                })
              }}
            >
              下架
            </Button>
          ) : null}
          {row.status === 'pending_acceptance' ? (
            <Button
              icon={<CheckOutlined />}
              type="primary"
              onClick={() =>
                runAction(
                  () => acceptAdminWorkOrder(row.workOrderId),
                  '已验收通过',
                )
              }
            >
              验收
            </Button>
          ) : null}
          {row.status === 'accepted' && Number(row.pendingUnfreezeAmount || 0) > 0 ? (
            <Button
              icon={<WarningOutlined />}
              danger
              onClick={() => openDeductModal(row)}
            >
              扣押金
            </Button>
          ) : null}
          {['in_progress', 'pending_acceptance'].includes(row.status) ? (
            <Button
              icon={<WarningOutlined />}
              danger
              onClick={() => setProblemOrder(row)}
            >
              问题单
            </Button>
          ) : null}
          {row.status === 'problem' ? (
            <Button icon={<FormOutlined />} onClick={() => setResolutionOrder(row)}>
              处置
            </Button>
          ) : null}
        </Space>
      ),
    },
  ]

  return (
    <section className="platform-panel-stack">
      <Card title="从源订单同步" bordered={false}>
        <Form layout="inline" onFinish={submitSourceSync}>
          <Form.Item
            label="平台订单号"
            name="platformOrderId"
            rules={[{ required: true, message: '请输入平台订单号' }]}
          >
            <Input
              placeholder="用户填写链接 A 的订单号"
              style={{ width: 260 }}
            />
          </Form.Item>
          <Form.Item>
            <Button type="primary" icon={<SyncOutlined />} htmlType="submit">
              同步
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Card title="生成本地接单工单 Mock" bordered={false}>
        <MockWorkOrderForm onCreated={refreshAll} />
      </Card>
      <Card
        title="接单工单"
        extra={
          <Space>
            <Select
              value={status}
              style={{ width: 150 }}
              options={[
                { value: '', label: '全部状态' },
                { value: 'pending_material', label: '待完善' },
                { value: 'unassigned', label: '未分配' },
                { value: 'open', label: '待抢单' },
                { value: 'in_progress', label: '代练中' },
                { value: 'pending_acceptance', label: '待验收' },
                { value: 'problem', label: '问题单' },
                { value: 'accepted', label: '已验收' },
                { value: 'cancelled', label: '已取消' },
              ]}
              onChange={(nextStatus) => {
                setStatus(nextStatus)
                setPage(1)
              }}
            />
            <Button
              icon={<ReloadOutlined />}
              loading={ordersQuery.isFetching}
              onClick={() => ordersQuery.refetch()}
            >
              刷新
            </Button>
          </Space>
        }
        bordered={false}
      >
        <Table<WorkOrder>
          rowKey="workOrderId"
          loading={ordersQuery.isLoading}
          dataSource={ordersQuery.data?.data.items || []}
          columns={columns}
          pagination={buildAdminTablePagination({
            current: ordersPagination?.page || page,
            pageSize: ordersPagination?.pageSize || pageSize,
            total: ordersPagination?.total || 0,
            onChange: (nextPage, nextPageSize) => {
              setPage(nextPage)
              setPageSize(nextPageSize)
            },
          })}
          scroll={{ x: 1240 }}
        />
      </Card>

      <Drawer
        title={
          detailOrder
            ? `${detailOrder.productName || '工单详情'} · ${detailOrder.workOrderNo}`
            : '工单详情'
        }
        width={860}
        open={Boolean(detailOrder)}
        destroyOnHidden
        onClose={() => setDetailOrder(null)}
        extra={
          detailOrder ? (
            <Space>
              <Tag color={resolveStatusColor(detailOrder.status)}>
                {formatStatus(detailOrder.status)}
              </Tag>
              {detailOrder.orderId ? (
                <Button
                  onClick={() => {
                    const orderId = detailOrder.orderId
                    setDetailOrder(null)
                    navigate(`/admin/orders/${orderId}`)
                  }}
                >
                  查看源订单
                </Button>
              ) : null}
            </Space>
          ) : null
        }
      >
        {detailOrder ? (
          <div className="worker-order-detail-stack">
            <Card title="基础信息" size="small">
              <Descriptions column={{ xs: 1, md: 2 }} bordered size="small">
                <Descriptions.Item label="工单号">
                  {detailOrder.workOrderNo}
                </Descriptions.Item>
                <Descriptions.Item label="平台订单号">
                  {detailOrder.platformOrderId || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="源订单 ID">
                  {detailOrder.orderId || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="订单子项 ID">
                  {detailOrder.orderItemId || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="商品">
                  {detailOrder.productName || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="分类">
                  {detailOrder.categoryName || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="状态">
                  <Tag color={resolveStatusColor(detailOrder.status)}>
                    {formatStatus(detailOrder.status)}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="打手">
                  {detailOrder.worker?.displayName ||
                    detailOrder.worker?.username ||
                    '-'}
                </Descriptions.Item>
                <Descriptions.Item label="接单金额">
                  {formatMoney(detailOrder.rewardAmount)}
                </Descriptions.Item>
                <Descriptions.Item label="押金">
                  {formatMoney(detailOrder.requiredDepositAmount)}
                </Descriptions.Item>
                <Descriptions.Item label="任务时限">
                  {Number(detailOrder.timeoutMinutes || 0) > 0
                    ? `${detailOrder.timeoutMinutes} 分钟`
                    : '不限时'}
                </Descriptions.Item>
                <Descriptions.Item label="超时策略">
                  {formatTimeoutPolicyLabel(detailOrder.timeoutPolicy)}
                </Descriptions.Item>
                <Descriptions.Item label="超时截止">
                  {detailOrder.deadlineAt ? (
                    <Space wrap size={8}>
                      <DeadlineCountdown
                        deadlineAt={detailOrder.deadlineAt}
                        showExpired
                      />
                      <Typography.Text type="secondary">
                        {formatAdminDateTime(detailOrder.deadlineAt)}
                      </Typography.Text>
                    </Space>
                  ) : (
                    '-'
                  )}
                </Descriptions.Item>
                <Descriptions.Item label="发布时间">
                  {formatAdminDateTime(detailOrder.publishedAt)}
                </Descriptions.Item>
                <Descriptions.Item label="接单时间">
                  {formatAdminDateTime(detailOrder.assignedAt)}
                </Descriptions.Item>
                <Descriptions.Item label="提交验收">
                  {formatAdminDateTime(getAcceptanceSubmittedAt(detailOrder))}
                </Descriptions.Item>
                <Descriptions.Item label="验收通过">
                  {formatAdminDateTime(detailOrder.acceptedAt)}
                </Descriptions.Item>
                <Descriptions.Item label="创建时间">
                  {formatAdminDateTime(detailOrder.createdAt)}
                </Descriptions.Item>
                <Descriptions.Item label="更新时间">
                  {formatAdminDateTime(detailOrder.updatedAt)}
                </Descriptions.Item>
                <Descriptions.Item label="问题备注" span={2}>
                  <span className="worker-order-detail-value">
                    {String(detailOrder.problemNote || '').trim() || '-'}
                  </span>
                </Descriptions.Item>
              </Descriptions>
            </Card>

            <Card title="资料信息" size="small">
              {renderDetailFieldValues(
                getMaterialDetailItems(detailOrder),
                '当前还没有填写资料',
              )}
              <div style={{ marginTop: 12 }}>
                <Typography.Text type="secondary">买家主页截图</Typography.Text>
                <div style={{ marginTop: 8 }}>
                  <ImagePreviewList files={getMaterialScreenshots(detailOrder)} size={72} />
                </div>
              </div>
            </Card>

            <Card title="资料要求" size="small">
              {renderRequirementFieldValues(detailOrder)}
            </Card>

            <Card title="验收信息" size="small">
              <div className="worker-order-detail-stack">
                <Descriptions column={{ xs: 1, md: 2 }} bordered size="small">
                  <Descriptions.Item label="提交时间">
                    {formatAdminDateTime(getAcceptanceSubmittedAt(detailOrder))}
                  </Descriptions.Item>
                  <Descriptions.Item label="验收图片">
                    {getAcceptanceFiles(detailOrder).length +
                      getAcceptanceImageUrls(detailOrder).length || '-'}
                  </Descriptions.Item>
                  <Descriptions.Item label="备注" span={2}>
                    <span className="worker-order-detail-value">
                      {String(detailOrder.acceptance?.note || '').trim() || '-'}
                    </span>
                  </Descriptions.Item>
                </Descriptions>
                {getAcceptanceFiles(detailOrder).length ||
                getAcceptanceImageUrls(detailOrder).length ? (
                  <ImagePreviewList
                    files={getAcceptanceFiles(detailOrder)}
                    imageUrls={getAcceptanceImageUrls(detailOrder)}
                    size={72}
                  />
                ) : (
                  <Typography.Text type="secondary">
                    暂无验收图
                  </Typography.Text>
                )}
              </div>
            </Card>

            <Card title="原始数据" size="small">
              <Tabs
                className="worker-order-detail-json-tabs"
                items={[
                  {
                    key: 'material',
                    label: '资料',
                    children: <JsonPreview value={detailOrder.material} />,
                  },
                  {
                    key: 'requirement',
                    label: '需求',
                    children: <JsonPreview value={detailOrder.requirement} />,
                  },
                  {
                    key: 'acceptance',
                    label: '验收',
                    children: <JsonPreview value={detailOrder.acceptance} />,
                  },
                ]}
              />
            </Card>
          </div>
        ) : null}
      </Drawer>

      <Modal
        title={`编辑工单 · ${editOrder?.workOrderNo || ''}`}
        open={Boolean(editOrder)}
        onCancel={() => {
          setEditOrder(null)
          editForm.resetFields()
        }}
        onOk={() => editForm.submit()}
        destroyOnHidden
        width={720}
      >
        {editOrder ? (
          <Form form={editForm} layout="vertical" onFinish={submitEdit}>
            <Form.Item
              label="商品"
              name="productName"
              rules={[{ required: true, message: '请填写商品名称' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item label="平台订单号" name="platformOrderId">
              <Input placeholder="留空表示无平台订单号" />
            </Form.Item>
            <Form.Item label="分类" name="categoryId">
              <Select
                allowClear
                placeholder="选择接单分类"
                options={(categoriesQuery.data?.data.items || [])
                  .filter((category) => category.status === 'active')
                  .map((category) => ({
                    label: category.name,
                    value: category.categoryId,
                  }))}
              />
            </Form.Item>
            <Form.Item
              label="接单金额"
              name="rewardAmount"
              rules={[{ required: true, message: '请填写接单金额' }]}
              tooltip="打手看到的接单报酬"
            >
              <InputNumber min={0.01} step={1} addonAfter="元" />
            </Form.Item>
            <Form.Item
              label="冻结押金"
              name="requiredDepositAmount"
              rules={[{ required: true, message: '请填写冻结押金' }]}
              tooltip="抢单时需要冻结的押金，0 表示无需押金"
            >
              <InputNumber min={0} step={1} addonAfter="元" />
            </Form.Item>
            <Form.Item
              label="资料字段"
              name="fieldsText"
              extra="每行一个字段：key:名称，下拉项用 # 分隔（如 system:系统#安卓,苹果）"
            >
              <Input.TextArea rows={5} />
            </Form.Item>
            <Form.Item
              label="任务时限"
              name="timeoutMinutes"
              tooltip="打手抢单后开始计时，超时由系统自动按策略处置；0 表示不限时"
            >
              <InputNumber
                min={0}
                step={5}
                addonAfter="分钟"
                style={{ width: 160 }}
              />
            </Form.Item>
            <Form.Item
              label="超时策略"
              name="timeoutPolicy"
              tooltip="reopen：释放押金退回大厅继续可抢；cancel_release：取消订单并退还押金；cancel_deduct：取消订单并扣除押金"
            >
              <Select
                style={{ width: 320 }}
                options={[
                  { value: 'reopen', label: '释放押金退回大厅' },
                  { value: 'cancel_release', label: '取消订单并退还押金' },
                  { value: 'cancel_deduct', label: '取消订单并扣除押金' },
                ]}
              />
            </Form.Item>
          </Form>
        ) : null}
      </Modal>

      <Modal
        title={`扣减待解冻押金 · ${deductOrder?.workOrderNo || ''}`}
        open={Boolean(deductOrder)}
        onCancel={() => {
          setDeductOrder(null)
          deductForm.resetFields()
        }}
        onOk={() => deductForm.submit()}
        destroyOnHidden
      >
        {deductOrder ? (
          <Form form={deductForm} layout="vertical" onFinish={submitDeduct}>
            <Alert
              showIcon
              type="warning"
              message={`该工单当前待解冻押金 ${formatMoney(
                deductOrder.pendingUnfreezeAmount,
              )}，扣减后剩余部分仍按原计划解冻。`}
              style={{ marginBottom: 16 }}
            />
            <Form.Item
              label="扣减金额"
              name="amount"
              rules={[{ required: true, message: '请输入扣减金额' }]}
            >
              <InputNumber
                min={0.01}
                max={Math.round(Number(deductOrder.pendingUnfreezeAmount || 0)) / 100}
                step={1}
                addonAfter="元"
                className="full-width"
              />
            </Form.Item>
            <Form.Item
              label="扣减原因"
              name="note"
              rules={[{ required: true, message: '请填写扣减原因' }]}
            >
              <Input.TextArea rows={3} placeholder="如：订单出现问题，按规则扣除押金" />
            </Form.Item>
          </Form>
        ) : null}
      </Modal>

      <Modal
        title="标记问题单"
        open={Boolean(problemOrder)}
        onCancel={() => {
          setProblemOrder(null)
          problemForm.resetFields()
        }}
        onOk={() => problemForm.submit()}
        destroyOnHidden
      >
        <Form form={problemForm} layout="vertical" onFinish={submitProblem}>
          <Form.Item
            label="问题备注"
            name="note"
            rules={[{ required: true, message: '请填写问题备注' }]}
          >
            <Input.TextArea rows={4} />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="处置问题单"
        open={Boolean(resolutionOrder)}
        onCancel={() => {
          setResolutionOrder(null)
          resolutionForm.resetFields()
        }}
        onOk={() => resolutionForm.submit()}
        destroyOnHidden
      >
        <Form
          form={resolutionForm}
          layout="vertical"
          initialValues={{ action: 'return_to_worker' }}
          onFinish={submitResolution}
        >
          <Form.Item
            label="处置方式"
            name="action"
            rules={[{ required: true, message: '请选择处置方式' }]}
          >
            <Select
              options={[
                { value: 'return_to_worker', label: '退回打手继续代练' },
                { value: 'reopen', label: '释放押金并重新放回大厅' },
                { value: 'cancel_release', label: '取消订单并退还押金' },
                { value: 'cancel_deduct', label: '取消订单并扣除押金' },
              ]}
            />
          </Form.Item>
          <Form.Item
            label="处置备注"
            name="note"
            rules={[{ required: true, message: '请填写处置备注' }]}
          >
            <Input.TextArea rows={4} />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="人工补充资料"
        open={Boolean(materialOrder)}
        onCancel={() => {
          setMaterialOrder(null)
          materialForm.resetFields()
        }}
        onOk={() => materialForm.submit()}
        destroyOnHidden
      >
        <Form form={materialForm} layout="vertical" onFinish={submitMaterial}>
          {getRequirementFields(materialOrder).map((field) => (
            <Form.Item
              key={field.key}
              label={field.label}
              name={['fields', field.key]}
              rules={
                field.required
                  ? [{ required: true, message: `请选择/填写${field.label}` }]
                  : undefined
              }
            >
              {field.type === 'select' && (field.options || []).length > 0 ? (
                <Select
                  options={(field.options || []).map((option) => ({
                    label: option,
                    value: option,
                  }))}
                />
              ) : (
                <Input />
              )}
            </Form.Item>
          ))}
          <Form.Item label="买家主页截图">
            <ImageUpload
              scene="collect-material"
              scope="admin"
              maxCount={5}
              value={materialScreenshots}
              onChange={setMaterialScreenshots}
            />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title={`拼单配置 · ${sharingOrder?.productName || ''}`}
        open={Boolean(sharingOrder)}
        onCancel={() => {
          setSharingOrder(null)
          sharingForm.resetFields()
        }}
        onOk={() => sharingForm.submit()}
        destroyOnHidden
        width={720}
      >
        {sharingOrder ? (
          <Space direction="vertical" size={16} className="full-width">
            <Form
              form={sharingForm}
              layout="vertical"
              initialValues={{
                enabled: false,
                totalQuantity: 1,
                unitReward: 0,
              }}
              onFinish={submitSharingConfig}
            >
              <Form.Item
                label="启用拼单"
                name="enabled"
                valuePropName="checked"
                tooltip="启用后打手可在抢单大厅按单价×数量参与拼单，未拼满时整单仍可被抢走"
              >
                <Switch />
              </Form.Item>
              <Form.Item noStyle shouldUpdate>
                {({ getFieldValue }) =>
                  getFieldValue('enabled') ? (
                    <Space size={16} wrap>
                      <Form.Item
                        label="总数量"
                        name="totalQuantity"
                        rules={[{ required: true, message: '请填写总数量' }]}
                      >
                        <InputNumber
                          min={1}
                          max={100000}
                          addonAfter="份"
                          onChange={(value) =>
                            syncSharingForm({
                              totalQuantity: Number(value) || 0,
                            })
                          }
                        />
                      </Form.Item>
                      <Form.Item
                        label="单价"
                        name="unitReward"
                        rules={[{ required: true, message: '请填写单价' }]}
                        tooltip="每个数量份对应的报酬，修改后总价自动重算"
                      >
                        <InputNumber
                          min={0.01}
                          step={1}
                          addonAfter="元"
                          onChange={(value) =>
                            syncSharingForm({ unitReward: Number(value) || 0 })
                          }
                        />
                      </Form.Item>
                      <Form.Item
                        label="拼单总价"
                        name="totalAmount"
                        rules={[{ required: true, message: '请填写总价' }]}
                        tooltip="总价 = 单价 × 数量，修改总价会自动反推数量"
                      >
                        <InputNumber
                          min={0.01}
                          step={1}
                          addonAfter="元"
                          onChange={(value) =>
                            syncSharingForm({ totalAmount: Number(value) || 0 })
                          }
                        />
                      </Form.Item>
                    </Space>
                  ) : null
                }
              </Form.Item>
            </Form>

            <Card size="small" title="拼单明细">
              {sharingQuery.isLoading ? (
                <Typography.Text type="secondary">加载中...</Typography.Text>
              ) : (sharingQuery.data?.data.shares || []).length === 0 ? (
                <Typography.Text type="secondary">暂无打手参与拼单</Typography.Text>
              ) : (
                <Table<WorkOrderShare>
                  rowKey="shareId"
                  size="small"
                  dataSource={sharingQuery.data?.data.shares || []}
                  pagination={false}
                  columns={[
                    {
                      title: '打手',
                      render: (_, share) =>
                        share.worker?.displayName || share.worker?.username || '-',
                    },
                    { title: '数量', dataIndex: 'quantity' },
                    {
                      title: '份额报酬',
                      render: (_, share) => formatMoney(share.shareReward),
                    },
                    {
                      title: '状态',
                      render: (_, share) => (
                        <Tag color={resolveSharingShareStatusColor(share.status)}>
                          {formatSharingShareStatus(share.status)}
                        </Tag>
                      ),
                    },
                    {
                      title: '提交时间',
                      render: (_, share) =>
                        share.submittedAt
                          ? formatAdminDateTime(share.submittedAt)
                          : '-',
                    },
                  ]}
                />
              )}
            </Card>
          </Space>
        ) : null}
      </Modal>
    </section>
  )
}

function formatRequirementFieldsText(fields: CollectField[]): string {
  return fields
    .map((field) => {
      const labelPart = `${field.key}:${field.label}`
      const options = (field.options || []).filter(Boolean)
      return options.length > 0
        ? `${labelPart}#${options.join(',')}`
        : labelPart
    })
    .join('\n')
}

function MockWorkOrderForm({ onCreated }: { onCreated: () => Promise<void> }) {
  const { message } = App.useApp()
  const [loading, setLoading] = useState(false)

  async function submit(values: {
    platformOrderId?: string
    productName?: string
    rewardAmount?: number
    materialComplete?: boolean
  }) {
    setLoading(true)
    try {
      await createAdminMockWorkOrder(values)
      message.success('Mock 工单已生成')
      await onCreated()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '生成失败')
    } finally {
      setLoading(false)
    }
  }

  return (
    <Form
      layout="inline"
      initialValues={{
        productName: '指挥官秘钥1个',
        rewardAmount: 25,
        materialComplete: false,
      }}
      onFinish={submit}
    >
      <Form.Item label="订单号" name="platformOrderId">
        <Input placeholder="留空自动生成" style={{ width: 180 }} />
      </Form.Item>
      <Form.Item label="商品" name="productName">
        <Input style={{ width: 220 }} />
      </Form.Item>
      <Form.Item label="接单金额" name="rewardAmount">
        <InputNumber min={0.01} step={1} addonAfter="元" />
      </Form.Item>
      <Form.Item
        label="资料完整"
        name="materialComplete"
        valuePropName="checked"
      >
        <Switch />
      </Form.Item>
      <Form.Item>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          htmlType="submit"
          loading={loading}
        >
          生成
        </Button>
      </Form.Item>
    </Form>
  )
}

