import { ReloadOutlined, SearchOutlined } from '@ant-design/icons'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import {
  App,
  Button,
  Card,
  Form,
  Input,
  InputNumber,
  Modal,
  Select,
  Space,
  Table,
  Tag,
  Typography,
} from 'antd'
import type { TableColumnsType } from 'antd'
import { useEffect, useRef, useState } from 'react'
import { useSearchParams } from 'react-router'

import {
  creditAdminWorkerWallet,
  fetchAdminWorkerLevels,
  fetchAdminWorkerUsers,
  fetchAdminWorkerWithdrawalAccounts,
  resetAdminWorkerPassword,
  reviewAdminWorkerUser,
  saveAdminWorkerPersonalDepositFreeAmount,
  saveAdminWorkerWithdrawalAccount,
} from '@/services/admin'
import ImageUpload from '@/components/files/ImageUpload'
import type {
  AdminWorkerWithdrawalAccount,
  UploadedFile,
  WorkerUser,
} from '@/types/worker-platform'
import { ADMIN_DEFAULT_PAGE_SIZE, buildAdminTablePagination } from '@/utils/admin-pagination'
import WorkerDetailDrawer from './WorkerDetailDrawer'
import { formatMoney, formatWorkerStatus } from './shared'

type WithdrawalAccountFormValues = {
  accountChannel?: string
  accountName?: string
  accountNo?: string
  alipayQrCodeImages?: UploadedFile[]
  wechatQrCodeImages?: UploadedFile[]
}

type FreezeWorkerFormValues = {
  freezeReason: string
}

type PersonalDepositFreeAmountFormValues = {
  depositFreeAmount?: number
}

export default function WorkersPanel() {
  const { message, modal } = App.useApp()
  const queryClient = useQueryClient()
  const [searchParams, setSearchParams] = useSearchParams()
  const [status, setStatus] = useState('')
  const [keywordInput, setKeywordInput] = useState('')
  const [keyword, setKeyword] = useState('')
  const [workerType, setWorkerType] = useState('')
  const [levelId, setLevelId] = useState(0)
  const [targetWorkerId, setTargetWorkerId] = useState(0)
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(ADMIN_DEFAULT_PAGE_SIZE)
  const [creditWorker, setCreditWorker] = useState<WorkerUser | null>(null)
  const [levelWorker, setLevelWorker] = useState<WorkerUser | null>(null)
  const [withdrawalAccountWorker, setWithdrawalAccountWorker] = useState<WorkerUser | null>(null)
  const [resetPasswordWorker, setResetPasswordWorker] = useState<WorkerUser | null>(null)
  const [freezeWorker, setFreezeWorker] = useState<WorkerUser | null>(null)
  const [personalDepositFreeWorker, setPersonalDepositFreeWorker] = useState<WorkerUser | null>(
    null,
  )
  const [detailWorker, setDetailWorker] = useState<WorkerUser | null>(null)
  const autoOpenedDetailRef = useRef(0)
  const [withdrawalAccounts, setWithdrawalAccounts] = useState<AdminWorkerWithdrawalAccount[]>([])
  const [loadingWithdrawalAccounts, setLoadingWithdrawalAccounts] = useState(false)
  const [savingWithdrawalAccount, setSavingWithdrawalAccount] = useState(false)
  const [creditForm] = Form.useForm()
  const [levelForm] = Form.useForm<{ levelId?: number }>()
  const [withdrawalAccountForm] = Form.useForm<WithdrawalAccountFormValues>()
  const [resetPasswordForm] = Form.useForm<{ password: string }>()
  const [freezeForm] = Form.useForm<FreezeWorkerFormValues>()
  const [personalDepositFreeForm] = Form.useForm<PersonalDepositFreeAmountFormValues>()
  const withdrawalAccountChannel = Form.useWatch('accountChannel', withdrawalAccountForm)
  const editingAlipayAccount = withdrawalAccounts.find(
    (account) => account.accountChannel === 'alipay',
  )

  useEffect(() => {
    const workerId = Number(searchParams.get('workerId') || 0)
    if (!Number.isInteger(workerId) || workerId <= 0) {
      setTargetWorkerId(0)
      return
    }
    setTargetWorkerId(workerId)
    setKeywordInput('')
    setKeyword('')
    setStatus('')
    setWorkerType('')
    setLevelId(0)
    setPage(1)
  }, [searchParams])

  const workersQuery = useQuery({
    queryKey: [
      'admin-worker-platform-workers',
      status,
      keyword,
      workerType,
      levelId,
      targetWorkerId,
      page,
      pageSize,
    ],
    queryFn: () =>
      fetchAdminWorkerUsers({
        status,
        keyword,
        workerType,
        levelId: levelId || undefined,
        workerId: targetWorkerId || undefined,
        page,
        pageSize,
      }),
  })
  const levelsQuery = useQuery({
    queryKey: ['admin-worker-platform-levels'],
    queryFn: () => fetchAdminWorkerLevels(),
  })
  const workersPagination = workersQuery.data?.data.pagination

  useEffect(() => {
    // 从工单流转记录等入口带 ?workerId= 定位到打手后，自动打开一次详情，关闭后不再重复弹。
    if (targetWorkerId <= 0 || autoOpenedDetailRef.current === targetWorkerId) return
    const match = workersQuery.data?.data.items.find(
      (item) => Number(item.workerId) === targetWorkerId,
    )
    if (!match) return
    autoOpenedDetailRef.current = targetWorkerId
    setDetailWorker(match)
  }, [targetWorkerId, workersQuery.data])

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

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

  function clearWorkerFilters() {
    setKeywordInput('')
    setKeyword('')
    setStatus('')
    setWorkerType('')
    setLevelId(0)
    setTargetWorkerId(0)
    setPage(1)
    setSearchParams(
      (current) => {
        current.delete('workerId')
        return current
      },
      { replace: true },
    )
  }

  async function review(worker: WorkerUser, nextStatus: string) {
    try {
      await reviewAdminWorkerUser(worker.workerId, { status: nextStatus })
      message.success('打手状态已更新')
      await refreshWorkers()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '操作失败')
    }
  }

  async function submitFreezeWorker(values: FreezeWorkerFormValues) {
    if (!freezeWorker) return
    try {
      await reviewAdminWorkerUser(freezeWorker.workerId, {
        status: 'rejected',
        freezeReason: values.freezeReason.trim(),
      })
      message.success('打手账号已冻结，原登录设备已退出')
      setFreezeWorker(null)
      freezeForm.resetFields()
      await refreshWorkers()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '冻结账号失败')
    }
  }

  function toggleWorkerType(worker: WorkerUser, workerType: 'internal' | 'external') {
    const isInternal = workerType === 'internal'
    modal.confirm({
      title: isInternal ? '设为内部打手？' : '设为外部打手？',
      content: isInternal
        ? '内部打手提交验收后将免审核，直接进入待打款；请确认该打手可信。'
        : '外部打手提交验收后需后台审核通过，才进入待打款。',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          await reviewAdminWorkerUser(worker.workerId, {
            status: worker.status,
            workerType,
          })
          message.success('打手类型已更新')
          await refreshWorkers()
        } catch (error) {
          message.error(error instanceof Error ? error.message : '操作失败')
        }
      },
    })
  }

  async function submitCredit(values: { amount?: number; note?: string }) {
    if (!creditWorker) return
    try {
      await creditAdminWorkerWallet(creditWorker.workerId, {
        amount: Number(values.amount || 0),
        note: values.note,
      })
      message.success('余额已增加')
      setCreditWorker(null)
      creditForm.resetFields()
      await refreshWorkers()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '充值失败')
    }
  }

  async function submitResetPassword(values: { password: string }) {
    if (!resetPasswordWorker) return
    try {
      await resetAdminWorkerPassword(resetPasswordWorker.workerId, {
        password: values.password.trim(),
      })
      message.success('打手密码已重置，旧登录设备已退出')
      setResetPasswordWorker(null)
      resetPasswordForm.resetFields()
      await refreshWorkers()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '重置打手密码失败')
    }
  }

  async function submitLevel(values: { levelId?: number }) {
    if (!levelWorker) return
    try {
      await reviewAdminWorkerUser(levelWorker.workerId, {
        status: levelWorker.status,
        levelId: Number(values.levelId || 0),
        reviewNote: levelWorker.reviewNote,
      })
      message.success('打手等级已更新')
      setLevelWorker(null)
      levelForm.resetFields()
      await refreshWorkers()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '调整等级失败')
    }
  }

  async function submitPersonalDepositFreeAmount(values: PersonalDepositFreeAmountFormValues) {
    if (!personalDepositFreeWorker) return
    try {
      await saveAdminWorkerPersonalDepositFreeAmount(personalDepositFreeWorker.workerId, {
        depositFreeAmount: values.depositFreeAmount ?? null,
      })
      message.success('个人免押额度已更新')
      setPersonalDepositFreeWorker(null)
      personalDepositFreeForm.resetFields()
      await refreshWorkers()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '更新个人免押额度失败')
    }
  }

  async function openWithdrawalAccountModal(worker: WorkerUser) {
    setWithdrawalAccountWorker(worker)
    setWithdrawalAccounts([])
    setLoadingWithdrawalAccounts(true)
    try {
      const response = await fetchAdminWorkerWithdrawalAccounts(worker.workerId)
      const accounts = response.data.items
      setWithdrawalAccounts(accounts)
      setWithdrawalAccountFormValues('alipay', accounts)
    } catch (error) {
      message.error(error instanceof Error ? error.message : '读取提现信息失败')
      setWithdrawalAccountWorker(null)
    } finally {
      setLoadingWithdrawalAccounts(false)
    }
  }

  function setWithdrawalAccountFormValues(accountChannel: string, accounts = withdrawalAccounts) {
    const account = accounts.find((item) => item.accountChannel === accountChannel)
    withdrawalAccountForm.setFieldsValue({
      accountChannel,
      accountName: account?.accountName || '',
      accountNo: account?.accountNo || '',
      alipayQrCodeImages: account?.alipayQrCodeImage ? [account.alipayQrCodeImage] : [],
      wechatQrCodeImages: account?.wechatQrCodeImage ? [account.wechatQrCodeImage] : [],
    })
  }

  async function submitWithdrawalAccount(values: WithdrawalAccountFormValues) {
    if (!withdrawalAccountWorker) return
    const accountChannel = String(values.accountChannel || '')
    setSavingWithdrawalAccount(true)
    try {
      const response = await saveAdminWorkerWithdrawalAccount(
        withdrawalAccountWorker.workerId,
        accountChannel,
        {
          accountName: String(values.accountName || '').trim(),
          accountNo: String(values.accountNo || '').trim(),
          alipayQrCodeImages: values.alipayQrCodeImages || [],
          wechatQrCodeImages: values.wechatQrCodeImages || [],
        },
      )
      const account = response.data.account
      const nextAccounts = [
        ...withdrawalAccounts.filter((item) => item.accountChannel !== account.accountChannel),
        account,
      ]
      setWithdrawalAccounts(nextAccounts)
      setWithdrawalAccountFormValues(account.accountChannel, nextAccounts)
      message.success('提现信息已保存')
    } catch (error) {
      message.error(error instanceof Error ? error.message : '保存提现信息失败')
    } finally {
      setSavingWithdrawalAccount(false)
    }
  }

  const columns: TableColumnsType<WorkerUser> = [
    {
      title: '打手',
      minWidth: 220,
      render: (_, row) => (
        <div className="cell-stack">
          <Space size={6} wrap>
            <Typography.Text strong>{row.displayName || row.username}</Typography.Text>
            <Tag color={row.workerType === 'internal' ? 'blue' : 'default'}>
              {row.workerType === 'internal' ? '内部' : '外部'}
            </Tag>
          </Space>
          <Typography.Text type="secondary">{row.username}</Typography.Text>
        </div>
      ),
    },
    { title: '等级', width: 140, render: (_, row) => row.level?.name || '-' },
    {
      title: '免押额度',
      width: 280,
      render: (_, row) =>
        row.personalDepositFreeAmount !== null ? (
          <Typography.Text>
            {formatMoney(row.effectiveDepositFreeAmount)}（等级{' '}
            {formatMoney(row.levelDepositFreeAmount)} + 个人{' '}
            {formatMoney(row.personalDepositFreeAmount)}）
          </Typography.Text>
        ) : (
          <Typography.Text type="secondary">
            {formatMoney(row.effectiveDepositFreeAmount)}（等级）
          </Typography.Text>
        ),
    },
    {
      title: '邀请人',
      width: 160,
      render: (_, row) =>
        row.inviter ? (
          <div className="cell-stack">
            <Typography.Text>{row.inviter.displayName || row.inviter.username}</Typography.Text>
            <Typography.Text type="secondary">{row.inviter.username}</Typography.Text>
          </div>
        ) : (
          '-'
        ),
    },
    {
      title: '余额',
      width: 120,
      render: (_, row) => formatMoney(row.wallet.availableAmount),
    },
    {
      title: '冻结',
      width: 120,
      render: (_, row) => formatMoney(row.wallet.frozenDepositAmount),
    },
    {
      title: '超时订单',
      width: 110,
      render: (_, row) => {
        const count = Number(row.timeoutOrderCount || 0)
        return count > 0 ? (
          <Tag color="red">{count} 单</Tag>
        ) : (
          <Typography.Text type="secondary">0</Typography.Text>
        )
      },
    },
    {
      title: '状态',
      width: 130,
      render: (_, row) => (
        <Tag color={row.status === 'active' ? 'green' : 'orange'}>
          {formatWorkerStatus(row.status)}
        </Tag>
      ),
    },
    {
      title: '冻结原因',
      width: 220,
      render: (_, row) =>
        row.status === 'rejected' && row.freezeReason ? (
          <Typography.Text ellipsis={{ tooltip: row.freezeReason }}>
            {row.freezeReason}
          </Typography.Text>
        ) : (
          '-'
        ),
    },
    {
      title: '操作',
      width: 340,
      render: (_, row) => (
        <Space wrap>
          <Button type="primary" ghost onClick={() => setDetailWorker(row)}>
            详情
          </Button>
          {row.status !== 'active' ? (
            <Button onClick={() => review(row, 'active')}>启用</Button>
          ) : null}
          {row.status !== 'rejected' ? (
            <Button danger onClick={() => setFreezeWorker(row)}>
              冻结
            </Button>
          ) : null}
          {row.workerType !== 'internal' ? (
            <Button onClick={() => toggleWorkerType(row, 'internal')}>设为内部</Button>
          ) : (
            <Button onClick={() => toggleWorkerType(row, 'external')}>设为外部</Button>
          )}
          <Button
            onClick={() => {
              setLevelWorker(row)
              levelForm.setFieldsValue({
                levelId: row.level?.levelId,
              })
            }}
          >
            调等级
          </Button>
          <Button
            onClick={() => {
              setPersonalDepositFreeWorker(row)
              personalDepositFreeForm.setFieldsValue({
                // 接口金额使用“分”，输入框按“元”编辑。
                depositFreeAmount:
                  row.personalDepositFreeAmount === null
                    ? undefined
                    : Number(row.personalDepositFreeAmount) / 100,
              })
            }}
          >
            免押额度
          </Button>
          <Button onClick={() => setCreditWorker(row)}>充值</Button>
          <Button onClick={() => setResetPasswordWorker(row)}>重置密码</Button>
          <Button onClick={() => void openWithdrawalAccountModal(row)}>提现信息</Button>
        </Space>
      ),
    },
  ]

  return (
    <Card
      title="打手"
      extra={
        <Space wrap className="filter-form">
          <Input
            allowClear
            value={keywordInput}
            placeholder="账号 / 昵称 / 手机号"
            style={{ width: 220 }}
            onChange={(event) => setKeywordInput(event.target.value)}
            onPressEnter={searchWorkers}
          />
          <Select
            allowClear
            value={status}
            style={{ width: 150 }}
            options={[
              { value: '', label: '全部状态' },
              { value: 'pending_review', label: '待处理' },
              { value: 'active', label: '已启用' },
              { value: 'rejected', label: '已冻结' },
              { value: 'disabled', label: '已停用' },
            ]}
            onChange={(nextStatus) => {
              setStatus(nextStatus || '')
              setPage(1)
            }}
          />
          <Select
            allowClear
            value={workerType || undefined}
            style={{ width: 140 }}
            placeholder="全部类型"
            options={[
              { value: 'external', label: '外部打手' },
              { value: 'internal', label: '内部打手' },
            ]}
            onChange={(nextType) => {
              setWorkerType(nextType || '')
              setPage(1)
            }}
          />
          <Select
            allowClear
            value={levelId || undefined}
            style={{ width: 140 }}
            placeholder="全部等级"
            loading={levelsQuery.isLoading}
            options={(levelsQuery.data?.data.items || []).map((item) => ({
              value: item.levelId,
              label: item.name,
            }))}
            onChange={(nextLevelId) => {
              setLevelId(nextLevelId || 0)
              setPage(1)
            }}
          />
          <Button type="primary" icon={<SearchOutlined />} onClick={searchWorkers}>
            查询
          </Button>
          <Button onClick={clearWorkerFilters}>清空筛选</Button>
          <Button
            icon={<ReloadOutlined />}
            loading={workersQuery.isFetching}
            onClick={() => workersQuery.refetch()}
          >
            刷新
          </Button>
        </Space>
      }
      bordered={false}
    >
      {targetWorkerId ? (
        <Typography.Text type="secondary">已定位打手 #{targetWorkerId}</Typography.Text>
      ) : null}
      <Table<WorkerUser>
        rowKey="workerId"
        loading={workersQuery.isLoading}
        dataSource={workersQuery.data?.data.items || []}
        columns={columns}
        pagination={buildAdminTablePagination({
          current: workersPagination?.page || page,
          pageSize: workersPagination?.pageSize || pageSize,
          total: workersPagination?.total || 0,
          onChange: (nextPage, nextPageSize) => {
            setPage(nextPage)
            setPageSize(nextPageSize)
          },
        })}
        scroll={{ x: 1000 }}
      />

      <Modal
        title="冻结打手账号"
        open={Boolean(freezeWorker)}
        onCancel={() => {
          setFreezeWorker(null)
          freezeForm.resetFields()
        }}
        onOk={() => freezeForm.submit()}
        destroyOnHidden
      >
        <Form form={freezeForm} layout="vertical" onFinish={submitFreezeWorker}>
          <Form.Item label="打手">
            <Typography.Text>
              {freezeWorker?.displayName || freezeWorker?.username || '-'}
            </Typography.Text>
          </Form.Item>
          <Form.Item
            label="冻结原因"
            name="freezeReason"
            rules={[
              { required: true, whitespace: true, message: '请填写冻结原因或备注' },
              { max: 500, message: '冻结原因不能超过 500 个字符' },
            ]}
          >
            <Input.TextArea
              autoSize={{ minRows: 3, maxRows: 6 }}
              maxLength={500}
              placeholder="例如：多次超时未完成订单，经核实后冻结账号"
              showCount
            />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="设置个人免押额度"
        open={Boolean(personalDepositFreeWorker)}
        onCancel={() => {
          setPersonalDepositFreeWorker(null)
          personalDepositFreeForm.resetFields()
        }}
        onOk={() => personalDepositFreeForm.submit()}
        destroyOnHidden
      >
        <Form
          form={personalDepositFreeForm}
          layout="vertical"
          onFinish={submitPersonalDepositFreeAmount}
        >
          <Form.Item label="打手">
            <Typography.Text>
              {personalDepositFreeWorker?.displayName || personalDepositFreeWorker?.username || '-'}
            </Typography.Text>
          </Form.Item>
          <Form.Item
            label="个人免押额度"
            name="depositFreeAmount"
            tooltip="该额度会与等级免押额度相加；留空或填 0 表示不追加个人额度。"
          >
            <InputNumber min={0} step={10} addonAfter="元" className="full-width" />
          </Form.Item>
          <Typography.Text type="secondary">
            个人额度会叠加等级额度，合计额度以内的订单或拼单份额无需冻结押金；超过部分才会冻结。
          </Typography.Text>
        </Form>
      </Modal>

      <Modal
        title="重置打手密码"
        open={Boolean(resetPasswordWorker)}
        onCancel={() => {
          setResetPasswordWorker(null)
          resetPasswordForm.resetFields()
        }}
        onOk={() => resetPasswordForm.submit()}
        destroyOnHidden
      >
        <Form form={resetPasswordForm} layout="vertical" onFinish={submitResetPassword}>
          <Form.Item label="打手">
            <Typography.Text>
              {resetPasswordWorker?.displayName || resetPasswordWorker?.username || '-'}
            </Typography.Text>
          </Form.Item>
          <Form.Item
            label="新密码"
            name="password"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 8, message: '密码至少 8 位' },
              {
                validator: (_, value) =>
                  !value || (/[a-zA-Z]/.test(value) && /\d/.test(value))
                    ? Promise.resolve()
                    : Promise.reject(new Error('密码需包含英文字母和数字')),
              },
            ]}
          >
            <Input.Password placeholder="至少 8 位，包含英文和数字" />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="编辑打手提现信息"
        open={Boolean(withdrawalAccountWorker)}
        confirmLoading={savingWithdrawalAccount}
        onCancel={() => {
          setWithdrawalAccountWorker(null)
          setWithdrawalAccounts([])
          withdrawalAccountForm.resetFields()
        }}
        onOk={() => withdrawalAccountForm.submit()}
        destroyOnHidden
      >
        <Form form={withdrawalAccountForm} layout="vertical" onFinish={submitWithdrawalAccount}>
          <Form.Item label="打手">
            <Typography.Text>
              {withdrawalAccountWorker?.displayName || withdrawalAccountWorker?.username || '-'}
            </Typography.Text>
          </Form.Item>
          <Form.Item
            label="提现方式"
            name="accountChannel"
            rules={[{ required: true, message: '请选择提现方式' }]}
          >
            <Select
              loading={loadingWithdrawalAccounts}
              options={[
                { value: 'alipay', label: '支付宝' },
                { value: 'wechat', label: '微信收款' },
              ]}
              onChange={(accountChannel) => setWithdrawalAccountFormValues(accountChannel)}
            />
          </Form.Item>
          <Form.Item
            label="收款人姓名"
            name="accountName"
            rules={[{ required: true, message: '请输入收款人姓名' }]}
          >
            <Input placeholder="请输入真实姓名" />
          </Form.Item>
          {withdrawalAccountChannel === 'wechat' ? (
            <Form.Item
              label="微信收款二维码"
              name="wechatQrCodeImages"
              rules={[{ required: true, message: '请上传微信收款二维码' }]}
            >
              <ImageUpload scene="admin-worker-withdrawal-wechat-qr" scope="admin" maxCount={1} />
            </Form.Item>
          ) : (
            <>
              <Form.Item
                label="支付宝账号"
                name="accountNo"
                rules={
                  editingAlipayAccount ? [] : [{ required: true, message: '请输入支付宝账号' }]
                }
              >
                <Input
                  placeholder={
                    editingAlipayAccount ? '历史账户未登记账号，可仅补充二维码' : '请输入支付宝账号'
                  }
                />
              </Form.Item>
              <Form.Item
                label="支付宝收款二维码"
                name="alipayQrCodeImages"
                rules={[{ required: true, message: '请上传支付宝收款二维码' }]}
              >
                <ImageUpload scene="admin-worker-withdrawal-alipay-qr" scope="admin" maxCount={1} />
              </Form.Item>
            </>
          )}
        </Form>
      </Modal>

      <Modal
        title="调整打手等级"
        open={Boolean(levelWorker)}
        onCancel={() => {
          setLevelWorker(null)
          levelForm.resetFields()
        }}
        onOk={() => levelForm.submit()}
        destroyOnHidden
      >
        <Form form={levelForm} layout="vertical" onFinish={submitLevel}>
          <Form.Item label="打手">
            <Typography.Text>
              {levelWorker?.displayName || levelWorker?.username || '-'}
            </Typography.Text>
          </Form.Item>
          <Form.Item
            label="目标等级"
            name="levelId"
            rules={[{ required: true, message: '请选择目标等级' }]}
          >
            <Select
              loading={levelsQuery.isLoading}
              options={(levelsQuery.data?.data.items || []).map((item) => ({
                value: item.levelId,
                label: `${item.name} / 最多同时 ${item.maxActiveOrders} 单`,
              }))}
            />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="人工增加余额"
        open={Boolean(creditWorker)}
        onCancel={() => {
          setCreditWorker(null)
          creditForm.resetFields()
        }}
        onOk={() => creditForm.submit()}
        destroyOnHidden
      >
        <Form form={creditForm} layout="vertical" onFinish={submitCredit}>
          <Form.Item label="金额" name="amount" rules={[{ required: true, message: '请输入金额' }]}>
            <InputNumber min={0.01} step={10} addonAfter="元" className="full-width" />
          </Form.Item>
          <Form.Item label="备注" name="note">
            <Input />
          </Form.Item>
        </Form>
      </Modal>

      <WorkerDetailDrawer worker={detailWorker} onClose={() => setDetailWorker(null)} />
    </Card>
  )
}
