import { useState, useRef } from 'react'
import { toast } from 'sonner'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Info, Check, Upload, Settings as SettingsIcon, FileText, X, Plus, CalendarDays, Sparkles, Trash2 } from 'lucide-react'
import PageGuide from '../../components/ui/PageGuide'
import { payrollApi, employeeApi } from '../../lib/api-services'
import Card from '../../components/ui/Card'
import Button from '../../components/ui/Button'
import { Input, Label } from '../../components/ui/Input'
// 金额格式化：保留两位小数 + 千分位
const fmt = (n: number) => (n || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })

export function OvertimeCalculator() {
  const queryClient = useQueryClient()
  const [step, setStep] = useState<1 | 2 | 3>(1)
  const [month, setMonth] = useState(new Date().toISOString().slice(0, 7))
  const fileInputRef = useRef<HTMLInputElement>(null)
  const [previewData, setPreviewData] = useState<any[]>([])
  const [editingId, setEditingId] = useState<string | null>(null)
  const [editForm, setEditForm] = useState({ weekdayHours: 0, weekendHours: 0, holidayHours: 0 })
  const [showAddForm, setShowAddForm] = useState(false)
  const [addForm, setAddForm] = useState({ employeeId: '', weekdayHours: 0, weekendHours: 0, holidayHours: 0 })

  // 加班费规则配置
  const { data: config, isLoading: configLoading } = useQuery<any>({
    queryKey: ['overtime-config'],
    queryFn: async () => {
      return await payrollApi.overtimeConfig()
    },
  })

  const saveConfigMutation = useMutation({
    mutationFn: (data: any) => payrollApi.saveOvertimeConfig(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['overtime-config'] })
    },
  })

  // 节假日配置
  const [holidayYear, setHolidayYear] = useState(new Date().getFullYear().toString())
  const [showHolidays, setShowHolidays] = useState(false)
  const [holidayForm, setHolidayForm] = useState({ date: '', type: 'HOLIDAY', name: '' })
  const [holidayItems, setHolidayItems] = useState<{ date: string; type: string; name?: string }[]>([])

  const { data: holidays, refetch: refetchHolidays } = useQuery<any[]>({
    queryKey: ['holidays', holidayYear],
    queryFn: async () => {
      return await payrollApi.holidays(holidayYear)
    },
    enabled: showHolidays,
  })

  const presetHolidaysMutation = useMutation({
    mutationFn: (year: string) => payrollApi.presetHolidays(year),
    onSuccess: (data: any) => {
      toast.success(`已预置 ${data.holidays || 0} 个法定节假日、${data.workdays || 0} 个调休工作日`)
      queryClient.invalidateQueries({ queryKey: ['holidays', holidayYear] })
      refetchHolidays()
    },
    onError: (err: any) => toast.error(err.response?.data?.message || '预置失败'),
  })

  const saveHolidaysMutation = useMutation({
    mutationFn: (data: { year: string; items: { date: string; type: string; name?: string }[] }) =>
      payrollApi.saveHolidays(data),
    onSuccess: () => {
      toast.success('节假日配置已保存')
      queryClient.invalidateQueries({ queryKey: ['holidays', holidayYear] })
      refetchHolidays()
    },
    onError: () => toast.error('保存失败'),
  })

  // 员工列表
  const { data: employees } = useQuery<{ items: { id: string; name: string; department: string }[] }>({
    queryKey: ['employees-for-overtime'],
    queryFn: async () => {
      return await employeeApi.paged({ pageSize: 100 })
    },
  })

  // 加班记录
  const { data: overtimeRecords, refetch } = useQuery<any[]>({
    queryKey: ['overtime-records', month],
    queryFn: async () => {
      return await payrollApi.overtimeRecords({ month })
    },
    enabled: step === 3,
  })

  const batchImportMutation = useMutation({
    mutationFn: (data: any[]) => payrollApi.batchImportOvertime(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['overtime-records'] })
      setPreviewData([])
      setStep(3)
    },
  })

  // 从考勤记录同步加班工时
  const syncFromAttendanceMutation = useMutation({
    mutationFn: (m: string) => payrollApi.syncOvertimeFromAttendance(m),
    onSuccess: (data: any) => {
      toast.success(`已从考勤同步 ${data.synced || 0} 位员工的加班工时`)
      queryClient.invalidateQueries({ queryKey: ['overtime-records'] })
      setStep(3)
    },
    onError: () => toast.error('同步失败'),
  })

  // 更新单条加班记录
  const updateOvertimeMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: any }) =>
      payrollApi.updateOvertime(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['overtime-records'] })
      setEditingId(null)
    },
  })

  // 开始编辑
  const startEdit = (record: any) => {
    setEditingId(record.id)
    setEditForm({
      weekdayHours: record.weekdayHours || 0,
      weekendHours: record.weekendHours || 0,
      holidayHours: record.holidayHours || 0,
    })
  }

  // 保存编辑
  const saveEdit = () => {
    if (editingId) {
      updateOvertimeMutation.mutate({ id: editingId, data: editForm })
    }
  }

  // 手动添加加班记录
  const addOvertimeMutation = useMutation({
    mutationFn: (data: any) => payrollApi.saveOvertime(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['overtime-records'] })
      setShowAddForm(false)
      setAddForm({ employeeId: '', weekdayHours: 0, weekendHours: 0, holidayHours: 0 })
      toast.success('加班记录已添加')
    },
    onError: () => toast.error('添加失败'),
  })

  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return
    const empList = employees?.items || []
    const fileName = file.name.toLowerCase()

    const parseRows = (rows: any[]): void => {
      const items: any[] = []
      for (let i = 0; i < rows.length; i++) {
        const row = rows[i]
        // 兼容中文列名和英文列名
        const empName = String(row['姓名'] ?? row['name'] ?? row['姓名*'] ?? '').trim()
        if (!empName) continue
        const emp = empList.find(e => e.name === empName)
        if (!emp) continue
        items.push({
          employeeId: emp.id,
          employeeName: emp.name,
          department: emp.department,
          month: String(row['月份'] ?? row['month'] ?? '').trim() || month,
          weekdayHours: Number(row['工作日加班时长'] ?? row['weekdayHours'] ?? row['工作日'] ?? 0) || 0,
          weekendHours: Number(row['休息日加班时长'] ?? row['weekendHours'] ?? row['休息日'] ?? 0) || 0,
          holidayHours: Number(row['法定节假日加班时长'] ?? row['holidayHours'] ?? row['法定节假日'] ?? 0) || 0,
        })
      }
      if (items.length > 0) {
        setPreviewData(items)
      } else {
        toast.error('未匹配到员工，请确保文件包含"姓名"列')
      }
    }

    if (fileName.endsWith('.xlsx') || fileName.endsWith('.xls')) {
      // Excel 格式解析
      const reader = new FileReader()
      reader.onload = async (event) => {
        try {
          const data = new Uint8Array(event.target?.result as ArrayBuffer)
          const XLSX = await import('xlsx')
          const wb = XLSX.read(data, { type: 'array' })
          const ws = wb.Sheets[wb.SheetNames[0]]
          const rows = XLSX.utils.sheet_to_json(ws)
          parseRows(rows)
        } catch {
          toast.error('Excel 文件解析失败')
        }
      }
      reader.readAsArrayBuffer(file)
    } else {
      // CSV 格式解析（保持兼容）
      const reader = new FileReader()
      reader.onload = (event) => {
        const text = event.target?.result as string
        const lines = text.split('\n').filter(l => l.trim())
        if (lines.length < 2) { toast.error('CSV 文件内容为空'); return }
        // 解析表头
        const headers = lines[0].split(',').map(c => c.trim())
        const rows: any[] = []
        for (let i = 1; i < lines.length; i++) {
          const cols = lines[i].split(',').map(c => c.trim())
          const row: any = {}
          headers.forEach((h, idx) => { row[h] = cols[idx] ?? '' })
          rows.push(row)
        }
        parseRows(rows)
      }
      reader.readAsText(file)
    }
  }

  const confirmImport = () => {
    const payload = previewData.map(d => ({
      employeeId: d.employeeId,
      month: d.month,
      weekdayHours: d.weekdayHours,
      weekendHours: d.weekendHours,
      holidayHours: d.holidayHours,
    }))
    batchImportMutation.mutate(payload)
  }

  const cfg = config || { weekdayRate: 1.5, weekendRate: 2.0, holidayRate: 3.0, monthlyDays: 21.75, dailyHours: 8 }

  return (
    <div className="space-y-4">
      <PageGuide>
        加班费计算器根据加班类型（工作日/周末/法定节假日）和对应倍率自动计算加班费。流程：①选择月份和员工 → ②录入加班时长 → ③系统按配置倍率计算费用 → ④确认后计入当月工资。
      </PageGuide>
      {/* 步骤指示器 */}
      <div className="flex items-center gap-2">
        {[
          { n: 1, label: '设定计算规则' },
          { n: 2, label: '导入考勤数据' },
          { n: 3, label: '查看加班记录' },
        ].map((s) => (
          <div key={s.n} className="flex items-center gap-2">
            <button
              onClick={() => setStep(s.n as 1 | 2 | 3)}
              className={`px-3 py-1.5 rounded text-xs flex items-center gap-1.5 transition-colors ${
                step === s.n ? 'bg-primary text-white' : 'bg-gray-100 text-gray-500 hover:bg-gray-200'
              }`}
            >
              <span className={`w-4 h-4 rounded-full flex items-center justify-center text-xs ${
                step === s.n ? 'bg-white/20' : step > s.n ? 'bg-safe text-white' : 'bg-gray-300 text-white'
              }`}>{step > s.n ? '✓' : s.n}</span>
              {s.label}
            </button>
            {s.n < 3 && <div className="w-4 h-px bg-gray-300" />}
          </div>
        ))}
      </div>

      {/* Step 1: 设定计算规则 */}
      {step === 1 && (
        <Card>
          <h2 className="text-xs font-medium mb-3 flex items-center gap-2"><SettingsIcon className="w-4 h-4" />加班费计算规则</h2>
          {configLoading ? (
            <div className="text-center py-8 text-gray-500">加载中...</div>
          ) : (
            <div className="space-y-4">
              <div className="grid md:grid-cols-3 gap-4">
                <div>
                  <Label>工作日加班倍率</Label>
                  <Input type="number" step="0.1" defaultValue={cfg.weekdayRate} onBlur={(e) => saveConfigMutation.mutate({ ...cfg, weekdayRate: Number(e.target.value) })} />
                  <p className="text-xs text-gray-500 mt-1">平时加班按小时工资的倍率</p>
                </div>
                <div>
                  <Label>休息日加班倍率</Label>
                  <Input type="number" step="0.1" defaultValue={cfg.weekendRate} onBlur={(e) => saveConfigMutation.mutate({ ...cfg, weekendRate: Number(e.target.value) })} />
                  <p className="text-xs text-gray-500 mt-1">周末加班按小时工资的倍率</p>
                </div>
                <div>
                  <Label>法定节假日加班倍率</Label>
                  <Input type="number" step="0.1" defaultValue={cfg.holidayRate} onBlur={(e) => saveConfigMutation.mutate({ ...cfg, holidayRate: Number(e.target.value) })} />
                  <p className="text-xs text-gray-500 mt-1">法定节假日加班按小时工资的倍率</p>
                </div>
              </div>
              <div className="grid md:grid-cols-2 gap-4">
                <div>
                  <Label>月计薪天数</Label>
                  <Input type="number" step="0.01" defaultValue={cfg.monthlyDays} onBlur={(e) => saveConfigMutation.mutate({ ...cfg, monthlyDays: Number(e.target.value) })} />
                  <p className="text-xs text-gray-500 mt-1">用于折算日工资/小时工资（默认21.75天）</p>
                </div>
                <div>
                  <Label>每日工时（小时）</Label>
                  <Input type="number" step="0.5" defaultValue={cfg.dailyHours} onBlur={(e) => saveConfigMutation.mutate({ ...cfg, dailyHours: Number(e.target.value) })} />
                  <p className="text-xs text-gray-500 mt-1">用于折算小时工资（默认8小时）</p>
                </div>
              </div>
              <div className="bg-blue-50 text-blue-700 text-xs px-3 py-2 rounded-md flex items-start gap-2">
                <Info className="w-4 h-4 mt-0.5 shrink-0" />
                <div>
                  <p>计算公式：小时工资 = 月工资 ÷ 月计薪天数 ÷ 每日工时</p>
                  <p>加班费 = 小时工资 × 倍率 × 加班工时</p>
                  <p className="mt-1 text-gray-500">实际金额在发薪批次中根据员工月工资自动计算，此处只配置倍率规则。</p>
                </div>
              </div>
              {saveConfigMutation.isSuccess && (
                <div className="text-xs text-safe flex items-center gap-1"><Check className="w-3.5 h-3.5" />规则已保存</div>
              )}

              {/* 节假日配置 */}
              <div className="border-t pt-4">
                <button
                  onClick={() => setShowHolidays(!showHolidays)}
                  className="flex items-center gap-2 text-sm font-medium text-gray-700 hover:text-primary"
                >
                  <CalendarDays className="w-4 h-4" />
                  节假日配置
                  <span className="text-xs text-gray-400 font-normal">（用于区分法定节假日和调休工作日）</span>
                </button>
                {showHolidays && (
                  <div className="mt-3 space-y-3 bg-gray-50 rounded-lg p-4">
                    <div className="flex items-center gap-2">
                      <Input type="number" value={holidayYear} onChange={(e) => setHolidayYear(e.target.value)} className="w-24" />
                      <span className="text-xs text-gray-500">年</span>
                      <Button variant="secondary" size="sm" onClick={() => presetHolidaysMutation.mutate(holidayYear)} disabled={presetHolidaysMutation.isPending}>
                        <Sparkles className="w-3.5 h-3.5 mr-1" />
                        {presetHolidaysMutation.isPending ? '预置中...' : '一键预置法定节假日'}
                      </Button>
                    </div>

                    {/* 节假日列表 */}
                    {holidays && holidays.length > 0 ? (
                      <div className="space-y-2 max-h-60 overflow-y-auto">
                        {holidays.map((h: any) => (
                          <div key={h.id} className="flex items-center gap-3 bg-white rounded-md px-3 py-2 text-xs">
                            <span className="font-mono text-gray-700">{h.date.slice(0, 10)}</span>
                            <span className={`px-2 py-0.5 rounded-full ${h.type === 'HOLIDAY' ? 'bg-red-50 text-red-600' : 'bg-blue-50 text-blue-600'}`}>
                              {h.type === 'HOLIDAY' ? '法定节假日' : '调休工作日'}
                            </span>
                            <span className="text-gray-500">{h.name || '-'}</span>
                          </div>
                        ))}
                      </div>
                    ) : (
                      <div className="text-xs text-gray-400 text-center py-4">
                        {holidays ? '暂无节假日配置，点击上方按钮一键预置' : '加载中...'}
                      </div>
                    )}

                    {/* 手动添加 */}
                    <div className="border-t pt-3">
                      <div className="flex items-end gap-2">
                        <div>
                          <Label>日期</Label>
                          <Input type="date" value={holidayForm.date} onChange={(e) => setHolidayForm({ ...holidayForm, date: e.target.value })} className="w-40" />
                        </div>
                        <div>
                          <Label>类型</Label>
                          <select
                            className="h-9 rounded-md border border-gray-200 bg-white px-3 text-sm"
                            value={holidayForm.type}
                            onChange={(e) => setHolidayForm({ ...holidayForm, type: e.target.value })}
                          >
                            <option value="HOLIDAY">法定节假日</option>
                            <option value="WORKDAY">调休工作日</option>
                          </select>
                        </div>
                        <div>
                          <Label>名称</Label>
                          <Input type="text" value={holidayForm.name} onChange={(e) => setHolidayForm({ ...holidayForm, name: e.target.value })} placeholder="如：春节" className="w-32" />
                        </div>
                        <Button size="sm" onClick={() => {
                          if (!holidayForm.date) return toast.error('请选择日期')
                          const newItems = [...(holidays || []), { date: holidayForm.date, type: holidayForm.type, name: holidayForm.name }].sort((a, b) => a.date.localeCompare(b.date))
                          saveHolidaysMutation.mutate({
                            year: holidayYear,
                            items: newItems.map(h => ({ date: h.date.slice(0, 10), type: h.type, name: h.name })),
                          })
                          setHolidayForm({ date: '', type: 'HOLIDAY', name: '' })
                        }}>
                          <Plus className="w-3.5 h-3.5 mr-1" />添加
                        </Button>
                      </div>
                    </div>

                    <div className="bg-blue-50 text-blue-700 text-xs px-3 py-2 rounded-md flex items-start gap-2">
                      <Info className="w-4 h-4 mt-0.5 shrink-0" />
                      <div>
                        <p><b>法定节假日</b>：春节、国庆等法定假日，加班按 3 倍工资</p>
                        <p><b>调休工作日</b>：周末调休上班，按工作日 1.5 倍计算</p>
                        <p className="text-gray-500 mt-1">从考勤同步加班工时时，系统会根据此配置自动判断日期类型</p>
                      </div>
                    </div>
                  </div>
                )}
              </div>

              <div className="flex justify-end">
                <Button onClick={() => setStep(2)}>下一步：导入考勤数据 →</Button>
              </div>
            </div>
          )}
        </Card>
      )}

      {/* Step 2: 导入考勤数据 */}
      {step === 2 && (
        <Card>
          <h2 className="text-xs font-medium mb-3 flex items-center gap-2"><Upload className="w-4 h-4" />导入加班工时</h2>
          <div className="space-y-4">
            <div>
              <Label>月份</Label>
              <Input type="month" value={month} onChange={(e) => setMonth(e.target.value)} className="w-48" />
            </div>
            <div className="border-t pt-3">
              <div className="flex gap-2 items-center">
                <input ref={fileInputRef} type="file" accept=".csv,.xlsx,.xls" className="hidden" onChange={handleFileUpload} />
                <Button variant="secondary" onClick={() => fileInputRef.current?.click()} disabled={batchImportMutation.isPending}>
                  <Upload className="w-4 h-4 mr-1" />
                  {batchImportMutation.isPending ? '导入中...' : '选择文件导入'}
                </Button>
                <Button variant="secondary" onClick={() => syncFromAttendanceMutation.mutate(month)} disabled={syncFromAttendanceMutation.isPending}>
                  {syncFromAttendanceMutation.isPending ? '同步中...' : '从考勤同步'}
                </Button>
              </div>
              <div className="text-xs text-gray-500 mt-2">
                文件格式：姓名,工作日加班(h),休息日加班(h),节假日加班(h),月份(可选) — 或直接从考勤记录同步加班工时
              </div>
            </div>

            {previewData.length > 0 && (
              <div className="border-t pt-3 space-y-3">
                <div className="text-xs font-medium text-gray-700">预览（{previewData.length}条）</div>
                <div className="overflow-x-auto">
                  <table className="w-full text-sm">
                    <thead>
                      <tr className="border-b text-xs text-gray-500">
                        <th className="py-2 text-left">员工</th>
                        <th className="py-2 text-left">部门</th>
                        <th className="py-2 text-right">工作日(h)</th>
                        <th className="py-2 text-right">休息日(h)</th>
                        <th className="py-2 text-right">节假日(h)</th>
                        <th className="py-2 text-left">月份</th>
                      </tr>
                    </thead>
                    <tbody>
                      {previewData.map((d, i) => (
                        <tr key={i} className="border-b last:border-0">
                          <td className="py-2">{d.employeeName}{d.idCardNumber ? <span className="ml-1 text-xs text-gray-400 font-mono">{d.idCardNumber}</span> : ''}</td>
                          <td className="py-2 text-gray-500">{d.department}</td>
                          <td className="py-2 text-right">{d.weekdayHours}</td>
                          <td className="py-2 text-right">{d.weekendHours}</td>
                          <td className="py-2 text-right">{d.holidayHours}</td>
                          <td className="py-2 text-gray-500">{d.month}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
                <div className="flex gap-2">
                  <Button onClick={confirmImport} disabled={batchImportMutation.isPending}>
                    {batchImportMutation.isPending ? '保存中...' : '确认导入'}
                  </Button>
                  <Button variant="secondary" onClick={() => setPreviewData([])}>取消</Button>
                </div>
              </div>
            )}

            <div className="flex justify-between border-t pt-3">
              <Button variant="secondary" onClick={() => setStep(1)}>← 上一步</Button>
              <Button onClick={() => setStep(3)}>下一步：查看加班记录 →</Button>
            </div>
          </div>
        </Card>
      )}

      {/* Step 3: 查看加班记录 */}
      {step === 3 && (
        <Card>
          <div className="flex items-center justify-between mb-3">
            <h2 className="text-xs font-medium flex items-center gap-2"><FileText className="w-4 h-4" />加班记录（{month}）</h2>
            <div className="flex items-center gap-2">
              <Input type="month" value={month} onChange={(e) => setMonth(e.target.value)} className="w-32" />
              <Button variant="secondary" size="sm" onClick={() => refetch()}>刷新</Button>
              <Button size="sm" onClick={() => setShowAddForm(!showAddForm)}><Plus className="w-3.5 h-3.5 mr-1" />手动添加</Button>
            </div>
          </div>
          {showAddForm && (
            <div className="border rounded-lg p-3 mb-3 bg-gray-50 space-y-3">
              <div className="grid md:grid-cols-4 gap-3">
                <div>
                  <Label>员工</Label>
                  <select
                    className="w-full h-9 rounded-md border border-gray-200 bg-white px-3 text-sm"
                    value={addForm.employeeId}
                    onChange={(e) => setAddForm({ ...addForm, employeeId: e.target.value })}
                  >
                    <option value="">请选择员工</option>
                    {employees?.items?.map((emp: any) => (
                      <option key={emp.id} value={emp.id}>{emp.name} - {emp.department}</option>
                    ))}
                  </select>
                </div>
                <div>
                  <Label>工作日加班(h)</Label>
                  <Input type="number" step="0.5" min="0" value={addForm.weekdayHours} onChange={(e) => setAddForm({ ...addForm, weekdayHours: Number(e.target.value) })} />
                </div>
                <div>
                  <Label>休息日加班(h)</Label>
                  <Input type="number" step="0.5" min="0" value={addForm.weekendHours} onChange={(e) => setAddForm({ ...addForm, weekendHours: Number(e.target.value) })} />
                </div>
                <div>
                  <Label>节假日加班(h)</Label>
                  <Input type="number" step="0.5" min="0" value={addForm.holidayHours} onChange={(e) => setAddForm({ ...addForm, holidayHours: Number(e.target.value) })} />
                </div>
              </div>
              <div className="flex gap-2">
                <Button size="sm" onClick={() => {
                  if (!addForm.employeeId) return toast.error('请选择员工')
                  const emp = employees?.items?.find((e: any) => e.id === addForm.employeeId)
                  let monthlyWage = 0
                  try { monthlyWage = Number((emp as any)?.monthlySalary) || 0 } catch {}
                  addOvertimeMutation.mutate({ ...addForm, month, monthlyWage: monthlyWage || 1 })
                }} disabled={addOvertimeMutation.isPending || !addForm.employeeId}>
                  {addOvertimeMutation.isPending ? '保存中...' : '保存'}
                </Button>
                <Button variant="secondary" size="sm" onClick={() => setShowAddForm(false)}>取消</Button>
              </div>
            </div>
          )}
          {!overtimeRecords || overtimeRecords.length === 0 ? (
            <div className="text-center py-8 text-gray-500">该月暂无加班记录，请先导入考勤数据</div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b text-xs text-gray-500">
                    <th className="py-2 text-left">员工</th>
                    <th className="py-2 text-left">部门</th>
                    <th className="py-2 text-right">工作日(h)</th>
                    <th className="py-2 text-right">休息日(h)</th>
                    <th className="py-2 text-right">节假日(h)</th>
                    <th className="py-2 text-right">加班费</th>
                    <th className="py-2 text-center">状态</th>
                    <th className="py-2 text-center">操作</th>
                  </tr>
                </thead>
                <tbody>
                  {overtimeRecords.map((r: any) => (
                    <tr key={r.id} className="border-b last:border-0 hover:bg-gray-50">
                      <td className="py-2">
                        <div className="flex flex-col gap-0.5">
                          <span>{r.employee?.name}</span>
                          {r.employee?.idCardNumber && <span className="text-gray-400 text-[11px] font-mono">{r.employee.idCardNumber}</span>}
                        </div>
                      </td>
                      <td className="py-2 text-gray-500">{r.employee?.department}</td>
                      {editingId === r.id ? (
                        <>
                          <td className="py-1 text-right">
                            <input
                              type="number"
                              className="w-16 text-right border rounded px-1 py-0.5 text-xs"
                              value={editForm.weekdayHours}
                              onChange={(e) => setEditForm({ ...editForm, weekdayHours: Number(e.target.value) })}
                              min="0"
                              step="0.5"
                            />
                          </td>
                          <td className="py-1 text-right">
                            <input
                              type="number"
                              className="w-16 text-right border rounded px-1 py-0.5 text-xs"
                              value={editForm.weekendHours}
                              onChange={(e) => setEditForm({ ...editForm, weekendHours: Number(e.target.value) })}
                              min="0"
                              step="0.5"
                            />
                          </td>
                          <td className="py-1 text-right">
                            <input
                              type="number"
                              className="w-16 text-right border rounded px-1 py-0.5 text-xs"
                              value={editForm.holidayHours}
                              onChange={(e) => setEditForm({ ...editForm, holidayHours: Number(e.target.value) })}
                              min="0"
                              step="0.5"
                            />
                          </td>
                        </>
                      ) : (
                        <>
                          <td className="py-2 text-right cursor-pointer hover:text-blue-600" onClick={() => startEdit(r)}>{r.weekdayHours || '-'}</td>
                          <td className="py-2 text-right cursor-pointer hover:text-blue-600" onClick={() => startEdit(r)}>{r.weekendHours || '-'}</td>
                          <td className="py-2 text-right cursor-pointer hover:text-blue-600" onClick={() => startEdit(r)}>{r.holidayHours || '-'}</td>
                        </>
                      )}
                      <td className="py-2 text-right font-medium text-gray-700">
                        {r.totalPay > 0 ? `¥${fmt(r.totalPay)}` : <span className="text-gray-500">待计算</span>}
                      </td>
                      <td className="py-2 text-center">
                        {r.batchId ? (
                          <span className="px-2 py-0.5 rounded bg-green-50 text-safe text-xs">已入批次</span>
                        ) : (
                          <span className="px-2 py-0.5 rounded bg-amber-50 text-amber-600 text-xs">未入批次</span>
                        )}
                      </td>
                      <td className="py-2 text-center">
                        {editingId === r.id ? (
                          <div className="flex items-center justify-center gap-1">
                            <button
                              onClick={saveEdit}
                              disabled={updateOvertimeMutation.isPending}
                              className="text-safe hover:text-green-700 disabled:opacity-50"
                              title="保存"
                            >
                              <Check className="w-4 h-4" />
                            </button>
                            <button
                              onClick={() => setEditingId(null)}
                              className="text-gray-500 hover:text-gray-600"
                              title="取消"
                            >
                              <X className="w-4 h-4" />
                            </button>
                          </div>
                        ) : (
                          !r.batchId && (
                            <button
                              onClick={() => startEdit(r)}
                              className="text-gray-500 hover:text-blue-600"
                              title="编辑"
                            >
                              <FileText className="w-4 h-4" />
                            </button>
                          )
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
          <div className="flex justify-between border-t pt-3 mt-3">
            <Button variant="secondary" onClick={() => setStep(2)}>← 上一步</Button>
            <div className="text-xs text-gray-500 flex items-center gap-1">
              <Info className="w-3.5 h-3.5" />
              加班费金额在发薪批次中「导入加班费」时自动计算
            </div>
          </div>
        </Card>
      )}
    </div>
  )
}
