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

import JsonPreview from '@/components/admin/JsonPreview'
import WorkOrderEventTimeline from '@/components/WorkOrderEventTimeline'
import ImageUpload from '@/components/files/ImageUpload'
import ImagePreviewList from '@/components/files/ImagePreviewList'
import {
  acceptAdminWorkOrder,
  acceptAdminWorkOrderShare,
  acceptAdminWorkOrders,
  assignAdminWorkOrderToWorker,
  cancelAdminWorkOrder,
  cancelAdminWorkOrderShare,
  cancelAdminWorkOrderSharing,
  completeAdminWorkOrderGiftCooldown,
  confirmAdminWorkOrderFriend,
  deductAdminWorkOrderPendingDeposit,
  deleteAdminWorkOrder,
  fetchAdminWorkCategories,
  fetchAdminSession,
  fetchAdminWorkOrderSharing,
  fetchAdminWorkerLevels,
  fetchAdminWorkerUsers,
  fetchAdminWorkOrders,
  markAdminWorkOrderProblem,
  pinAdminWorkOrder,
  publishAdminWorkOrder,
  reopenAdminCancelledWorkOrder,
  resetAdminWorkOrderGiftMaterial,
  resolveAdminProblemWorkOrder,
  submitAdminWorkOrderMaterial,
  unpublishAdminWorkOrder,
  updateAdminWorkOrder,
  updateAdminWorkOrderNote,
  updateAdminWorkOrderSharing,
} from '@/services/admin'
import type { UploadedFile, WorkOrder, WorkOrderShare } from '@/types/worker-platform'
import { AdminRangePicker } from '@/components/admin/AdminDatePicker'
import dayjs, { ADMIN_DATE_FORMAT } from '@/lib/dayjs'
import { ADMIN_DEFAULT_PAGE_SIZE, buildAdminTablePagination } from '@/utils/admin-pagination'
import { hasAdminPermission, hasAdminRole } from '@/utils/admin-auth'
import { formatAdminDateTime } from '@/utils/admin-time'
import {
  DeadlineCountdown,
  formatAcceptanceMode,
  formatGiftPhase,
  formatTimeoutPolicyLabel,
  getAcceptanceFiles,
  getAcceptanceImageUrls,
  getAcceptanceSubmittedAt,
  getMaterialFields,
  getMaterialDetailItems,
  getMaterialScreenshots,
  getRequirementFields,
  renderDetailFieldValues,
  renderMaterialSummary,
  asRecord,
  formatMoney,
  formatSharingShareStatus,
  formatStatus,
  resolveGiftPhaseColor,
  resolveSharingShareStatusColor,
  resolveStatusColor,
} from './shared'
import { AmountEditableCell, ProductNameEditableCell } from './WorkOrderTableCells'
import { MockWorkOrderForm, WorkOrderStatisticsBar } from './WorkOrderPanelParts'
import {
  formatRequirementFieldsText,
  formatUserPaymentAmount,
  getDisplayOrderNo,
  getUserPaymentFen,
  parseWorkerMaterialText,
  renderWorkOrderWorkers,
  setSkipPublishConfirm,
  shouldSkipPublishConfirm,
} from './work-order-panel-utils'

const FILTERABLE_WORK_ORDER_STATUSES = [
  'pending_material',
  'unassigned',
  'open',
  'in_progress',
  'pending_acceptance',
  'problem',
  'vip_evidence_pending',
  'accepted',
  'cancelled',
] as const

const VIP_EVIDENCE_PENDING_STATUS = 'vip_evidence_pending'

const GIFT_PHASE_FILTER_OPTIONS = [
  'material_required',
  'material_submitted',
  'friend_countdown',
  'gift_ready',
] as const

type MaterialFormValues = {
  fields?: Record<string, string>
  rewardAmount?: number
}

type CancelOrderFormValues = {
  action?: 'return_to_hall' | 'cancel_order'
  reason?: string
}

type CancelShareFormValues = {
  reason?: string
}

type CancelSharingFormValues = {
  action?: 'return_to_hall' | 'cancel_order'
  reason?: string
}

export default function WorkOrdersPanel() {
  const { message, modal } = App.useApp()
  const navigate = useNavigate()
  const [searchParams, setSearchParams] = useSearchParams()
  const queryClient = useQueryClient()
  const canEditRequirementFields = hasAdminRole('operator')
  const canViewStatistics = hasAdminRole('operator')
  const adminSessionQuery = useQuery({
    queryKey: ['admin-session'],
    queryFn: fetchAdminSession,
    retry: false,
  })
  const sessionPermissions = adminSessionQuery.data?.data.user.permissions
  const canReturnToHall = sessionPermissions
    ? sessionPermissions.includes('worker_order.return_to_hall')
    : hasAdminPermission('worker_order.return_to_hall')
  const canCancelOrder = sessionPermissions
    ? sessionPermissions.includes('worker_order.cancel')
    : hasAdminPermission('worker_order.cancel')
  const canCancelShare = sessionPermissions
    ? sessionPermissions.includes('worker_order.cancel_share')
    : hasAdminPermission('worker_order.cancel_share')
  const canEditOrder = sessionPermissions
    ? sessionPermissions.includes('worker_order.edit')
    : hasAdminPermission('worker_order.edit')
  const canAssignOrder = sessionPermissions
    ? sessionPermissions.includes('worker_order.assign')
    : hasAdminPermission('worker_order.assign')
  const canDeleteOrder = sessionPermissions
    ? sessionPermissions.includes('worker_order.delete')
    : hasAdminPermission('worker_order.delete')
  const canReopenOrder = sessionPermissions
    ? sessionPermissions.includes('worker_order.reopen')
    : hasAdminPermission('worker_order.reopen')
  const canPublishOrder = sessionPermissions
    ? sessionPermissions.includes('worker_order.publish')
    : hasAdminPermission('worker_order.publish')
  const canAcceptOrder = sessionPermissions
    ? sessionPermissions.includes('worker_order.accept')
    : hasAdminPermission('worker_order.accept')
  const canUpdateMaterial = sessionPermissions
    ? sessionPermissions.includes('worker_order.update_material')
    : hasAdminPermission('worker_order.update_material')
  const canManageProblem = sessionPermissions
    ? sessionPermissions.includes('worker_order.manage_problem')
    : hasAdminPermission('worker_order.manage_problem')
  const canDeductDeposit = sessionPermissions
    ? sessionPermissions.includes('worker_order.deduct_deposit')
    : hasAdminPermission('worker_order.deduct_deposit')
  const canConfigureSharing = sessionPermissions
    ? sessionPermissions.includes('worker_order.configure_share')
    : hasAdminPermission('worker_order.configure_share')
  const [statuses, setStatuses] = useState<string[]>([])
  const [targetWorkOrderId, setTargetWorkOrderId] = useState<number | undefined>()
  const [keyword, setKeyword] = useState('')
  const [createdRange, setCreatedRange] = useState<[string, string] | null>(null)
  const [keywordInput, setKeywordInput] = useState('')
  const [workerId, setWorkerId] = useState<number | undefined>()
  const [categoryId, setCategoryId] = useState<number | undefined>()
  const [workerLevelIds, setWorkerLevelIds] = useState<number[]>([])
  const [acceptanceMode, setAcceptanceMode] = useState<string | undefined>()
  const [giftPhase, setGiftPhase] = useState<string | undefined>()
  const [filterWorkerKeyword, setFilterWorkerKeyword] = useState('')
  const [assignWorkerKeyword, setAssignWorkerKeyword] = useState('')
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(ADMIN_DEFAULT_PAGE_SIZE)
  const [selectedAcceptanceOrderIds, setSelectedAcceptanceOrderIds] = useState<number[]>([])
  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 [materialPasteText, setMaterialPasteText] = useState('')
  const [sharingOrder, setSharingOrder] = useState<WorkOrder | null>(null)
  const [cancelShare, setCancelShare] = useState<WorkOrderShare | null>(null)
  const [cancelSharingOrder, setCancelSharingOrder] = useState<WorkOrder | null>(null)
  const [assignOrder, setAssignOrder] = useState<WorkOrder | null>(null)
  const [assignWorkerId, setAssignWorkerId] = useState<number | undefined>(undefined)
  const [editOrder, setEditOrder] = useState<WorkOrder | null>(null)
  const [noteOrder, setNoteOrder] = useState<WorkOrder | null>(null)
  const [deductOrder, setDeductOrder] = useState<WorkOrder | null>(null)
  const [cancelOrder, setCancelOrder] = useState<WorkOrder | null>(null)
  const [problemForm] = Form.useForm()
  const [resolutionForm] = Form.useForm()
  const [materialForm] = Form.useForm<MaterialFormValues>()
  const [cancelForm] = Form.useForm<CancelOrderFormValues>()
  const [cancelShareForm] = Form.useForm<CancelShareFormValues>()
  const [cancelSharingForm] = Form.useForm<CancelSharingFormValues>()
  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 [noteForm] = Form.useForm<{ note?: string }>()
  const [sharingForm] = Form.useForm<{
    enabled?: boolean
    totalQuantity?: number
    unitReward?: number
    totalAmount?: number
  }>()
  // 仅单独筛选「待验收」时提供批量验收入口（多选状态下不启用勾选，避免误操作）
  const isPendingAcceptanceOnly = statuses.length === 1 && statuses[0] === 'pending_acceptance'
  const selectedWorkOrderStatuses = statuses.filter(
    (status) => status !== VIP_EVIDENCE_PENDING_STATUS,
  )
  const vipEvidencePending = statuses.includes(VIP_EVIDENCE_PENDING_STATUS)
  const showWorkerLevelFilter = statuses.includes('pending_acceptance')

  useEffect(() => {
    const workOrderId = Number(searchParams.get('workOrderId') || 0)
    if (!Number.isInteger(workOrderId) || workOrderId <= 0) return
    setTargetWorkOrderId(workOrderId)
    setStatuses([])
    setKeyword('')
    setKeywordInput('')
    setWorkerId(undefined)
    setWorkerLevelIds([])
    setPage(1)
    setSearchParams(
      (current) => {
        current.delete('workOrderId')
        return current
      },
      { replace: true },
    )
  }, [searchParams, setSearchParams])

  const ordersQuery = useQuery({
    queryKey: [
      'admin-worker-platform-orders',
      statuses.join(','),
      keyword,
      workerId,
      categoryId,
      workerLevelIds.join(','),
      targetWorkOrderId,
      acceptanceMode || '',
      giftPhase || '',
      page,
      pageSize,
      createdRange ? createdRange[0] : '',
      createdRange ? createdRange[1] : '',
    ],
    queryFn: () =>
      fetchAdminWorkOrders({
        status:
          selectedWorkOrderStatuses.length > 0 ? selectedWorkOrderStatuses.join(',') : undefined,
        vipEvidencePending: vipEvidencePending || undefined,
        acceptanceMode: acceptanceMode || undefined,
        giftPhase: giftPhase || undefined,
        workOrderId: targetWorkOrderId,
        categoryId,
        keyword,
        workerId,
        workerLevelIds:
          showWorkerLevelFilter && workerLevelIds.length > 0 ? workerLevelIds.join(',') : undefined,
        page,
        pageSize,
        ...(createdRange ? { createdFrom: createdRange[0], createdTo: createdRange[1] } : {}),
      }),
  })
  const ordersPagination = ordersQuery.data?.data.pagination
  const categoriesQuery = useQuery({
    queryKey: ['admin-worker-platform-categories'],
    queryFn: () => fetchAdminWorkCategories(),
  })
  const workerLevelsQuery = useQuery({
    queryKey: ['admin-worker-platform-levels'],
    queryFn: () => fetchAdminWorkerLevels(),
    enabled: showWorkerLevelFilter,
  })
  const filterWorkersQuery = useQuery({
    queryKey: ['admin-worker-platform-workers', 'order-filter', filterWorkerKeyword],
    queryFn: () =>
      fetchAdminWorkerUsers({
        keyword: filterWorkerKeyword.trim(),
        page: 1,
        pageSize: 30,
      }),
  })
  const sharingQuery = useQuery({
    queryKey: ['admin-worker-platform-order-sharing', sharingOrder?.workOrderId],
    queryFn: () => fetchAdminWorkOrderSharing(Number(sharingOrder?.workOrderId)),
    enabled: Boolean(sharingOrder),
  })
  const sharingShares = sharingQuery.data?.data.shares || []
  const hasCancellableSharingShares = sharingShares.some((share) =>
    ['joined', 'submitted'].includes(share.status),
  )
  const hasAcceptedSharingShares = sharingShares.some((share) => share.status === 'accepted')
  const assignWorkersQuery = useQuery({
    queryKey: ['admin-worker-platform-workers', 'assign', assignWorkerKeyword],
    queryFn: () =>
      fetchAdminWorkerUsers({
        status: 'active',
        keyword: assignWorkerKeyword.trim(),
        page: 1,
        pageSize: 30,
      }),
    enabled: Boolean(assignOrder),
  })
  useEffect(() => {
    setSelectedAcceptanceOrderIds([])
  }, [
    statuses,
    keyword,
    workerId,
    categoryId,
    workerLevelIds,
    targetWorkOrderId,
    acceptanceMode,
    giftPhase,
    page,
    pageSize,
  ])

  useEffect(() => {
    if (!showWorkerLevelFilter) setWorkerLevelIds([])
  }, [showWorkerLevelFilter])

  useEffect(() => {
    if (acceptanceMode !== 'friend_gift') setGiftPhase(undefined)
  }, [acceptanceMode])

  function openAssignModal(row: WorkOrder) {
    setAssignOrder(row)
    setAssignWorkerId(undefined)
    setAssignWorkerKeyword('')
  }

  function openCancelModal(row: WorkOrder) {
    setCancelOrder(row)
    cancelForm.setFieldsValue({ action: 'return_to_hall', reason: '' })
  }

  function applyMaterialPaste(text: string) {
    if (!materialOrder) return
    const recognized = parseWorkerMaterialText(text)
    const keys = Object.keys(recognized) as Array<keyof typeof recognized>
    if (keys.length === 0) {
      message.warning('未识别到可填充的字段，请检查粘贴内容格式')
      return
    }
    const requirementFields = getRequirementFields(materialOrder)
    const availableKeys = new Set(requirementFields.map((field) => field.key))
    const next: Record<string, string> = {}
    const filled: string[] = []
    for (const key of keys) {
      if (!availableKeys.has(key)) continue
      next[key] = recognized[key]
      const label = requirementFields.find((field) => field.key === key)?.label || key
      filled.push(`${label}=${recognized[key]}`)
    }
    if (filled.length === 0) {
      message.warning('识别到的字段与当前资料要求不匹配')
      return
    }
    materialForm.setFieldsValue({ fields: next })
    message.success(`已自动填写：${filled.join('，')}`)
  }

  async function submitAssign() {
    if (!assignOrder || !assignWorkerId) return
    const succeeded = await runAction(
      () =>
        assignAdminWorkOrderToWorker(assignOrder.workOrderId, {
          workerId: assignWorkerId,
        }),
      (response) =>
        response.data.voucherConsume.voucherCount > 0
          ? '电子凭证已自动核销，订单已指派给打手'
          : '已指派打手',
    )
    if (!succeeded) return
    setAssignOrder(null)
    setAssignWorkerId(undefined)
  }

  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 submitCancelShare(values: CancelShareFormValues) {
    if (!sharingOrder || !cancelShare) return
    const workOrderId = sharingOrder.workOrderId
    const succeeded = await runAction(
      () =>
        cancelAdminWorkOrderShare(workOrderId, cancelShare.shareId, {
          reason: String(values.reason || '').trim(),
        }),
      '该参与者已撤单，押金和拼单份数已恢复',
    )
    if (!succeeded) return
    await queryClient.invalidateQueries({
      queryKey: ['admin-worker-platform-order-sharing', workOrderId],
    })
    setCancelShare(null)
    cancelShareForm.resetFields()
  }

  async function submitCancelSharing(values: CancelSharingFormValues) {
    if (!cancelSharingOrder || !values.action) return
    const action = values.action
    const succeeded = await runAction(
      () =>
        cancelAdminWorkOrderSharing(cancelSharingOrder.workOrderId, {
          action,
          reason: String(values.reason || '').trim(),
        }),
      (result) =>
        action === 'return_to_hall'
          ? `已撤回 ${result.data.cancelledShareCount} 个未验收份额并退回大厅`
          : `拼单订单已取消，已撤销 ${result.data.cancelledShareCount} 个参与份额`,
    )
    if (!succeeded) return
    await queryClient.invalidateQueries({
      queryKey: ['admin-worker-platform-order-sharing', cancelSharingOrder.workOrderId],
    })
    setCancelSharingOrder(null)
    cancelSharingForm.resetFields()
  }

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

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

  function publishWorkOrder(row: WorkOrder) {
    return runAction(
      () => publishAdminWorkOrder(row.workOrderId),
      (response) =>
        !response.data.voucherConsume.ok
          ? '订单已发布，但电子凭证核销未完成'
          : response.data.hallVisible
            ? response.data.voucherConsume.voucherCount > 0
              ? '订单已发布，电子凭证已顺带核销'
              : '订单已展示在大厅'
            : '订单已进入大厅等待队列',
    )
  }

  function confirmPublishWorkOrder(row: WorkOrder) {
    if (shouldSkipPublishConfirm()) {
      void publishWorkOrder(row)
      return
    }

    let skipFutureConfirm = false
    modal.confirm({
      title: '确认发布该订单？',
      content: (
        <div>
          <Typography.Paragraph>
            如订单关联电子凭证，系统会在发布后顺带尝试核销；核销失败不影响订单发布。
          </Typography.Paragraph>
          <Checkbox
            onChange={(event) => {
              skipFutureConfirm = event.target.checked
            }}
          >
            不再提示
          </Checkbox>
        </div>
      ),
      okText: '发布订单',
      cancelText: '取消',
      onOk: () => {
        if (skipFutureConfirm) setSkipPublishConfirm()
        return publishWorkOrder(row)
      },
    })
  }

  function confirmBatchAcceptance() {
    const workOrderIds = selectedAcceptanceOrderIds
    if (workOrderIds.length === 0) {
      message.warning('请先选择待验收订单')
      return
    }
    modal.confirm({
      title: `确认验收 ${workOrderIds.length} 个订单？`,
      content: '验收通过后将结算打手奖励，并按配置处理押金。',
      okText: '一键验收',
      cancelText: '取消',
      onOk: async () => {
        const succeeded = await runAction(
          () => acceptAdminWorkOrders(workOrderIds),
          `已验收 ${workOrderIds.length} 个订单`,
        )
        if (succeeded) setSelectedAcceptanceOrderIds([])
      },
    })
  }

  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 submitCancelOrder(values: CancelOrderFormValues) {
    if (!cancelOrder || !values.action) return
    const action = values.action
    const succeeded = await runAction(
      () =>
        cancelAdminWorkOrder(cancelOrder.workOrderId, {
          action,
          reason: String(values.reason || '').trim(),
        }),
      action === 'return_to_hall' ? '订单已退回大厅，打手额度已恢复' : '订单已取消，打手额度已恢复',
    )
    if (!succeeded) return
    setCancelOrder(null)
    cancelForm.resetFields()
  }

  async function submitMaterial(values: MaterialFormValues) {
    if (!materialOrder) return
    const requestedRewardAmount =
      materialOrder.status === 'in_progress' && !materialOrder.sharing?.enabled
        ? Number(values.rewardAmount || 0)
        : undefined
    const succeeded = await runAction(
      async () => {
        const response = await submitAdminWorkOrderMaterial(
          materialOrder.workOrderId,
          values.fields || {},
          materialScreenshots,
          requestedRewardAmount,
        )
        if (
          requestedRewardAmount !== undefined &&
          Number(response.data.order.rewardAmount || 0) !== Math.round(requestedRewardAmount * 100)
        ) {
          throw new Error('接单价格保存未生效，请刷新后重试')
        }
        return response
      },
      materialOrder.status === 'in_progress' ? '订单资料已更新' : '订单资料已保存',
    )
    if (!succeeded) return
    setMaterialOrder(null)
    materialForm.resetFields()
    setMaterialScreenshots([])
  }

  function searchOrders() {
    setKeyword(keywordInput.trim())
    setPage(1)
  }

  function clearOrderFilters() {
    setTargetWorkOrderId(undefined)
    setKeywordInput('')
    setKeyword('')
    setStatuses([])
    setWorkerId(undefined)
    setCategoryId(undefined)
    setWorkerLevelIds([])
    setAcceptanceMode(undefined)
    setGiftPhase(undefined)
    setCreatedRange(null)
    setPage(1)
  }

  function openMaterialModal(row: WorkOrder) {
    setMaterialOrder(row)
    materialForm.setFieldsValue({
      fields: getMaterialFields(row),
      rewardAmount: Math.round(Number(row.rewardAmount || 0)) / 100,
    })
    setMaterialScreenshots(getMaterialScreenshots(row))
  }

  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 openNoteModal(row: WorkOrder) {
    setNoteOrder(row)
    noteForm.setFieldsValue({ note: row.adminNote || '' })
  }

  async function submitNote(values: { note?: string }) {
    if (!noteOrder) return
    const succeeded = await runAction(
      () => updateAdminWorkOrderNote(noteOrder.workOrderId, String(values.note || '')),
      '工单备注已保存',
    )
    if (!succeeded) return
    if (detailOrder?.workOrderId === noteOrder.workOrderId) {
      setDetailOrder({ ...detailOrder, adminNote: String(values.note || '').trim() })
    }
    setNoteOrder(null)
    noteForm.resetFields()
  }

  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 doSave = () =>
      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),
            ...(canEditRequirementFields ? { fieldsText: String(values.fieldsText || '') } : {}),
            timeoutMinutes: Math.max(0, Number(values.timeoutMinutes || 0)),
            timeoutPolicy: values.timeoutPolicy || 'reopen',
          }),
        '工单信息已保存',
      )
    const paymentFen = getUserPaymentFen(editOrder)
    const rewardFen = Math.round(Number(values.rewardAmount || 0) * 100)
    if (paymentFen !== null && rewardFen > paymentFen) {
      modal.confirm({
        title: '发单金额高于用户付款金额',
        content: (
          <span>
            该订单用户付款 {formatMoney(paymentFen)}，发单金额{' '}
            <Typography.Text strong type="danger">
              {formatMoney(rewardFen)}
            </Typography.Text>
            ，本单平台将亏损。确认保存？
          </span>
        ),
        okText: '确认保存',
        cancelText: '取消',
        onOk: async () => {
          const succeeded = await doSave()
          if (!succeeded) return
          setEditOrder(null)
          editForm.resetFields()
        },
      })
      return
    }
    const succeeded = await doSave()
    if (!succeeded) return
    setEditOrder(null)
    editForm.resetFields()
  }

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

  function confirmFriendAdded(row: WorkOrder) {
    const cooldownHours = Number(row.gift?.cooldownHours || 72)
    const cooldownMinutes = Number(row.gift?.cooldownMinutes || 0)
    const cooldownLabel = cooldownMinutes > 0 ? `${cooldownMinutes} 分钟` : `${cooldownHours} 小时`
    modal.confirm({
      title: '确认已添加打手为游戏好友？',
      content: (
        <div>
          <Typography.Paragraph>
            请先核对打手提交的昵称 / ID / 区服与主页截图，确认已在游戏内互为好友后再点击确认。
          </Typography.Paragraph>
          <Typography.Paragraph>
            确认后开始 {cooldownLabel}
            赠送冷却，冷却结束前打手不能提交赠送凭证；任务时限将顺延到冷却结束后重新起算。
          </Typography.Paragraph>
        </div>
      ),
      okText: '已加好友，开始冷却',
      cancelText: '取消',
      onOk: () =>
        runAction(
          () => confirmAdminWorkOrderFriend(row.workOrderId),
          `已确认加好友，${cooldownLabel} 冷却开始`,
        ),
    })
  }

  function completeGiftCooldown(row: WorkOrder) {
    modal.confirm({
      title: '手动结束赠送冷却？',
      content:
        '确认后将立即允许打手提交赠送凭证与验收资料；订单任务时限将从当前时刻重新计算。此操作会记录在订单流转记录中。',
      okText: '确认结束冷却',
      okButtonProps: { type: 'primary' },
      cancelText: '取消',
      onOk: () =>
        runAction(
          () => completeAdminWorkOrderGiftCooldown(row.workOrderId),
          '已手动结束赠送冷却，打手现在可以提交验收',
        ),
    })
  }

  function requestResetGiftMaterial(row: WorkOrder) {
    modal.confirm({
      title: '重置打手好友赠送资料？',
      content:
        '打手已提交的资料、加好友时间与冷却进度将全部清零，订单回到“待打手提交资料”阶段，需打手重新提交后再次确认加好友。',
      okText: '确认重置',
      okButtonProps: { danger: true },
      cancelText: '取消',
      onOk: () =>
        runAction(
          () => resetAdminWorkOrderGiftMaterial(row.workOrderId),
          '已重置，等待打手重新提交资料',
        ),
    })
  }

  const columns: TableColumnsType<WorkOrder> = [
    {
      title: '订单',
      minWidth: 300,
      render: (_, row) => {
        const source = asRecord(row.material?.source)
        const shopName = String(source.shopName || '').trim()
        const provider = String(source.provider || '').trim()
        return (
          <div className="cell-stack">
            <ProductNameEditableCell
              order={row}
              onOpenDetail={() => openDetailDrawer(row)}
              onSaved={refreshAll}
            />
            <Space size={[6, 6]} wrap>
              {row.categoryName ? <Tag>{row.categoryName}</Tag> : null}
              <Typography.Text type="secondary">
                创建时间 {formatAdminDateTime(row.createdAt)}
              </Typography.Text>
            </Space>
            {shopName || provider ? (
              <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                {provider ? `来源：${provider}` : ''}
                {provider && shopName ? ' · ' : ''}
                {shopName ? `店铺：${shopName}` : ''}
              </Typography.Text>
            ) : null}
            <Typography.Text type="secondary">{getDisplayOrderNo(row)}</Typography.Text>
          </div>
        )
      },
    },
    {
      title: '用户付款金额',
      width: 130,
      render: (_, row) => formatUserPaymentAmount(row),
    },
    {
      title: '发单金额',
      width: 130,
      render: (_, row) => (
        <AmountEditableCell order={row} field="rewardAmount" onSaved={refreshAll} />
      ),
    },
    {
      title: '押金',
      width: 130,
      render: (_, row) => (
        <AmountEditableCell order={row} field="requiredDepositAmount" onSaved={refreshAll} />
      ),
    },
    {
      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: 150,
      render: (_, row) => {
        const cancelText =
          row.cancel?.reason || (row.cancel ? `${row.cancel.source}（未记录原因）` : '')
        return (
          <div className="cell-stack">
            <Space wrap size={4}>
              <Tag color={resolveStatusColor(row.status)}>{formatStatus(row.status)}</Tag>
              {row.rawStatus === 'open' && row.pinnedAt ? (
                <Tag color="gold" icon={<PushpinOutlined />}>
                  置顶
                </Tag>
              ) : null}
              {row.acceptanceMode === 'friend_gift' ? <Tag color="purple">好友赠送</Tag> : null}
              {row.acceptanceMode === 'friend_gift' &&
              row.gift &&
              !['pending_material', 'unassigned', 'open'].includes(row.rawStatus || row.status) ? (
                <Tag color={resolveGiftPhaseColor(row.gift.phase)}>
                  {formatGiftPhase(row.gift.phase)}
                </Tag>
              ) : null}
            </Space>
            {row.cancel ? (
              <Typography.Text
                type="secondary"
                style={{ fontSize: 12, maxWidth: 140 }}
                ellipsis={{ tooltip: `${row.cancel.source}：${cancelText}` }}
              >
                {cancelText}
              </Typography.Text>
            ) : null}
            {String(row.adminNote || '').trim() ? (
              <Typography.Text
                type="secondary"
                style={{ fontSize: 12, maxWidth: 140 }}
                ellipsis={{ tooltip: row.adminNote }}
              >
                备注：{row.adminNote}
              </Typography.Text>
            ) : null}
          </div>
        )
      },
    },
    {
      title: '打手',
      width: 140,
      render: (_, row) => renderWorkOrderWorkers(row),
    },
    {
      title: '资料',
      width: 240,
      render: (_, row) => renderMaterialSummary(row),
    },
    {
      title: '验收图',
      width: 170,
      render: (_, row) => {
        const isVipAutoAcceptance = row.acceptance?.reviewMode === 'vip_auto'
        const evidencePending = row.acceptance?.evidenceStatus === 'pending'
        if (row.sharing?.enabled) {
          return (
            <Button type="link" size="small" onClick={() => openSharingConfigModal(row)}>
              查看拼单验收图
              {row.sharingProgress?.pendingSubmissionCount
                ? `（${row.sharingProgress.pendingSubmissionCount}人待提交）`
                : ''}
            </Button>
          )
        }
        return (
          <Space direction="vertical" size={4}>
            <ImagePreviewList
              files={getAcceptanceFiles(row)}
              imageUrls={getAcceptanceImageUrls(row)}
              size={44}
              maxVisible={2}
            />
            {isVipAutoAcceptance ? (
              <Tag color="purple">
                {evidencePending ? 'VIP 免审核，待补图' : 'VIP 免审核，已补图'}
              </Tag>
            ) : null}
          </Space>
        )
      },
    },
    {
      title: '操作',
      width: 400,
      render: (_, row) => (
        <Space wrap>
          <Button onClick={() => openDetailDrawer(row)}>详情</Button>
          {canEditOrder ? (
            <Button icon={<FormOutlined />} onClick={() => openNoteModal(row)}>
              备注
            </Button>
          ) : null}
          {row.capabilities?.canEdit && canEditOrder ? (
            <Button icon={<EditOutlined />} onClick={() => openEditModal(row)}>
              编辑
            </Button>
          ) : null}
          {row.capabilities?.canDelete && canDeleteOrder ? (
            <Button danger icon={<DeleteOutlined />} onClick={() => requestDeleteWorkOrder(row)}>
              删除
            </Button>
          ) : null}
          {row.capabilities?.canReopen && canReopenOrder ? (
            <Button
              icon={<UndoOutlined />}
              onClick={() => {
                modal.confirm({
                  title: '确认重新启用该订单？',
                  content: '订单将恢复为未分配状态。请确认资料与金额后，再发布到抢单大厅。',
                  okText: '重新启用',
                  cancelText: '取消',
                  onOk: () =>
                    runAction(
                      () => reopenAdminCancelledWorkOrder(row.workOrderId),
                      '订单已恢复为未分配状态，可编辑后发布',
                    ),
                })
              }}
            >
              重新启用
            </Button>
          ) : null}
          {row.sharing?.enabled ||
          (row.capabilities?.canConfigureSharing && canConfigureSharing) ? (
            <Button icon={<TeamOutlined />} onClick={() => openSharingConfigModal(row)}>
              {row.sharing?.enabled && !row.capabilities?.canConfigureSharing
                ? '拼单管理'
                : '拼单配置'}
            </Button>
          ) : null}
          {row.capabilities?.canAssign && canAssignOrder ? (
            <Button icon={<UserAddOutlined />} onClick={() => openAssignModal(row)}>
              指派并核销
            </Button>
          ) : null}
          {row.capabilities?.canCancel && (canReturnToHall || canCancelOrder) ? (
            <Button danger icon={<UndoOutlined />} onClick={() => openCancelModal(row)}>
              撤单
            </Button>
          ) : null}
          {row.capabilities?.canUpdateMaterial && canUpdateMaterial ? (
            <Button icon={<FormOutlined />} onClick={() => openMaterialModal(row)}>
              {['open', 'in_progress'].includes(row.status) ? '更新资料' : '补资料'}
            </Button>
          ) : null}
          {row.capabilities?.canPublish && canPublishOrder ? (
            <Button
              icon={<SendOutlined />}
              disabled={Number(row.rewardAmount || 0) <= 0}
              title={
                Number(row.rewardAmount || 0) <= 0 ? '接单金额为 0，不能发布到大厅' : undefined
              }
              onClick={() => confirmPublishWorkOrder(row)}
            >
              发布并核销
            </Button>
          ) : null}
          {row.capabilities?.canPin && canPublishOrder ? (
            <Button
              icon={<PushpinOutlined />}
              title={row.pinnedAt ? '取消置顶' : '置顶后抢单大厅优先展示'}
              onClick={() =>
                runAction(
                  () => pinAdminWorkOrder(row.workOrderId, !row.pinnedAt),
                  row.pinnedAt ? '已取消置顶' : '已置顶，抢单大厅优先展示',
                )
              }
            >
              {row.pinnedAt ? '取消置顶' : '置顶'}
            </Button>
          ) : null}
          {row.capabilities?.canUnpublish && canPublishOrder ? (
            <Button
              danger
              onClick={() => {
                modal.confirm({
                  title: '确认下架该订单？',
                  content: '下架后订单会回到未分配状态，不再在抢单大厅展示。',
                  okText: '确认下架',
                  cancelText: '取消',
                  onOk: () =>
                    runAction(() => unpublishAdminWorkOrder(row.workOrderId), '订单已撤回到未分配'),
                })
              }}
            >
              下架
            </Button>
          ) : null}
          {row.capabilities?.canAccept && canAcceptOrder ? (
            <Button
              icon={<CheckOutlined />}
              type="primary"
              onClick={() => runAction(() => acceptAdminWorkOrder(row.workOrderId), '已验收通过')}
            >
              验收
            </Button>
          ) : null}
          {row.capabilities?.canDeduct &&
          canDeductDeposit &&
          Number(row.pendingUnfreezeAmount || 0) > 0 ? (
            <Button icon={<WarningOutlined />} danger onClick={() => openDeductModal(row)}>
              扣押金
            </Button>
          ) : null}
          {row.status === 'accepted' ? (
            <Button
              icon={<WarningOutlined />}
              danger
              onClick={() =>
                navigate('/admin/worker-platform?tab=after-sales', {
                  state: { createOrder: row },
                })
              }
            >
              售后
            </Button>
          ) : null}
          {row.capabilities?.canConfirmFriend && canManageProblem ? (
            <Button
              type="primary"
              icon={<UserAddOutlined />}
              onClick={() => confirmFriendAdded(row)}
            >
              确认加好友
            </Button>
          ) : null}
          {row.capabilities?.canCompleteGiftCooldown && canManageProblem ? (
            <Button type="primary" onClick={() => completeGiftCooldown(row)}>
              结束冷却
            </Button>
          ) : null}
          {row.capabilities?.canResetGiftFlow && canManageProblem ? (
            <Button danger onClick={() => requestResetGiftMaterial(row)}>
              重置打手资料
            </Button>
          ) : null}
          {row.capabilities?.canMarkProblem && canManageProblem ? (
            <Button icon={<WarningOutlined />} danger onClick={() => setProblemOrder(row)}>
              问题单
            </Button>
          ) : null}
          {row.capabilities?.canResolveProblem && canManageProblem ? (
            <Button icon={<FormOutlined />} onClick={() => setResolutionOrder(row)}>
              处置
            </Button>
          ) : null}
        </Space>
      ),
    },
  ]

  return (
    <section className="platform-panel-stack">
      {targetWorkOrderId ? (
        <Alert
          type="info"
          showIcon
          message={`已定位工单 #${targetWorkOrderId}`}
          action={
            <Button size="small" onClick={() => setTargetWorkOrderId(undefined)}>
              取消定位
            </Button>
          }
        />
      ) : null}
      <Card title="订单搜索与筛选" bordered={false}>
        <div className="worker-orders-toolbar">
          <Space wrap className="filter-form worker-orders-search-controls">
            <Input
              allowClear
              value={keywordInput}
              placeholder="订单号 / 商品名 / 游戏ID / 游戏昵称"
              style={{ width: 280 }}
              onChange={(event) => setKeywordInput(event.target.value)}
              onPressEnter={searchOrders}
            />
            <Select
              mode="multiple"
              allowClear
              value={statuses}
              placeholder="全部状态（可多选）"
              style={{ minWidth: 220, maxWidth: 420 }}
              maxTagCount="responsive"
              listHeight={320}
              options={FILTERABLE_WORK_ORDER_STATUSES.map((item) => ({
                value: item,
                label: <Tag color={resolveStatusColor(item)}>{formatStatus(item)}</Tag>,
              }))}
              onChange={(nextStatuses: string[]) => {
                setStatuses(nextStatuses)
                setPage(1)
              }}
            />
            <Select
              allowClear
              showSearch
              filterOption={false}
              value={workerId}
              placeholder="全部接单人员"
              style={{ width: 180 }}
              loading={filterWorkersQuery.isLoading}
              onSearch={setFilterWorkerKeyword}
              options={(filterWorkersQuery.data?.data.items || []).map((worker) => ({
                value: worker.workerId,
                label:
                  worker.displayName && worker.displayName !== worker.username
                    ? `${worker.displayName}（${worker.username}）`
                    : worker.username,
              }))}
              onChange={(nextWorkerId) => {
                setWorkerId(nextWorkerId)
                if (!nextWorkerId) setFilterWorkerKeyword('')
                setPage(1)
              }}
            />
            <Select
              allowClear
              showSearch
              optionFilterProp="label"
              value={categoryId}
              placeholder="全部接单分类"
              style={{ width: 180 }}
              loading={categoriesQuery.isLoading}
              options={(categoriesQuery.data?.data.items || []).map((category) => ({
                value: category.categoryId,
                label: category.name,
              }))}
              onChange={(nextCategoryId) => {
                setCategoryId(nextCategoryId)
                setPage(1)
              }}
            />
            {showWorkerLevelFilter ? (
              <Select
                mode="multiple"
                allowClear
                value={workerLevelIds}
                placeholder="全部打手 VIP 等级"
                style={{ minWidth: 180, maxWidth: 320 }}
                maxTagCount="responsive"
                loading={workerLevelsQuery.isLoading}
                options={(workerLevelsQuery.data?.data.items || []).map((level) => ({
                  value: level.levelId,
                  label: level.name,
                }))}
                onChange={(nextWorkerLevelIds: number[]) => {
                  setWorkerLevelIds(nextWorkerLevelIds)
                  setPage(1)
                }}
              />
            ) : null}
            <Select
              allowClear
              value={acceptanceMode}
              placeholder="全部验收模式"
              style={{ width: 150 }}
              options={[
                { value: 'standard', label: '标准验收' },
                { value: 'friend_gift', label: '好友赠送' },
              ]}
              onChange={(nextMode) => {
                setAcceptanceMode(nextMode)
                setPage(1)
              }}
            />
            {acceptanceMode === 'friend_gift' ? (
              <Select
                allowClear
                value={giftPhase}
                placeholder="全部赠送阶段"
                style={{ width: 170 }}
                options={GIFT_PHASE_FILTER_OPTIONS.map((phase) => ({
                  value: phase,
                  label: <Tag color={resolveGiftPhaseColor(phase)}>{formatGiftPhase(phase)}</Tag>,
                }))}
                onChange={(nextPhase) => {
                  setGiftPhase(nextPhase)
                  setPage(1)
                }}
              />
            ) : null}
            <AdminRangePicker
              value={createdRange ? [dayjs(createdRange[0]), dayjs(createdRange[1])] : null}
              onChange={(dates) => {
                const [start, end] = dates || []
                setCreatedRange(
                  start && end
                    ? [start.format(ADMIN_DATE_FORMAT), end.format(ADMIN_DATE_FORMAT)]
                    : null,
                )
                setPage(1)
              }}
            />
            <Button type="primary" icon={<SearchOutlined />} onClick={searchOrders}>
              查询
            </Button>
            <Button onClick={clearOrderFilters}>清空筛选</Button>
          </Space>
          <div className="worker-orders-mock">
            <Typography.Text type="secondary">本地 Mock</Typography.Text>
            <MockWorkOrderForm onCreated={refreshAll} />
          </div>
        </div>
      </Card>
      {canViewStatistics ? (
        <WorkOrderStatisticsBar statistics={ordersQuery.data?.data.statistics} />
      ) : null}
      {ordersQuery.isError ? (
        <Alert
          type="error"
          showIcon
          message="接单工单加载失败"
          description="请刷新后重试；若问题持续存在，请联系管理员查看服务日志。"
        />
      ) : null}
      <Card
        title="接单工单"
        extra={
          <Space>
            {isPendingAcceptanceOnly ? (
              <Button
                type="primary"
                icon={<CheckOutlined />}
                disabled={selectedAcceptanceOrderIds.length === 0}
                onClick={confirmBatchAcceptance}
              >
                批量验收（{selectedAcceptanceOrderIds.length}）
              </Button>
            ) : null}
            <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}
          rowSelection={
            isPendingAcceptanceOnly
              ? {
                  selectedRowKeys: selectedAcceptanceOrderIds,
                  onChange: (selectedRowKeys) =>
                    setSelectedAcceptanceOrderIds(selectedRowKeys.map((item) => Number(item))),
                }
              : undefined
          }
          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
        className="worker-order-detail-drawer"
        title={
          detailOrder
            ? `${detailOrder.productName || '工单详情'} · ${getDisplayOrderNo(detailOrder)}`
            : '工单详情'
        }
        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)
                    void 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="平台订单号">
                  {getDisplayOrderNo(detailOrder)}
                </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="打手">
                  {renderWorkOrderWorkers(detailOrder)}
                </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.Item label="客服备注" span={2}>
                  <Space align="start">
                    <span className="worker-order-detail-value">
                      {String(detailOrder.adminNote || '').trim() || '-'}
                    </span>
                    {canEditOrder ? (
                      <Button
                        size="small"
                        icon={<EditOutlined />}
                        onClick={() => openNoteModal(detailOrder)}
                      >
                        编辑
                      </Button>
                    ) : null}
                  </Space>
                </Descriptions.Item>
                {detailOrder.cancel ? (
                  <Descriptions.Item label="取消信息" span={2}>
                    <span className="worker-order-detail-value">
                      {detailOrder.cancel.source}
                      {detailOrder.cancel.cancelledAt
                        ? ` · ${formatAdminDateTime(detailOrder.cancel.cancelledAt)}`
                        : ''}
                      {detailOrder.cancel.actorType === 'admin' && detailOrder.cancel.actorName
                        ? ` · 操作人 ${detailOrder.cancel.actorName}`
                        : ''}
                      {detailOrder.cancel.reason
                        ? ` · 原因：${detailOrder.cancel.reason}`
                        : ' · 原因未记录'}
                    </span>
                  </Descriptions.Item>
                ) : null}
              </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>

            {detailOrder.acceptanceMode === 'friend_gift' && detailOrder.gift ? (
              <Card
                title="好友赠送进度"
                size="small"
                extra={
                  <Space>
                    <Tag color="purple">{formatAcceptanceMode(detailOrder.acceptanceMode)}</Tag>
                    <Tag color={resolveGiftPhaseColor(detailOrder.gift.phase)}>
                      {formatGiftPhase(detailOrder.gift.phase)}
                    </Tag>
                    {detailOrder.capabilities?.canConfirmFriend && canManageProblem ? (
                      <Button
                        type="primary"
                        size="small"
                        onClick={() => confirmFriendAdded(detailOrder)}
                      >
                        确认加好友
                      </Button>
                    ) : null}
                    {detailOrder.capabilities?.canCompleteGiftCooldown && canManageProblem ? (
                      <Button
                        type="primary"
                        size="small"
                        onClick={() => completeGiftCooldown(detailOrder)}
                      >
                        结束冷却
                      </Button>
                    ) : null}
                    {detailOrder.capabilities?.canResetGiftFlow && canManageProblem ? (
                      <Button
                        size="small"
                        danger
                        onClick={() => requestResetGiftMaterial(detailOrder)}
                      >
                        重置打手资料
                      </Button>
                    ) : null}
                  </Space>
                }
              >
                <div className="worker-order-detail-stack">
                  <Descriptions column={{ xs: 1, md: 2 }} bordered size="small">
                    <Descriptions.Item label="冷却时长">
                      {detailOrder.gift.cooldownMinutes > 0
                        ? `${detailOrder.gift.cooldownMinutes} 分钟`
                        : `${detailOrder.gift.cooldownHours} 小时`}
                    </Descriptions.Item>
                    <Descriptions.Item label="打手资料提交">
                      {formatAdminDateTime(detailOrder.gift.boosterMaterial?.submittedAt)}
                    </Descriptions.Item>
                    <Descriptions.Item label="已加好友">
                      {formatAdminDateTime(detailOrder.gift.friendAddedAt)}
                    </Descriptions.Item>
                    <Descriptions.Item label="可赠送时间">
                      {detailOrder.gift.giftAvailableAt
                        ? formatAdminDateTime(detailOrder.gift.giftAvailableAt)
                        : '-'}
                    </Descriptions.Item>
                  </Descriptions>
                  <Descriptions column={{ xs: 1, md: 2 }} bordered size="small">
                    {(
                      [
                        ['gameNickname', '游戏昵称'],
                        ['gameId', '游戏ID'],
                        ['serverZone', '区服'],
                        ['system', '系统'],
                      ] as const
                    ).map(([key, label]) => (
                      <Descriptions.Item key={key} label={label}>
                        <span className="worker-order-detail-value">
                          {String(detailOrder.gift?.boosterMaterial?.fields?.[key] || '').trim() ||
                            '-'}
                        </span>
                      </Descriptions.Item>
                    ))}
                    <Descriptions.Item label="打手备注" span={2}>
                      <span className="worker-order-detail-value">
                        {String(detailOrder.gift?.boosterMaterial?.note || '').trim() || '-'}
                      </span>
                    </Descriptions.Item>
                  </Descriptions>
                  <div>
                    <Typography.Text type="secondary">打手主页截图</Typography.Text>
                    <div style={{ marginTop: 8 }}>
                      {detailOrder.gift.boosterMaterial?.screenshots?.length ? (
                        <ImagePreviewList
                          files={detailOrder.gift.boosterMaterial.screenshots}
                          size={72}
                        />
                      ) : (
                        <Typography.Text type="secondary">未提交</Typography.Text>
                      )}
                    </div>
                  </div>
                </div>
              </Card>
            ) : null}

            <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>
                  {detailOrder.acceptance?.reviewMode === 'vip_auto' ? (
                    <Descriptions.Item label="VIP 补图">
                      {detailOrder.acceptance.evidenceStatus === 'pending'
                        ? `待补图，截止 ${formatAdminDateTime(detailOrder.acceptance.evidenceDueAt)}`
                        : `已补图 ${formatAdminDateTime(detailOrder.acceptance.evidenceSupplementedAt)}`}
                    </Descriptions.Item>
                  ) : null}
                  <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">
              <WorkOrderEventTimeline orderId={detailOrder.workOrderId} viewer="admin" />
            </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={`客服备注 · ${getDisplayOrderNo(noteOrder)}`}
        open={Boolean(noteOrder)}
        onCancel={() => {
          setNoteOrder(null)
          noteForm.resetFields()
        }}
        onOk={() => noteForm.submit()}
        destroyOnHidden
      >
        {noteOrder ? (
          <Form form={noteForm} layout="vertical" onFinish={submitNote}>
            <Form.Item
              label="备注内容"
              name="note"
              rules={[{ max: 2000, message: '备注不能超过 2000 个字符' }]}
              extra="仅后台客服可见，不会展示给打手。"
            >
              <Input.TextArea
                rows={5}
                maxLength={2000}
                showCount
                placeholder="请输入本单客服备注"
              />
            </Form.Item>
          </Form>
        ) : null}
      </Modal>
      <Modal
        title={`编辑工单 · ${getDisplayOrderNo(editOrder)}`}
        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} disabled={!canEditRequirementFields} />
            </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={`扣减待解冻押金 · ${getDisplayOrderNo(deductOrder)}`}
        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={`撤单处理 · ${getDisplayOrderNo(cancelOrder)}`}
        open={Boolean(cancelOrder)}
        onCancel={() => {
          setCancelOrder(null)
          cancelForm.resetFields()
        }}
        onOk={() => cancelForm.submit()}
        destroyOnHidden
      >
        {cancelOrder ? (
          <Form
            form={cancelForm}
            layout="vertical"
            initialValues={{ action: canReturnToHall ? 'return_to_hall' : 'cancel_order' }}
            onFinish={submitCancelOrder}
          >
            <Alert
              showIcon
              type="warning"
              message="处理后都会恢复打手接单额度和冻结押金，请确认处理方式。"
              style={{ marginBottom: 16 }}
            />
            <Form.Item
              label="处理方式"
              name="action"
              rules={[{ required: true, message: '请选择撤单处理方式' }]}
            >
              <Radio.Group>
                <Space direction="vertical">
                  {canReturnToHall ? (
                    <Radio value="return_to_hall">退回大厅：订单重新开放给其他打手接单</Radio>
                  ) : null}
                  {canCancelOrder ? (
                    <Radio value="cancel_order">取消订单：用户退款后终止订单，不再回大厅</Radio>
                  ) : null}
                </Space>
              </Radio.Group>
            </Form.Item>
            <Form.Item
              label="处理原因"
              name="reason"
              dependencies={['action']}
              rules={[
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (getFieldValue('action') !== 'cancel_order' || String(value || '').trim()) {
                      return Promise.resolve()
                    }
                    return Promise.reject(new Error('取消订单时请填写退款或撤单原因'))
                  },
                }),
              ]}
            >
              <Input.TextArea rows={3} placeholder="取消订单时请填写退款原因；退回大厅可选填" />
            </Form.Item>
          </Form>
        ) : null}
      </Modal>

      <Modal
        title={
          ['open', 'in_progress'].includes(materialOrder?.status || '')
            ? '更新订单资料'
            : '人工补充资料'
        }
        open={Boolean(materialOrder)}
        onCancel={() => {
          setMaterialOrder(null)
          setMaterialPasteText('')
          materialForm.resetFields()
          setMaterialScreenshots([])
        }}
        onOk={() => materialForm.submit()}
        destroyOnHidden
      >
        <Form form={materialForm} layout="vertical" onFinish={submitMaterial}>
          {materialOrder?.status === 'in_progress' && !materialOrder.sharing?.enabled ? (
            <Form.Item
              label="发单价格"
              name="rewardAmount"
              rules={[{ required: true, message: '请输入发单价格' }]}
            >
              <InputNumber min={0} precision={2} addonAfter="元" style={{ width: '100%' }} />
            </Form.Item>
          ) : null}
          <Form.Item label="粘贴自动识别">
            <Space.Compact style={{ width: '100%' }}>
              <Input.TextArea
                rows={3}
                value={materialPasteText}
                onChange={(event) => setMaterialPasteText(event.target.value)}
                onPaste={(event) => {
                  const text = event.clipboardData?.getData('text/plain') || ''
                  if (!text.trim()) return
                  event.preventDefault()
                  applyMaterialPaste(text)
                  setMaterialPasteText('')
                }}
                placeholder={
                  '粘贴客服消息后自动识别填充，格式如：\n安卓还是苹果(必填)：安卓\nQ区还是V区(必填)：Q区\n角色名称(必填)：张三\n游戏编号(必填)：123456'
                }
              />
              <Button
                onClick={() => {
                  const text = materialPasteText.trim()
                  if (!text) return
                  applyMaterialPaste(text)
                  setMaterialPasteText('')
                }}
              >
                识别填充
              </Button>
            </Space.Compact>
          </Form.Item>
          {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 ? (
                <Radio.Group
                  options={(field.options || []).map((option) => ({
                    label: option,
                    value: option,
                  }))}
                />
              ) : (
                <Input />
              )}
            </Form.Item>
          ))}
          <Form.Item label="买家主页截图">
            <ImageUpload
              scene="collect-material"
              scope="admin"
              maxCount={5}
              showPasteHint
              captureGlobalPaste
              value={materialScreenshots}
              onChange={setMaterialScreenshots}
            />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title={`指派打手 · ${assignOrder?.productName || ''}`}
        open={Boolean(assignOrder)}
        onCancel={() => {
          setAssignOrder(null)
          setAssignWorkerId(undefined)
        }}
        onOk={() => submitAssign()}
        okText="指派并核销"
        okButtonProps={{ disabled: !assignWorkerId }}
        destroyOnHidden
        width={520}
      >
        <Space direction="vertical" size={12} className="full-width">
          <Typography.Paragraph type="secondary">
            指派后订单直接进入该打手的「我的订单」，不再出现在抢单大厅；有关联电子凭证时会先自动核销，再按订单规则冻结打手押金。核销后取消指派不会恢复电子凭证。
          </Typography.Paragraph>
          <Select
            style={{ width: '100%' }}
            placeholder="选择要指派的打手"
            loading={assignWorkersQuery.isLoading}
            showSearch
            filterOption={false}
            value={assignWorkerId}
            onSearch={setAssignWorkerKeyword}
            onChange={(nextWorkerId) => {
              setAssignWorkerId(nextWorkerId)
              if (!nextWorkerId) setAssignWorkerKeyword('')
            }}
            options={(assignWorkersQuery.data?.data.items || []).map((worker) => ({
              value: worker.workerId,
              label: `${worker.displayName || worker.username}（${worker.username}）${
                worker.workerType === 'internal' ? '· 内部' : ''
              }`,
            }))}
          />
        </Space>
      </Modal>

      <Modal
        title={`${sharingOrder?.capabilities?.canConfigureSharing && canConfigureSharing ? '拼单配置' : '拼单明细'} · ${sharingOrder?.productName || ''}`}
        open={Boolean(sharingOrder)}
        onCancel={() => {
          setSharingOrder(null)
          setCancelShare(null)
          setCancelSharingOrder(null)
          sharingForm.resetFields()
          cancelShareForm.resetFields()
          cancelSharingForm.resetFields()
        }}
        onOk={() => sharingForm.submit()}
        footer={
          sharingOrder?.capabilities?.canConfigureSharing && canConfigureSharing ? undefined : null
        }
        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}
              disabled={!sharingOrder.capabilities?.canConfigureSharing || !canConfigureSharing}
            >
              <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>
              ) : (
                <>
                  {sharingOrder.capabilities?.canCancelSharing &&
                  hasCancellableSharingShares &&
                  (canReturnToHall || canCancelOrder) ? (
                    <Space
                      direction="vertical"
                      size={8}
                      className="full-width"
                      style={{ marginBottom: 12 }}
                    >
                      <Alert
                        showIcon
                        type="warning"
                        message="拼单撤单会批量处理所有未验收份额"
                        description={
                          hasAcceptedSharingShares
                            ? '已验收份额会保留；如需退款，请从售后处理。'
                            : '可选择把未验收份额退回大厅，或取消整个拼单订单。'
                        }
                      />
                      <div>
                        <Button
                          danger
                          onClick={() => {
                            setCancelSharingOrder(sharingOrder)
                            cancelSharingForm.setFieldsValue({
                              action: canReturnToHall ? 'return_to_hall' : 'cancel_order',
                              reason: '',
                            })
                          }}
                        >
                          拼单撤单处理
                        </Button>
                      </div>
                    </Space>
                  ) : null}
                  <Table<WorkOrderShare>
                    rowKey="shareId"
                    size="small"
                    dataSource={sharingShares}
                    loading={sharingQuery.isFetching}
                    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) : '-',
                      },
                      {
                        title: '验收图',
                        width: 150,
                        render: (_, share) => (
                          <ImagePreviewList
                            files={
                              Array.isArray(share.acceptance?.files) ? share.acceptance.files : []
                            }
                            imageUrls={
                              Array.isArray(share.acceptance?.imageUrls)
                                ? share.acceptance.imageUrls
                                : []
                            }
                            size={44}
                            maxVisible={2}
                          />
                        ),
                      },
                      {
                        title: '备注',
                        render: (_, share) => String(share.acceptance?.note || '').trim() || '-',
                      },
                      {
                        title: '操作',
                        width: 190,
                        render: (_, share) => {
                          if (share.status === 'accepted') return <Tag color="green">已验收</Tag>
                          if (share.status === 'cancelled') return <Tag>已撤单</Tag>
                          return (
                            <Space size={6}>
                              {share.status === 'submitted' ? (
                                <Button
                                  type="primary"
                                  size="small"
                                  onClick={() => {
                                    void runAction(
                                      () =>
                                        acceptAdminWorkOrderShare(
                                          sharingOrder.workOrderId,
                                          share.shareId,
                                        ),
                                      '该拼单参与者已验收',
                                    ).then((succeeded) => {
                                      if (succeeded) {
                                        void queryClient.invalidateQueries({
                                          queryKey: [
                                            'admin-worker-platform-order-sharing',
                                            sharingOrder.workOrderId,
                                          ],
                                        })
                                      }
                                    })
                                  }}
                                >
                                  单独验收
                                </Button>
                              ) : (
                                <Typography.Text type="secondary">待提交</Typography.Text>
                              )}
                              {canCancelShare ? (
                                <Button
                                  danger
                                  size="small"
                                  icon={<UndoOutlined />}
                                  title="只撤销当前参与者的拼单份额，其他参与者不受影响"
                                  onClick={() => {
                                    setCancelShare(share)
                                    cancelShareForm.setFieldsValue({ reason: '' })
                                  }}
                                >
                                  单人撤单
                                </Button>
                              ) : null}
                            </Space>
                          )
                        },
                      },
                    ]}
                  />
                </>
              )}
            </Card>
          </Space>
        ) : null}
      </Modal>

      <Modal
        title={`撤销拼单参与者 · ${
          cancelShare?.worker?.displayName || cancelShare?.worker?.username || ''
        }`}
        open={Boolean(cancelShare)}
        okText="确认撤单"
        cancelText="取消"
        okButtonProps={{ danger: true }}
        onCancel={() => {
          setCancelShare(null)
          cancelShareForm.resetFields()
        }}
        onOk={() => cancelShareForm.submit()}
        destroyOnHidden
      >
        {cancelShare ? (
          <Form form={cancelShareForm} layout="vertical" onFinish={submitCancelShare}>
            <Alert
              showIcon
              type="warning"
              message={`将撤销该打手承接的 ${cancelShare.quantity} 份拼单`}
              description="撤单后会退还该份额冻结的押金，空出的份数重新回到接单大厅；已提交的验收资料会保留在后台记录中。"
              style={{ marginBottom: 16 }}
            />
            <Form.Item label="撤单原因" name="reason">
              <Input.TextArea rows={3} placeholder="选填，用于后台流转记录" />
            </Form.Item>
          </Form>
        ) : null}
      </Modal>

      <Modal
        title={`拼单撤单处理 · ${getDisplayOrderNo(cancelSharingOrder)}`}
        open={Boolean(cancelSharingOrder)}
        onCancel={() => {
          setCancelSharingOrder(null)
          cancelSharingForm.resetFields()
        }}
        onOk={() => cancelSharingForm.submit()}
        destroyOnHidden
      >
        {cancelSharingOrder ? (
          <Form form={cancelSharingForm} layout="vertical" onFinish={submitCancelSharing}>
            <Alert
              showIcon
              type="warning"
              message="将批量处理所有未验收的拼单份额"
              description="退回大厅会释放未验收份额的押金并重新开放对应数量；取消整单仅在不存在已验收份额时可用。"
              style={{ marginBottom: 16 }}
            />
            <Form.Item
              label="处理方式"
              name="action"
              rules={[{ required: true, message: '请选择拼单撤单处理方式' }]}
            >
              <Radio.Group>
                <Space direction="vertical">
                  {canReturnToHall ? (
                    <Radio value="return_to_hall">
                      退回大厅：撤回所有未验收份额，空出数量重新开放给其他打手
                    </Radio>
                  ) : null}
                  {canCancelOrder ? (
                    <Radio value="cancel_order">
                      取消整单：终止订单；存在已验收份额时不可用，需转售后处理
                    </Radio>
                  ) : null}
                </Space>
              </Radio.Group>
            </Form.Item>
            <Form.Item
              label="处理原因"
              name="reason"
              dependencies={['action']}
              rules={[
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (getFieldValue('action') !== 'cancel_order' || String(value || '').trim()) {
                      return Promise.resolve()
                    }
                    return Promise.reject(new Error('取消整单时请填写退款或撤单原因'))
                  },
                }),
              ]}
            >
              <Input.TextArea rows={3} placeholder="取消整单时请填写退款原因；退回大厅可选填" />
            </Form.Item>
          </Form>
        ) : null}
      </Modal>
    </section>
  )
}
