import {
  DeleteOutlined,
  EditOutlined,
  FormOutlined,
  LinkOutlined,
  PlusOutlined,
  ReloadOutlined,
} from '@ant-design/icons'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import {
  App,
  Button,
  Card,
  Divider,
  Form,
  Input,
  InputNumber,
  Modal,
  Popconfirm,
  Radio,
  Select,
  Space,
  Switch,
  Table,
  Tabs,
  Tag,
  Typography,
} from 'antd'
import type { TableColumnsType } from 'antd'
import { useEffect, useMemo, useRef, useState } from 'react'
import { useNavigate, useSearchParams } from 'react-router'

import {
  deleteAdminWorkProductRule,
  deleteAdminWorkProductRuleMapping,
  fetchAdminKuaishouIndustryShops,
  fetchAdminWorkCategories,
  fetchAdminWorkProductRuleMappings,
  fetchAdminWorkProductRules,
  reprocessAdminKuaishouWorkOrderMatches,
  saveAdminWorkProductRule,
  syncAdminWorkProductRulePrice,
} from '@/services/admin'
import type { CollectField, WorkProductRule, WorkProductRuleMapping } from '@/types/worker-platform'
import type { AdminKuaishouIndustryShopOption } from '@/types/admin'
import { ADMIN_DEFAULT_PAGE_SIZE, buildAdminTablePagination } from '@/utils/admin-pagination'
import { formatMoney } from './shared'
import { WorkProductBindingForm, type SourcePrefill } from './WorkProductBindingForm'

export default function ProductRulesPanel() {
  const { message } = App.useApp()
  const queryClient = useQueryClient()
  const [form] = Form.useForm()
  const navigate = useNavigate()
  const [searchParams] = useSearchParams()
  const hasInitializedRuleSelection = useRef(false)

  const [editingRule, setEditingRule] = useState<WorkProductRule | null>(null)
  const [syncingPrice, setSyncingPrice] = useState(false)
  const [activeMappingId, setActiveMappingId] = useState<number | 'new' | null>(null)
  const [sourcePrefill, setSourcePrefill] = useState<SourcePrefill | null>(null)

  const [keywordInput, setKeywordInput] = useState('')
  const [keyword, setKeyword] = useState('')
  const [categoryId, setCategoryId] = useState<number | undefined>()
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(ADMIN_DEFAULT_PAGE_SIZE)

  const rulesQuery = useQuery({
    queryKey: ['admin-worker-platform-product-rules', keyword, categoryId, page, pageSize],
    queryFn: () =>
      fetchAdminWorkProductRules({
        keyword,
        categoryId,
        page,
        pageSize,
      }),
  })
  const mappingsQuery = useQuery({
    queryKey: ['admin-worker-platform-product-mappings'],
    queryFn: () => fetchAdminWorkProductRuleMappings(),
  })
  const ruleMappingsQuery = useQuery({
    queryKey: ['admin-worker-platform-product-mappings', 'rule', editingRule?.ruleId],
    queryFn: () =>
      fetchAdminWorkProductRuleMappings({ ruleId: editingRule?.ruleId }).then(
        (response) => response.data,
      ),
    enabled: Boolean(editingRule?.ruleId),
  })
  const categoriesQuery = useQuery({
    queryKey: ['admin-worker-platform-categories'],
    queryFn: () => fetchAdminWorkCategories(),
  })
  const shopsQuery = useQuery({
    queryKey: ['admin-kuaishou-industry-shops', 'product-rules'],
    queryFn: fetchAdminKuaishouIndustryShops,
  })

  const shops = shopsQuery.data?.data.shops || []
  const shopNameBySellerId = useMemo(() => createShopNameBySellerId(shops), [shops])
  const ruleMappings = ruleMappingsQuery.data?.items || []

  const rules = rulesQuery.data?.data.items || []
  const mappings = mappingsQuery.data?.data.items || []
  const mappingsByRuleId = new Map<number, WorkProductRuleMapping[]>()
  for (const mapping of mappings) {
    const rMappings = mappingsByRuleId.get(mapping.ruleId) || []
    rMappings.push(mapping)
    mappingsByRuleId.set(mapping.ruleId, rMappings)
  }
  const rulesPagination = rulesQuery.data?.data.pagination
  const categoryCounts = new Map(
    (rulesQuery.data?.data.categoryCounts || []).map((item) => [
      item.categoryId === null ? 'uncategorized' : String(item.categoryId),
      item.total,
    ]),
  )

  // 首次加载时默认选中第一条；新建时必须保留空表单，不能再次自动选回旧模板。
  useEffect(() => {
    if (!hasInitializedRuleSelection.current && !editingRule && rules.length > 0) {
      hasInitializedRuleSelection.current = true
      editRule(rules[0])
    }
  }, [rules, editingRule])

  // Sync activeMappingId when ruleMappings load
  useEffect(() => {
    if (ruleMappings.length > 0) {
      if (
        activeMappingId !== 'new' &&
        (!activeMappingId || !ruleMappings.some((m) => m.mappingId === activeMappingId))
      ) {
        setActiveMappingId(ruleMappings[0].mappingId)
      }
    } else {
      setActiveMappingId('new')
    }
  }, [ruleMappings, activeMappingId])

  function searchRules(value = keywordInput) {
    setKeyword(value.trim())
    setPage(1)
  }

  // Handle URL navigation like ?tab=rules&bind=1&sellerId=...
  useEffect(() => {
    if (!searchParams.get('bind')) return
    const prefill: SourcePrefill = {
      sellerId: String(searchParams.get('sellerId') || '').trim(),
      relItemId: String(searchParams.get('relItemId') || '').trim(),
      itemTitle: String(searchParams.get('itemTitle') || '').trim(),
      relSkuId: String(searchParams.get('relSkuId') || '').trim(),
      skuNick: String(searchParams.get('skuNick') || '').trim(),
    }
    if (!prefill.sellerId) {
      void navigate('/admin/worker-platform?tab=rules', { replace: true })
      return
    }
    setSourcePrefill(prefill)
    setActiveMappingId('new')
    void navigate('/admin/worker-platform?tab=rules', { replace: true })
  }, [navigate, searchParams])

  function resetRuleForm() {
    setEditingRule(null)
    setActiveMappingId('new')
    setSourcePrefill(null)
    form.resetFields()
  }

  function editRule(rule: WorkProductRule) {
    setEditingRule(rule)
    setActiveMappingId(null) // will auto-select first mapping in useEffect
    const hasManualSharingOverride = hasManualSharingInput(
      rule.sharing?.totalQuantity,
      rule.sharing?.unitReward,
    )
    form.setFieldsValue({
      provider: rule.provider,
      platform: rule.platform,
      shopId: rule.shopId,
      skuCode: rule.skuCode,
      productName: rule.productName,
      matchType: rule.matchType,
      sellerId: rule.match.sellerId,
      itemId: rule.match.itemId,
      relItemId: rule.match.relItemId,
      skuId: rule.match.skuId,
      relSkuId: rule.match.relSkuId,
      itemTitle: rule.match.itemTitle,
      skuNick: rule.match.skuNick,
      itemTitleMatchType: rule.match.itemTitleMatchType,
      skuNickMatchType: rule.match.skuNickMatchType,
      categoryId: rule.categoryId || undefined,
      pricingMode: rule.unitPriceFen > 0 ? 'unit' : 'fixed',
      rewardAmount: rule.rewardAmount / 100,
      unitPrice: rule.unitPriceFen / 100,
      sharingEnabled: rule.sharing?.enabled || false,
      sharingAutoFromOrder: rule.sharing?.autoFromOrder || false,
      sharingTotalQuantity: hasManualSharingOverride ? rule.sharing?.totalQuantity : undefined,
      sharingUnitReward: hasManualSharingOverride
        ? (rule.sharing?.unitReward || 0) / 100
        : undefined,
      sharingTotalAmount: hasManualSharingOverride
        ? ((rule.sharing?.totalQuantity || 1) * (rule.sharing?.unitReward || 0)) / 100
        : undefined,
      timeoutMinutes: rule.timeoutMinutes || 0,
      timeoutPolicy: rule.timeoutPolicy || 'reopen',
      acceptanceMode: rule.acceptanceMode || 'standard',
      giftCooldownUnit: Number(rule.giftCooldownMinutes || 0) > 0 ? 'minutes' : 'hours',
      giftCooldownValue:
        Number(rule.giftCooldownMinutes || 0) > 0
          ? Number(rule.giftCooldownMinutes || 0)
          : Number(rule.giftCooldownHours ?? 72),
      fieldsText: formatRuleFields(rule.requirement?.fields || []),
      sortOrder: rule.sortOrder,
      enabled: rule.enabled,
      autoCreate: rule.autoCreate,
    })
  }

  async function saveRule(values: {
    ruleId?: number
    ruleKey?: string
    provider?: string
    platform?: string
    shopId?: string
    skuCode?: string
    productName?: string
    matchType?: string
    sellerId?: string
    itemId?: string
    relItemId?: string
    skuId?: string
    relSkuId?: string
    itemTitle?: string
    skuNick?: string
    itemTitleMatchType?: 'contains' | 'exact'
    skuNickMatchType?: 'contains' | 'exact'
    categoryId?: number
    rewardAmount?: number
    pricingMode?: string
    unitPrice?: number
    sharingEnabled?: boolean
    sharingAutoFromOrder?: boolean
    sharingTotalQuantity?: number
    sharingUnitReward?: number
    sharingTotalAmount?: number
    timeoutMinutes?: number
    timeoutPolicy?: string
    acceptanceMode?: string
    giftCooldownUnit?: 'hours' | 'minutes'
    giftCooldownValue?: number
    fieldsText?: string
    enabled?: boolean
    autoCreate?: boolean
    sortOrder?: number
  }) {
    try {
      const unitMode = values.pricingMode === 'unit'
      const isFriendGift = values.acceptanceMode === 'friend_gift'
      if (isFriendGift && values.sharingEnabled === true) {
        message.error('好友赠送验收模式不支持拼单，请先关闭拼单')
        return
      }
      const hasManualSharingOverride =
        form.isFieldTouched('sharingTotalQuantity') || form.isFieldTouched('sharingUnitReward')
          ? Number(values.sharingTotalQuantity || 0) > 0 ||
            Number(values.sharingUnitReward || 0) > 0
          : hasManualSharingInput(values.sharingTotalQuantity, values.sharingUnitReward)
      const { pricingMode: _pricingMode, giftCooldownUnit, giftCooldownValue, ...payload } = values
      const res = await saveAdminWorkProductRule({
        ...payload,
        ruleId: editingRule?.ruleId,
        ruleKey: editingRule?.ruleKey || '',
        unitPrice: unitMode ? Number(values.unitPrice || 0) : 0,
        acceptanceMode: isFriendGift ? 'friend_gift' : 'standard',
        giftCooldownHours:
          isFriendGift && giftCooldownUnit !== 'minutes' ? Number(giftCooldownValue || 0) : 0,
        giftCooldownMinutes:
          isFriendGift && giftCooldownUnit === 'minutes' ? Number(giftCooldownValue || 0) : 0,
        sharingEnabled: isFriendGift ? false : values.sharingEnabled === true,
        sharingAutoFromOrder:
          unitMode && values.sharingEnabled === true && !hasManualSharingOverride,
      })
      message.success(editingRule ? '接单模板已更新' : '接单模板已创建')
      const savedRule = res.data?.rule
      if (savedRule) {
        editRule(savedRule)
      } else {
        resetRuleForm()
      }
      await Promise.all([
        queryClient.invalidateQueries({
          queryKey: ['admin-worker-platform-product-rules'],
        }),
        queryClient.invalidateQueries({
          queryKey: ['admin-worker-platform-summary'],
        }),
      ])
    } catch (error) {
      message.error(error instanceof Error ? error.message : '保存失败')
    }
  }

  function confirmSyncRulePrice() {
    if (!editingRule) return
    Modal.confirm({
      title: '同步模板价格',
      content:
        '将同步接单大厅中该模板的待抢单价格。部分拼单仅调整剩余份额价格，已加入份额报酬保持不变。',
      okText: '确认同步',
      cancelText: '取消',
      onOk: async () => {
        setSyncingPrice(true)
        try {
          const response = await syncAdminWorkProductRulePrice(editingRule.ruleId)
          const result = response.data
          message.success(
            `已同步 ${result.updatedCount} 单：待抢单 ${result.updatedNormalCount} 单，部分拼单 ${result.updatedPartialSharingCount} 单`,
          )
          await Promise.all([
            queryClient.invalidateQueries({ queryKey: ['admin-worker-platform-product-rules'] }),
            queryClient.invalidateQueries({ queryKey: ['admin-worker-platform-orders'] }),
          ])
        } catch (error) {
          message.error(error instanceof Error ? error.message : '同步价格失败')
          throw error
        } finally {
          setSyncingPrice(false)
        }
      },
    })
  }

  async function toggleRuleEnabled(rule: WorkProductRule, enabled: boolean) {
    try {
      const hasManualSharingOverride = hasManualSharingInput(
        rule.sharing?.totalQuantity,
        rule.sharing?.unitReward,
      )
      await saveAdminWorkProductRule({
        ruleId: rule.ruleId,
        ruleKey: rule.ruleKey,
        provider: rule.provider,
        platform: rule.platform,
        productName: rule.productName,
        categoryId: rule.categoryId || undefined,
        rewardAmount: rule.rewardAmount / 100,
        unitPrice: rule.unitPriceFen / 100,
        sharingEnabled: rule.sharing?.enabled || false,
        sharingAutoFromOrder:
          rule.unitPriceFen > 0 && rule.sharing?.enabled === true && !hasManualSharingOverride,
        sharingTotalQuantity: hasManualSharingOverride ? rule.sharing?.totalQuantity : undefined,
        sharingUnitReward: hasManualSharingOverride
          ? (rule.sharing?.unitReward || 0) / 100
          : undefined,
        sharingTotalAmount: hasManualSharingOverride
          ? ((rule.sharing?.totalQuantity || 1) * (rule.sharing?.unitReward || 0)) / 100
          : undefined,
        timeoutMinutes: rule.timeoutMinutes || 0,
        timeoutPolicy: rule.timeoutPolicy || 'reopen',
        fieldsText: formatRuleFields(rule.requirement?.fields || []),
        sortOrder: rule.sortOrder,
        enabled,
        autoCreate: rule.autoCreate,
      })
      message.success(`规则「${rule.ruleKey}」已${enabled ? '启用' : '停用'}`)
      await queryClient.invalidateQueries({
        queryKey: ['admin-worker-platform-product-rules'],
      })
    } catch (error) {
      message.error(error instanceof Error ? error.message : '修改状态失败')
    }
  }

  async function removeRule(rule: WorkProductRule) {
    try {
      await deleteAdminWorkProductRule(rule.ruleId)
      if (editingRule?.ruleId === rule.ruleId) {
        resetRuleForm()
      }
      message.success('接单模板已删除')
      await queryClient.invalidateQueries({
        queryKey: ['admin-worker-platform-product-rules'],
      })
      await queryClient.invalidateQueries({
        queryKey: ['admin-worker-platform-product-mappings'],
      })
    } catch (error) {
      message.error(error instanceof Error ? error.message : '删除失败')
    }
  }

  async function deleteBinding(mapping: WorkProductRuleMapping) {
    try {
      await deleteAdminWorkProductRuleMapping(mapping.mappingId)
      message.success('商品绑定已删除')
      setActiveMappingId(null)
      await Promise.all([
        queryClient.invalidateQueries({ queryKey: ['admin-worker-platform-product-mappings'] }),
        queryClient.invalidateQueries({ queryKey: ['admin-worker-platform-product-rules'] }),
      ])
    } catch (error) {
      message.error(error instanceof Error ? error.message : '删除商品绑定失败')
    }
  }

  async function handleBindingSaved(savedMappingId?: number) {
    if (savedMappingId) {
      setActiveMappingId(savedMappingId)
    }
    setSourcePrefill(null)
    await Promise.all([
      queryClient.invalidateQueries({ queryKey: ['admin-worker-platform-product-mappings'] }),
      queryClient.invalidateQueries({ queryKey: ['admin-worker-platform-product-rules'] }),
    ])
  }

  async function reprocessKuaishouOrders() {
    try {
      const response = await reprocessAdminKuaishouWorkOrderMatches()
      const result = response.data
      message.success(
        `已扫描 ${result.scannedCount} 笔快手订单，新增 ${result.createdCount} 个接单工单`,
      )
      await Promise.all([
        queryClient.invalidateQueries({ queryKey: ['admin-worker-platform-product-rules'] }),
        queryClient.invalidateQueries({ queryKey: ['admin-worker-platform-summary'] }),
        queryClient.invalidateQueries({ queryKey: ['admin-worker-platform-orders'] }),
      ])
    } catch (error) {
      message.error(error instanceof Error ? error.message : '快手订单重匹配失败')
    }
  }

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

  const bindingSummaryColumns: TableColumnsType<WorkProductRuleMapping> = [
    {
      title: '店铺 / 商品',
      key: 'product',
      render: (_, row) => (
        <div className="cell-stack">
          <Typography.Text strong ellipsis={{ tooltip: row.itemTitle || row.relItemId }}>
            {row.itemTitle || (row.relItemId ? `指定商品 ${row.relItemId}` : '全部商品')}
          </Typography.Text>
          <Typography.Text type="secondary" style={{ fontSize: 12 }}>
            店铺{' '}
            {row.sellerIds
              .map((sellerId) => formatShopLabel(sellerId, shopNameBySellerId))
              .join('、')}
          </Typography.Text>
        </div>
      ),
    },
    {
      title: '类别',
      dataIndex: 'mappingType',
      width: 110,
      render: (value) => (
        <Tag color={value === 'sku_exact' ? 'purple' : value === 'sku_series' ? 'cyan' : 'blue'}>
          {value === 'sku_exact'
            ? 'SKU 精确'
            : value === 'sku_series'
              ? 'SKU 数量系列'
              : '商品默认'}
        </Tag>
      ),
    },
    {
      title: 'SKU 条件',
      key: 'sku',
      width: 140,
      render: (_, row) =>
        row.mappingType === 'product_default' ? (
          <Typography.Text type="secondary">-</Typography.Text>
        ) : (
          <Typography.Text ellipsis={{ tooltip: row.skuNick || row.relSkuId }}>
            {row.skuNick || row.relSkuId || '-'}
          </Typography.Text>
        ),
    },
    {
      title: '模式',
      key: 'mode',
      width: 65,
      render: (_, row) =>
        row.mappingType === 'sku_series' ? (
          <Tag style={{ margin: 0 }}>{row.skuMatchMode === 'exact' ? '精确' : '模糊'}</Tag>
        ) : (
          <Typography.Text type="secondary">-</Typography.Text>
        ),
    },
    {
      title: '状态',
      dataIndex: 'enabled',
      width: 65,
      render: (enabled) => (
        <Tag color={enabled ? 'green' : 'default'} style={{ margin: 0 }}>
          {enabled ? '启用' : '停用'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'actions',
      width: 85,
      render: (_, row) => (
        <Space size={0}>
          <Button
            type="link"
            size="small"
            onClick={(e) => {
              e.stopPropagation()
              setActiveMappingId(row.mappingId)
            }}
          >
            编辑
          </Button>
          <Popconfirm
            title="删除此商品绑定规则？"
            okText="删除"
            cancelText="取消"
            okButtonProps={{ danger: true }}
            onConfirm={() => deleteBinding(row)}
          >
            <Button
              type="text"
              size="small"
              danger
              icon={<DeleteOutlined />}
              onClick={(e) => e.stopPropagation()}
            />
          </Popconfirm>
        </Space>
      ),
    },
  ]

  // Columns for right table (40% width)
  const columns: TableColumnsType<WorkProductRule> = [
    {
      title: '模板 / 分类',
      key: 'rule',
      width: '42%',
      render: (_, row) => (
        <div className="cell-stack">
          <Typography.Text strong title={row.productName || row.ruleKey} ellipsis>
            {row.productName || row.ruleKey}
          </Typography.Text>
          <Space size={4} wrap style={{ marginTop: 2 }}>
            <Tag color="blue" style={{ margin: 0, fontSize: 11, lineHeight: '18px' }}>
              {row.ruleKey}
            </Tag>
            {row.categoryName ? (
              <Tag color="cyan" style={{ margin: 0, fontSize: 11, lineHeight: '18px' }}>
                {row.categoryName}
              </Tag>
            ) : null}
            {row.provider ? (
              <Typography.Text type="secondary" style={{ fontSize: 11 }}>
                {row.provider}
              </Typography.Text>
            ) : null}
          </Space>
        </div>
      ),
    },
    {
      title: '已绑定商品',
      key: 'productMappings',
      width: '24%',
      render: (_, row) => {
        const rMappings = mappingsByRuleId.get(row.ruleId) || []
        const enabledCount = rMappings.filter((m) => m.enabled).length
        const disabledCount = rMappings.length - enabledCount
        return rMappings.length > 0 ? (
          <div className="cell-stack">
            <Tag
              color={enabledCount > 0 ? 'green' : 'default'}
              style={{ margin: 0, width: 'fit-content' }}
            >
              {enabledCount > 0 ? `已匹配 ${enabledCount} 条` : '映射已停用'}
            </Tag>
            {disabledCount > 0 ? (
              <Typography.Text type="secondary" style={{ fontSize: 11 }}>
                另有 {disabledCount} 条停用
              </Typography.Text>
            ) : null}
          </div>
        ) : (
          <Tag style={{ margin: 0, color: '#8c8c8c' }}>未匹配商品</Tag>
        )
      },
    },
    {
      title: '接单金额',
      key: 'reward',
      width: '20%',
      render: (_, row) => (
        <div className="cell-stack">
          <Typography.Text strong style={{ color: '#3f8600', fontSize: 12 }}>
            {row.sharing?.autoFromOrder ? '随订单计算' : formatMoney(row.rewardAmount)}
          </Typography.Text>
          {row.unitPriceFen > 0 ? (
            <Typography.Text type="secondary" style={{ fontSize: 11 }}>
              按件: {formatMoney(row.unitPriceFen)}
            </Typography.Text>
          ) : null}
        </div>
      ),
    },
    {
      title: '状态',
      key: 'status',
      width: '14%',
      render: (_, row) => (
        <Space direction="vertical" size={2}>
          <Switch
            size="small"
            checked={row.enabled}
            checkedChildren="开"
            unCheckedChildren="关"
            onChange={(checked) => toggleRuleEnabled(row, checked)}
            onClick={(_, e) => e.stopPropagation()}
          />
          <Space size={2} wrap>
            {row.autoCreate ? (
              <Tag color="blue" style={{ fontSize: 10, margin: 0, padding: '0 3px' }}>
                自动
              </Tag>
            ) : null}
            {row.sharing?.enabled ? (
              <Tag color="purple" style={{ fontSize: 10, margin: 0, padding: '0 3px' }}>
                拼单
              </Tag>
            ) : null}
            {row.acceptanceMode === 'friend_gift' ? (
              <Tag color="orange" style={{ fontSize: 10, margin: 0, padding: '0 3px' }}>
                好友赠送
              </Tag>
            ) : null}
          </Space>
        </Space>
      ),
    },
    {
      title: '操作',
      key: 'actions',
      width: '10%',
      render: (_, row) => (
        <Space size={0} onClick={(event) => event.stopPropagation()}>
          <Button
            type="text"
            icon={<EditOutlined />}
            size="small"
            aria-label={`编辑规则 ${row.ruleKey}`}
            title="编辑规则"
            onClick={() => editRule(row)}
          />
          <Popconfirm
            title={`删除规则“${row.productName || row.ruleKey}”？`}
            description="删除后不会影响已创建工单。"
            okText="删除"
            cancelText="取消"
            okButtonProps={{ danger: true }}
            onConfirm={() => removeRule(row)}
          >
            <Button
              type="text"
              danger
              size="small"
              icon={<DeleteOutlined />}
              aria-label={`删除规则 ${row.ruleKey}`}
              title="删除规则"
            />
          </Popconfirm>
        </Space>
      ),
    },
  ]

  return (
    <section className="platform-panel-stack">
      <div className="product-rules-layout">
        {/* Left Form Card - 60% Width Split */}
        <Card
          className="product-rules-form-card"
          title={
            <Space size={8}>
              <FormOutlined style={{ color: '#1677ff' }} />
              <Typography.Text strong style={{ fontSize: 15 }}>
                {editingRule
                  ? `编辑模板 · ${editingRule.productName || editingRule.ruleKey}`
                  : '新建接单模板'}
              </Typography.Text>
            </Space>
          }
          extra={
            <Space size={8} align="center">
              {editingRule ? (
                <Button size="middle" onClick={resetRuleForm}>
                  + 新建模板
                </Button>
              ) : null}
              {editingRule ? (
                <Button loading={syncingPrice} size="middle" onClick={confirmSyncRulePrice}>
                  同步价格
                </Button>
              ) : null}
              <Button type="primary" size="middle" htmlType="submit" form="product-rule-form">
                {editingRule ? '保存模板' : '创建模板'}
              </Button>
            </Space>
          }
          bordered={false}
        >
          <Form
            id="product-rule-form"
            form={form}
            layout="vertical"
            className="product-rule-main-form"
            initialValues={{
              platform: 'kuaishou',
              matchType: 'contains',
              itemTitleMatchType: 'exact',
              skuNickMatchType: 'exact',
              pricingMode: 'fixed',
              rewardAmount: 25,
              enabled: true,
              autoCreate: true,
              sharingEnabled: false,
              acceptanceMode: 'standard',
              giftCooldownUnit: 'hours',
              giftCooldownValue: 72,
              fieldsText:
                'gameId:游戏编号\ngameNickname:游戏昵称\nsystem:系统#安卓,苹果\nserverZone:区服#QQ区,微信区',
            }}
            onFinish={saveRule}
          >
            {/* 基础信息 */}
            <div className="form-grid-3col">
              <Form.Item
                label="模板名称"
                name="productName"
                className="span-2"
                rules={[{ required: true, message: '请输入模板名称' }]}
              >
                <Input placeholder="例如：指挥官密钥标准模板" />
              </Form.Item>

              <Form.Item label="所属分类" name="categoryId">
                <Select
                  allowClear
                  placeholder="选择分类"
                  loading={categoriesQuery.isLoading}
                  options={(categoriesQuery.data?.data.items || []).map((item) => ({
                    value: item.categoryId,
                    label: item.name,
                  }))}
                />
              </Form.Item>
            </div>

            {/* Row 2: 计价方式 + 单价/金额 + 任务时限 */}
            <div className="form-grid-3col">
              <Form.Item label="计价方式" name="pricingMode">
                <Radio.Group
                  optionType="button"
                  buttonStyle="solid"
                  className="full-width"
                  options={[
                    { value: 'fixed', label: '固定金额' },
                    { value: 'unit', label: '按件计价' },
                  ]}
                />
              </Form.Item>

              <Form.Item noStyle shouldUpdate>
                {({ getFieldValue }) =>
                  getFieldValue('pricingMode') === 'unit' ? (
                    <Form.Item
                      label="按件单价"
                      name="unitPrice"
                      rules={[{ required: true, message: '请填写单价' }]}
                    >
                      <InputNumber min={0.01} step={1} addonAfter="元" className="full-width" />
                    </Form.Item>
                  ) : (
                    <Form.Item label="接单金额" name="rewardAmount">
                      <InputNumber min={0} step={1} addonAfter="元" className="full-width" />
                    </Form.Item>
                  )
                }
              </Form.Item>

              <Form.Item label="任务时限" name="timeoutMinutes">
                <InputNumber min={0} step={5} addonAfter="分钟" className="full-width" />
              </Form.Item>
            </div>

            {/* 验收模式：好友赠送模式与拼单互斥 */}
            <div className="form-grid-3col">
              <Form.Item
                label="验收模式"
                name="acceptanceMode"
                extra="好友赠送：打手接单后先提交本人资料，后台加好友并冷却后才能赠送交付"
              >
                <Radio.Group
                  optionType="button"
                  buttonStyle="solid"
                  className="full-width"
                  options={[
                    { value: 'standard', label: '标准验收' },
                    { value: 'friend_gift', label: '好友赠送' },
                  ]}
                  onChange={(event) => {
                    if (event.target.value === 'friend_gift') {
                      form.setFieldsValue({ sharingEnabled: false })
                    }
                  }}
                />
              </Form.Item>

              <Form.Item noStyle shouldUpdate>
                {({ getFieldValue }) =>
                  getFieldValue('acceptanceMode') === 'friend_gift' ? (
                    <Form.Item label="赠送冷却" required>
                      <Space.Compact className="full-width">
                        <Form.Item name="giftCooldownUnit" noStyle>
                          <Select
                            style={{ width: 100 }}
                            options={[
                              { value: 'hours', label: '按小时' },
                              { value: 'minutes', label: '按分钟' },
                            ]}
                          />
                        </Form.Item>
                        <Form.Item
                          noStyle
                          shouldUpdate={(previous, current) =>
                            previous.giftCooldownUnit !== current.giftCooldownUnit
                          }
                        >
                          {({ getFieldValue }) => {
                            const unit = getFieldValue('giftCooldownUnit')
                            const isMinutes = unit === 'minutes'
                            return (
                              <Form.Item
                                name="giftCooldownValue"
                                noStyle
                                rules={[{ required: true, message: '请填写冷却时长' }]}
                              >
                                <InputNumber
                                  min={1}
                                  max={isMinutes ? 43200 : 720}
                                  step={1}
                                  addonAfter={isMinutes ? '分钟' : '小时'}
                                  className="full-width"
                                />
                              </Form.Item>
                            )
                          }}
                        </Form.Item>
                      </Space.Compact>
                      <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                        选择小时或分钟其中一种单位；最长 30 天（720 小时 / 43200 分钟）。
                      </Typography.Text>
                    </Form.Item>
                  ) : (
                    <Form.Item label={<span />} />
                  )
                }
              </Form.Item>
            </div>

            {/* Row 3: 超时策略 + 来源 + 平台 */}
            <div className="form-grid-3col">
              <Form.Item label="超时策略" name="timeoutPolicy">
                <Select
                  options={[
                    { value: 'reopen', label: '释放押金退回大厅' },
                    { value: 'cancel_release', label: '取消订单退押金' },
                    { value: 'cancel_deduct', label: '取消订单扣押金' },
                  ]}
                />
              </Form.Item>

              <Form.Item label="来源" name="provider">
                <Input placeholder="如 91kaquan" />
              </Form.Item>

              <Form.Item label="平台" name="platform">
                <Input placeholder="如 kuaishou" />
              </Form.Item>
            </div>

            {/* Row 4: 排序权重 + 功能开关与拼单行内参数 */}
            <div className="form-grid-3col">
              <Form.Item label="排序权重" name="sortOrder">
                <InputNumber min={0} max={9999} placeholder="0" className="full-width" />
              </Form.Item>

              <Form.Item noStyle shouldUpdate>
                {({ getFieldValue }) => {
                  const sharingEnabled = getFieldValue('sharingEnabled')
                  const unitMode = getFieldValue('pricingMode') === 'unit'
                  const friendGiftMode = getFieldValue('acceptanceMode') === 'friend_gift'

                  return (
                    <div className="switches-inline-group span-2">
                      <Form.Item label="启用模板" name="enabled" valuePropName="checked">
                        <Switch size="small" />
                      </Form.Item>
                      <Form.Item label="自动建单" name="autoCreate" valuePropName="checked">
                        <Switch size="small" />
                      </Form.Item>
                      <Form.Item
                        label="启用拼单"
                        name="sharingEnabled"
                        valuePropName="checked"
                        tooltip={friendGiftMode ? '好友赠送模式不支持拼单' : undefined}
                      >
                        <Switch size="small" disabled={friendGiftMode} />
                      </Form.Item>

                      {sharingEnabled ? (
                        <div className="sharing-inline-inputs">
                          <Form.Item name="sharingTotalQuantity" style={{ margin: 0 }}>
                            <InputNumber
                              size="small"
                              min={1}
                              placeholder="拼单数量"
                              addonAfter="份"
                              style={{ width: 115 }}
                              onChange={(value) =>
                                !unitMode &&
                                syncSharingRuleForm({ sharingTotalQuantity: Number(value) || 0 })
                              }
                            />
                          </Form.Item>
                          <Form.Item name="sharingUnitReward" style={{ margin: 0 }}>
                            <InputNumber
                              size="small"
                              min={0.01}
                              step={1}
                              placeholder="拼单单价"
                              addonAfter="元"
                              style={{ width: 115 }}
                              onChange={(value) =>
                                !unitMode &&
                                syncSharingRuleForm({ sharingUnitReward: Number(value) || 0 })
                              }
                            />
                          </Form.Item>
                          {!unitMode ? (
                            <Form.Item name="sharingTotalAmount" style={{ margin: 0 }}>
                              <InputNumber
                                size="small"
                                min={0.01}
                                step={1}
                                placeholder="拼单总价"
                                addonAfter="元"
                                style={{ width: 115 }}
                                onChange={(value) =>
                                  syncSharingRuleForm({ sharingTotalAmount: Number(value) || 0 })
                                }
                              />
                            </Form.Item>
                          ) : null}
                        </div>
                      ) : null}
                    </div>
                  )
                }}
              </Form.Item>
            </div>

            {/* 资料字段 */}
            <Form.Item
              label="资料字段（工单要求打手提交的资料）"
              name="fieldsText"
              extra="格式：key:名称#选项1,选项2（每行一个字段）"
            >
              <Input.TextArea
                rows={2}
                placeholder={
                  'gameId:游戏编号\ngameNickname:游戏昵称\nsystem:系统#安卓,苹果\nserverZone:区服#QQ区,微信区'
                }
              />
            </Form.Item>
          </Form>

          <Divider style={{ margin: '14px 0 12px' }} />

          {/* 适用商品绑定区域 */}
          <div className="binding-section-container">
            <div className="binding-section-header">
              <Space align="center" size={8}>
                <LinkOutlined style={{ color: '#1677ff' }} />
                <Typography.Text strong style={{ fontSize: 14 }}>
                  适用商品绑定
                </Typography.Text>
                {editingRule ? (
                  <Tag color={ruleMappings.length > 0 ? 'blue' : 'default'} style={{ margin: 0 }}>
                    已绑定 {ruleMappings.length} 条规则
                  </Tag>
                ) : null}
              </Space>
            </div>

            {editingRule ? (
              <div className="binding-editor-wrap">
                {/* 内联编辑表单（直接展开，免弹窗） */}
                <WorkProductBindingForm
                  ruleId={editingRule.ruleId}
                  ruleName={editingRule.productName || editingRule.ruleKey}
                  shops={shops}
                  mappings={ruleMappings}
                  activeMappingId={activeMappingId}
                  sourcePrefill={sourcePrefill}
                  onSelectMapping={(id) => setActiveMappingId(id)}
                  onDeleteMapping={deleteBinding}
                  onSaved={handleBindingSaved}
                />
              </div>
            ) : (
              <div className="empty-rule-hint">
                <Typography.Text type="secondary">
                  💡 填写并保存接单模板后，即可在此直接配置适用商品绑定与 SKU 匹配规则。
                </Typography.Text>
              </div>
            )}
          </div>
        </Card>

        {/* Right Table Card - 40% Width */}
        <Card
          className="product-rules-list-card"
          title={
            <Space align="center" size={8}>
              <Typography.Text strong style={{ fontSize: 15 }}>
                接单模板列表
              </Typography.Text>
              <Tag color="blue" style={{ margin: 0 }}>
                {rulesPagination?.total || 0}
              </Tag>
            </Space>
          }
          extra={
            <Space size={6} wrap className="rules-list-card-extra">
              <Input.Search
                allowClear
                placeholder="搜索模板/商品/SKU"
                className="search-input-fluid"
                value={keywordInput}
                onChange={(event) => {
                  const value = event.target.value
                  setKeywordInput(value)
                  if (!value) searchRules('')
                }}
                onSearch={searchRules}
              />
              <Button
                icon={<ReloadOutlined />}
                size="middle"
                loading={rulesQuery.isFetching}
                onClick={() => rulesQuery.refetch()}
              />
              <Button size="middle" onClick={reprocessKuaishouOrders}>
                重匹配
              </Button>
              <Button type="primary" size="middle" icon={<PlusOutlined />} onClick={resetRuleForm}>
                新建
              </Button>
            </Space>
          }
          bordered={false}
        >
          {/* Category Tabs Bar */}
          <div className="product-rules-category-tabs-bar">
            <Tabs
              activeKey={categoryId ? String(categoryId) : 'all'}
              size="small"
              onChange={(key) => {
                setCategoryId(key === 'all' ? undefined : Number(key))
                setPage(1)
              }}
              items={[
                { key: 'all', label: `全部 (${rulesPagination?.total || 0})` },
                ...(categoriesQuery.data?.data.items || []).map((item) => {
                  const count = categoryCounts.get(String(item.categoryId)) || 0
                  return {
                    key: String(item.categoryId),
                    label: `${item.name}${count ? ` (${count})` : ''}`,
                  }
                }),
              ]}
            />
          </div>

          <Table<WorkProductRule>
            rowKey="ruleId"
            size="small"
            loading={rulesQuery.isLoading || mappingsQuery.isLoading}
            dataSource={rules}
            columns={columns}
            rowClassName={(row) => {
              const hasMappings = (mappingsByRuleId.get(row.ruleId) || []).length > 0
              return [
                editingRule?.ruleId === row.ruleId ? 'product-rule-row-active' : '',
                hasMappings ? 'product-rule-row-mapped' : '',
              ]
                .filter(Boolean)
                .join(' ')
            }}
            onRow={(row) => ({
              onClick: () => editRule(row),
              style: { cursor: 'pointer' },
              title: '点击在左侧编辑此模板',
            })}
            pagination={buildAdminTablePagination({
              current: rulesPagination?.page || page,
              pageSize: rulesPagination?.pageSize || pageSize,
              total: rulesPagination?.total || 0,
              onChange: (nextPage, nextPageSize) => {
                setPage(nextPage)
                setPageSize(nextPageSize)
              },
            })}
          />
        </Card>
      </div>
    </section>
  )
}

function formatRuleFields(fields: CollectField[]) {
  return fields
    .map((field) => {
      const options =
        Array.isArray(field.options) && field.options.length > 0
          ? `#${field.options.join(',')}`
          : ''
      return `${field.key}:${field.label}${options}`
    })
    .join('\n')
}

function hasManualSharingInput(quantity: unknown, unitRewardFen: unknown) {
  return Number(quantity || 0) > 1 || Number(unitRewardFen || 0) > 0
}

function createShopNameBySellerId(shops: AdminKuaishouIndustryShopOption[]) {
  const names = new Map<string, string>()
  for (const shop of shops) {
    const name = String(shop.shopName || '').trim()
    if (!name) continue
    const sellerId = String(shop.sellerId || '').trim()
    const shopId = String(shop.shopId || '').trim()
    if (sellerId) names.set(sellerId, name)
    if (shopId) names.set(shopId, name)
  }
  return names
}

function formatShopLabel(sellerId: string, shopNameBySellerId: Map<string, string>) {
  const name = shopNameBySellerId.get(sellerId)
  return name ? `${name}（${sellerId}）` : sellerId
}
