import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Input } from '../ui/input';
import { Textarea } from '../ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '../ui/dialog';
import { Progress } from '../ui/progress';
import { Employee } from '../../types/user-management';
import { ScheduleEditor, Schedule, ScheduleShift } from './ScheduleEditor';
import {
  Users,
  Plus,
  Eye,
  Search,
  Filter,
  Download,
  Upload,
  Clock,
  Calendar,
  TrendingUp,
  Award,
  Target,
  BarChart3,
  Phone,
  Mail,
  MapPin,
  Briefcase,
  Shield,
  ChevronLeft,
  ChevronRight,
  Copy,
  Save,
  CheckCircle2,
  AlertCircle,
  Star,
  Trophy,
  Activity,
  User,
  Edit, // Icon for editing work hours
  Trash2, // Icon for deleting work hours
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  LineChart,
  Line,
  PieChart,
  Pie,
  Cell,
  RadarChart,
  PolarGrid,
  PolarAngleAxis,
  PolarRadiusAxis,
  Radar,
} from 'recharts';

interface OperationPerformanceProps {
  activePath?: string;
}

interface Staff extends Employee {
  joinDate: string;
  status: '在职' | '休假' | '离职';
  avatar?: string;
}

interface WorkHour {
  id: string;
  staffId: string;
  staffName: string;
  taskId?: string;
  taskName?: string;
  date: string;
  startTime: string;
  endTime: string;
  totalHours: number;
  workType: string;
  fieldName: string;
  area: number;
  notes: string;
  status: '待审核' | '已审核' | '已驳回';
  recordType: '自动记录' | '手动录入';
  createdAt: string;
}

interface Performance {
  staffId: string;
  staffName: string;
  team: string;
  period: string;
  totalHours: number;
  completedTasks: number;
  completedArea: number;
  efficiency: number;
  ranking: number;
  score: number;
  trend: '上升' | '下降' | '持平';
}

// Schedule and ScheduleShift types are now imported from ScheduleEditor

export function OperationPerformance({ activePath }: OperationPerformanceProps) {
  const [activeTab, setActiveTab] = useState('staff');
  const [showHourDialog, setShowHourDialog] = useState(false);
  const [showScheduleEditor, setShowScheduleEditor] = useState(false);
  const [showCopyDialog, setShowCopyDialog] = useState(false);
  const [selectedHour, setSelectedHour] = useState<WorkHour | null>(null);
  const [selectedSchedule, setSelectedSchedule] = useState<Schedule | null>(null);
  const [filterTeam, setFilterTeam] = useState<string>('all');
  const [filterStatus, setFilterStatus] = useState<string>('all');
  
  // 绩效统计筛选条件
  const [perfTimeRange, setPerfTimeRange] = useState<'week' | 'month' | 'quarter' | 'year'>('month');
  const [perfViewType, setPerfViewType] = useState<'individual' | 'team'>('individual');
  const [perfPeriod, setPerfPeriod] = useState(new Date().toISOString().split('T')[0]);
  
  // 日期区间筛选
  const [perfStartDate, setPerfStartDate] = useState(() => {
    const date = new Date();
    date.setDate(1); // 本月第一天
    return date.toISOString().split('T')[0];
  });
  const [perfEndDate, setPerfEndDate] = useState(new Date().toISOString().split('T')[0]);
  
  // 工时记录表单数据
  const [hourFormData, setHourFormData] = useState({
    staffId: '',
    staffName: '',
    taskId: '',
    taskName: '',
    date: new Date().toISOString().split('T')[0],
    startTime: '08:00',
    endTime: '17:00',
    workType: '',
    fieldName: '',
    area: 0,
    notes: '',
  });

  // 根据路径自动切换Tab
  useEffect(() => {
    if (activePath) {
      if (activePath.includes('/staff')) {
        setActiveTab('staff');
      } else if (activePath.includes('/hours')) {
        setActiveTab('hours');
      } else if (activePath.includes('/statistics')) {
        setActiveTab('statistics');
      } else if (activePath.includes('/schedule')) {
        setActiveTab('schedule');
      }
    }
  }, [activePath]);

  // 员工数据
  const [staffList, setStaffList] = useState<Staff[]>([]);

  // 加载员工数据
  const loadStaffData = () => {
    const employeeData = localStorage.getItem('smart_agriculture_employees');
    if (employeeData) {
      try {
        const employees: Employee[] = JSON.parse(employeeData);
        // 转换为Staff格式
        const staffData: Staff[] = employees
          .filter(emp => emp.status === 'active') // 只显示在职员工
          .map(emp => ({
            ...emp,
            joinDate: emp.createdAt ? emp.createdAt.split('T')[0] : new Date().toISOString().split('T')[0], // 使用创建时间作为入职时间
            status: '在职' as const,
            avatar: undefined,
          }));
        setStaffList(staffData);
        console.log('加载员工数据:', staffData.length, '条');
      } catch (error) {
        console.error('加载员工数据失败:', error);
        toast.error('加载员工数据失败');
      }
    } else {
      console.log('未找到员工数据');
      setStaffList([]);
    }
  };

  useEffect(() => {
    loadStaffData();
  }, []);

  // 模拟工时记录数据
  const [workHours, setWorkHours] = useState<WorkHour[]>([
    {
      id: 'hour-1',
      staffId: 'staff-1',
      staffName: '张三',
      taskId: 'task-1',
      taskName: '东区1号地水稻播种',
      date: '2024-03-15',
      startTime: '08:00',
      endTime: '12:00',
      totalHours: 4,
      workType: '播种',
      fieldName: '东区1号地',
      area: 50.5,
      notes: '完成播种作业',
      status: '已审核',
      recordType: '自动记录',
      createdAt: '2024-03-15 12:30',
    },
    {
      id: 'hour-2',
      staffId: 'staff-2',
      staffName: '李四',
      taskId: 'task-2',
      taskName: '西区2号地施基肥',
      date: '2024-03-18',
      startTime: '09:00',
      endTime: '13:00',
      totalHours: 4,
      workType: '施肥',
      fieldName: '西区2号地',
      area: 45.2,
      notes: '施肥作业顺利',
      status: '已审核',
      recordType: '自动记录',
      createdAt: '2024-03-18 13:30',
    },
    {
      id: 'hour-3',
      staffId: 'staff-3',
      staffName: '王五',
      date: '2024-03-20',
      startTime: '06:00',
      endTime: '10:00',
      totalHours: 4,
      workType: '病虫害防治',
      fieldName: '南区3号地',
      area: 60.3,
      notes: '喷洒农药',
      status: '待审核',
      recordType: '手动录入',
      createdAt: '2024-03-20 11:00',
    },
  ]);

  // 样例绩效数据（用于演示和空数据时展示）
  const samplePerformanceData: Performance[] = [
    {
      staffId: 'sample-1',
      staffName: '张三',
      team: '第一作业组',
      period: '2024年3月',
      totalHours: 160,
      completedTasks: 12,
      completedArea: 500,
      efficiency: 3.125,
      ranking: 1,
      score: 95,
      trend: '上升',
    },
    {
      staffId: 'sample-2',
      staffName: '李四',
      team: '第二作业组',
      period: '2024年3月',
      totalHours: 152,
      completedTasks: 10,
      completedArea: 450,
      efficiency: 2.96,
      ranking: 2,
      score: 92,
      trend: '上升',
    },
    {
      staffId: 'sample-3',
      staffName: '王五',
      team: '第三作业组',
      period: '2024年3月',
      totalHours: 148,
      completedTasks: 8,
      completedArea: 400,
      efficiency: 2.70,
      ranking: 3,
      score: 88,
      trend: '持平',
    },
    {
      staffId: 'sample-4',
      staffName: '赵六',
      team: '第一作业组',
      period: '2024年3月',
      totalHours: 140,
      completedTasks: 9,
      completedArea: 350,
      efficiency: 2.50,
      ranking: 4,
      score: 85,
      trend: '下降',
    },
    {
      staffId: 'sample-5',
      staffName: '孙七',
      team: '第二作业组',
      period: '2024年3月',
      totalHours: 135,
      completedTasks: 7,
      completedArea: 320,
      efficiency: 2.37,
      ranking: 5,
      score: 82,
      trend: '持平',
    },
    {
      staffId: 'sample-6',
      staffName: '周八',
      team: '第三作业组',
      period: '2024年3月',
      totalHours: 128,
      completedTasks: 6,
      completedArea: 280,
      efficiency: 2.19,
      ranking: 6,
      score: 78,
      trend: '下降',
    },
  ];

  // 模拟排班数据
  const [schedules, setSchedules] = useState<Schedule[]>([
    {
      id: 'schedule-1',
      name: '2024年3月第3周排班',
      type: 'week',
      startDate: '2024-03-18',
      endDate: '2024-03-24',
      status: '已发布',
      createdAt: '2024-03-15',
      shifts: [
        {
          staffId: 'staff-1',
          staffName: '张三',
          team: '第一作业组',
          date: '2024-03-18',
          shift: '早班',
          workHours: '08:00-16:00',
          task: '播种作业',
        },
        {
          staffId: 'staff-2',
          staffName: '李四',
          team: '第二作业组',
          date: '2024-03-18',
          shift: '早班',
          workHours: '08:00-16:00',
          task: '施肥作业',
        },
      ],
    },
  ]);



  // 加载工时记录数据
  const loadWorkHours = () => {
    const hourData = localStorage.getItem('smart_agriculture_work_hours');
    if (hourData) {
      try {
        const hours: WorkHour[] = JSON.parse(hourData);
        setWorkHours(hours);
        console.log('加载工时记录:', hours.length, '条');
      } catch (error) {
        console.error('加载工时记录失败:', error);
        toast.error('加载工时记录失败');
      }
    }
  };

  useEffect(() => {
    loadWorkHours();
  }, []);

  const handleCreateHour = () => {
    setSelectedHour(null);
    setHourFormData({
      staffId: '',
      staffName: '',
      taskId: '',
      taskName: '',
      date: new Date().toISOString().split('T')[0],
      startTime: '08:00',
      endTime: '17:00',
      workType: '',
      fieldName: '',
      area: 0,
      notes: '',
    });
    setShowHourDialog(true);
  };

  const handleEditHour = (hour: WorkHour) => {
    setSelectedHour(hour);
    setHourFormData({
      staffId: hour.staffId,
      staffName: hour.staffName,
      taskId: hour.taskId || '',
      taskName: hour.taskName || '',
      date: hour.date,
      startTime: hour.startTime,
      endTime: hour.endTime,
      workType: hour.workType,
      fieldName: hour.fieldName,
      area: hour.area,
      notes: hour.notes,
    });
    setShowHourDialog(true);
  };

  const handleSaveHour = () => {
    // 验证必填项
    if (!hourFormData.staffId || !hourFormData.workType || !hourFormData.date || !hourFormData.startTime || !hourFormData.endTime) {
      toast.error('请填写所有必填项（员工、工作类型、日期、起止时间）');
      return;
    }

    // 验证时间有效性
    const start = new Date(`${hourFormData.date} ${hourFormData.startTime}`);
    const end = new Date(`${hourFormData.date} ${hourFormData.endTime}`);
    if (end <= start) {
      toast.error('结束时间必须晚于开始时间');
      return;
    }

    // 计算总工时
    const totalHours = (end.getTime() - start.getTime()) / (1000 * 60 * 60);

    // 读取现有工时数据
    const hourData = localStorage.getItem('smart_agriculture_work_hours');
    let hours: WorkHour[] = hourData ? JSON.parse(hourData) : [];

    if (selectedHour) {
      // 编辑模式：更新现有工时记录
      hours = hours.map(h =>
        h.id === selectedHour.id
          ? {
              ...h,
              staffId: hourFormData.staffId,
              staffName: hourFormData.staffName,
              taskId: hourFormData.taskId || undefined,
              taskName: hourFormData.taskName || undefined,
              date: hourFormData.date,
              startTime: hourFormData.startTime,
              endTime: hourFormData.endTime,
              totalHours: parseFloat(totalHours.toFixed(2)),
              workType: hourFormData.workType,
              fieldName: hourFormData.fieldName,
              area: hourFormData.area,
              notes: hourFormData.notes,
              status: '待审核' as const,
            }
          : h
      );
      toast.success('工时记录更新成功');
    } else {
      // 新增模式：创建新工时记录
      const newHour: WorkHour = {
        id: `hour-${Date.now()}`,
        staffId: hourFormData.staffId,
        staffName: hourFormData.staffName,
        taskId: hourFormData.taskId || undefined,
        taskName: hourFormData.taskName || undefined,
        date: hourFormData.date,
        startTime: hourFormData.startTime,
        endTime: hourFormData.endTime,
        totalHours: parseFloat(totalHours.toFixed(2)),
        workType: hourFormData.workType,
        fieldName: hourFormData.fieldName,
        area: hourFormData.area,
        notes: hourFormData.notes,
        status: '待审核',
        recordType: '手动录入',
        createdAt: new Date().toISOString(),
      };
      hours.unshift(newHour);
      toast.success('工时记录添加成功');
    }

    // 保存到 localStorage
    localStorage.setItem('smart_agriculture_work_hours', JSON.stringify(hours));

    // 重新加载工时列表
    setWorkHours(hours);

    // 关闭对话框
    setShowHourDialog(false);
  };

  const handleDeleteHour = (id: string) => {
    if (!confirm('确定要删除该工时记录吗？此操作不可恢复。')) return;

    const hourData = localStorage.getItem('smart_agriculture_work_hours');
    if (hourData) {
      let hours: WorkHour[] = JSON.parse(hourData);
      hours = hours.filter(h => h.id !== id);
      localStorage.setItem('smart_agriculture_work_hours', JSON.stringify(hours));
      setWorkHours(hours);
      toast.success('工时记录已删除');
    }
  };

  const handleApproveHour = (id: string) => {
    const hourData = localStorage.getItem('smart_agriculture_work_hours');
    if (hourData) {
      let hours: WorkHour[] = JSON.parse(hourData);
      hours = hours.map(h =>
        h.id === id ? { ...h, status: '已审核' as const } : h
      );
      localStorage.setItem('smart_agriculture_work_hours', JSON.stringify(hours));
      setWorkHours(hours);
      toast.success('工时已审核通过');
    }
  };

  const handleRejectHour = (id: string) => {
    const hourData = localStorage.getItem('smart_agriculture_work_hours');
    if (hourData) {
      let hours: WorkHour[] = JSON.parse(hourData);
      hours = hours.map(h =>
        h.id === id ? { ...h, status: '已驳回' as const } : h
      );
      localStorage.setItem('smart_agriculture_work_hours', JSON.stringify(hours));
      setWorkHours(hours);
      toast.success('工时已驳回');
    }
  };

  // 从任务执行记录中同步工时
  const syncWorkHoursFromTasks = () => {
    const tasksData = localStorage.getItem('smart_agriculture_operation_tasks');
    if (!tasksData) {
      toast.info('暂无任务执行记录');
      return;
    }

    try {
      const tasks = JSON.parse(tasksData);
      const executedTasks = tasks.filter((t: any) =>
        t.status === '已完成' &&
        t.executor &&
        t.actualStartTime &&
        t.actualEndTime
      );

      if (executedTasks.length === 0) {
        toast.info('暂无已完成的任务可同步');
        return;
      }

      const hourData = localStorage.getItem('smart_agriculture_work_hours');
      let hours: WorkHour[] = hourData ? JSON.parse(hourData) : [];
      
      // 记录已存在的任务ID
      const existingTaskIds = new Set(hours.map(h => h.taskId).filter(Boolean));
      
      let syncCount = 0;
      executedTasks.forEach((task: any) => {
        // 跳过已同步的任务
        if (existingTaskIds.has(task.id)) return;

        const start = new Date(task.actualStartTime);
        const end = new Date(task.actualEndTime);
        const totalHours = (end.getTime() - start.getTime()) / (1000 * 60 * 60);

        const newHour: WorkHour = {
          id: `hour-sync-${task.id}-${Date.now()}`,
          staffId: task.executorId || 'unknown',
          staffName: task.executor,
          taskId: task.id,
          taskName: task.taskName,
          date: task.actualStartTime.split('T')[0],
          startTime: start.toTimeString().slice(0, 5),
          endTime: end.toTimeString().slice(0, 5),
          totalHours: parseFloat(totalHours.toFixed(2)),
          workType: task.operationType || '其他',
          fieldName: task.fieldName || '',
          area: task.area || 0,
          notes: `从任务"${task.taskName}"自动同步`,
          status: '已审核',
          recordType: '自动记录',
          createdAt: new Date().toISOString(),
        };

        hours.unshift(newHour);
        syncCount++;
      });

      if (syncCount > 0) {
        localStorage.setItem('smart_agriculture_work_hours', JSON.stringify(hours));
        setWorkHours(hours);
        toast.success(`成功同步 ${syncCount} 条工时记录`);
      } else {
        toast.info('所有任务工时已同步，无新增记录');
      }
    } catch (error) {
      console.error('同步工时失败:', error);
      toast.error('同步工时失败');
    }
  };

  const filteredStaff = staffList.filter(s => {
    if (filterTeam !== 'all' && s.team !== filterTeam) return false;
    if (filterStatus !== 'all' && s.status !== filterStatus) return false;
    return true;
  });

  // 统计数据
  const totalStaff = staffList.length;
  const activeStaff = staffList.filter(s => s.status === '在职').length;
  const totalHours = workHours.reduce((sum, h) => sum + h.totalHours, 0);
  const pendingHours = workHours.filter(h => h.status === '待审核').length;

  // 计算绩效统计的时间范围（使用日期区间）
  const getPerfDateRange = () => {
    const start = new Date(perfStartDate);
    const end = new Date(perfEndDate);
    return { start, end };
  };

  // 筛选时间范围内的工时记录
  const filterPerfWorkHours = () => {
    const { start, end } = getPerfDateRange();
    return workHours.filter(hour => {
      if (hour.status !== '已审核') return false; // 只统计已审核的工时
      const hourDate = new Date(hour.date);
      return hourDate >= start && hourDate <= end;
    });
  };

  // 动态计算个人绩效
  const calculateIndividualPerformance = (): Performance[] => {
    const filteredHours = filterPerfWorkHours();
    const staffPerfMap = new Map<string, {
      staffName: string;
      team: string;
      totalHours: number;
      completedArea: number;
      taskIds: Set<string>;
    }>();

    // 聚合工时数据
    filteredHours.forEach(hour => {
      const existing = staffPerfMap.get(hour.staffName) || {
        staffName: hour.staffName,
        team: staffList.find(s => s.name === hour.staffName)?.team || '未分配',
        totalHours: 0,
        completedArea: 0,
        taskIds: new Set<string>(),
      };

      existing.totalHours += hour.totalHours;
      existing.completedArea += hour.area;
      if (hour.taskId) {
        existing.taskIds.add(hour.taskId);
      }

      staffPerfMap.set(hour.staffName, existing);
    });

    // 转换为Performance对象并计算排名
    const performances = Array.from(staffPerfMap.values()).map((data, index) => {
      const efficiencyValue = data.totalHours > 0 ? Number((data.completedArea * (1.0 / data.totalHours)).toFixed(2)) : 0;
      return {
        staffId: `staff-${index}`,
        staffName: data.staffName,
        team: data.team,
        period: formatPeriodLabel(),
        totalHours: data.totalHours,
        completedTasks: data.taskIds.size,
        completedArea: data.completedArea,
        efficiency: efficiencyValue,
        ranking: 0,
        score: 0,
        trend: '持平' as const,
      };
    });

    // 按效率排序并分配排名
    performances.sort((a, b) => b.efficiency - a.efficiency);
    performances.forEach((perf, index) => {
      perf.ranking = index + 1;
      // 简化的评分计算：基于效率和工作量
      perf.score = Math.min(100, Math.round(perf.efficiency * 20 + perf.completedArea * 0.1));
    });

    return performances;
  };

  // 动态计算班组绩效
  const calculateTeamPerformance = (): Performance[] => {
    const filteredHours = filterPerfWorkHours();
    const teamPerfMap = new Map<string, {
      team: string;
      totalHours: number;
      completedArea: number;
      taskIds: Set<string>;
      memberCount: number;
    }>();

    // 聚合工时数据
    filteredHours.forEach(hour => {
      const team = staffList.find(s => s.name === hour.staffName)?.team || '未分配';
      const existing = teamPerfMap.get(team) || {
        team,
        totalHours: 0,
        completedArea: 0,
        taskIds: new Set<string>(),
        memberCount: 0,
      };

      existing.totalHours += hour.totalHours;
      existing.completedArea += hour.area;
      if (hour.taskId) {
        existing.taskIds.add(hour.taskId);
      }

      teamPerfMap.set(team, existing);
    });

    // 计算每个班组的成员数量
    teamPerfMap.forEach((data, team) => {
      data.memberCount = staffList.filter(s => s.team === team && s.status === '在职').length;
    });

    // 转换为Performance对象
    const performances = Array.from(teamPerfMap.values()).map((data, index) => {
      const efficiencyValue = data.totalHours > 0 ? Number((data.completedArea * (1.0 / data.totalHours)).toFixed(2)) : 0;
      return {
        staffId: `team-${index}`,
        staffName: data.team,
        team: data.team,
        period: formatPeriodLabel(),
        totalHours: data.totalHours,
        completedTasks: data.taskIds.size,
        completedArea: data.completedArea,
        efficiency: efficiencyValue,
        ranking: 0,
        score: 0,
        trend: '持平' as const,
      };
    });

    // 按效率排序并分配排名
    performances.sort((a, b) => b.efficiency - a.efficiency);
    performances.forEach((perf, index) => {
      perf.ranking = index + 1;
      perf.score = Math.min(100, Math.round(perf.efficiency * 20 + perf.completedArea * 0.1));
    });

    return performances;
  };

  // 格式化周期标签
  const formatPeriodLabel = () => {
    const { start, end } = getPerfDateRange();
    const options: Intl.DateTimeFormatOptions = { month: 'long', day: 'numeric' };
    
    switch (perfTimeRange) {
      case 'week':
        return `${start.toLocaleDateString('zh-CN', options)} - ${end.toLocaleDateString('zh-CN', options)}`;
      case 'quarter':
        const quarter = Math.floor(start.getMonth() / 3) + 1;
        return `${start.getFullYear()}年第${quarter}季度`;
      case 'year':
        return `${start.getFullYear()}年`;
      default:
        return `${start.getFullYear()}年${start.getMonth() + 1}月`;
    }
  };

  // 获取当前展示的绩效数据（如果为空则使用样例数据）
  const calculatedPerfData = perfViewType === 'individual' 
    ? calculateIndividualPerformance()
    : calculateTeamPerformance();
  
  const currentPerfData = calculatedPerfData.length > 0 ? calculatedPerfData : samplePerformanceData;

  const { start: perfStart, end: perfEnd } = getPerfDateRange();

  // 绩效图表数据
  const efficiencyChartData = currentPerfData.map(p => {
    return {
      name: p.staffName,
      效率: p.efficiency,
      工作量: p.completedArea,
      工时: p.totalHours,
    };
  });

  // 班组综合对比雷达图数据
  const teamRadarData = perfViewType === 'team' ? currentPerfData.map(p => {
    const normalizedArea = p.completedArea * 0.1;
    const normalizedEfficiency = p.efficiency * 10;
    const normalizedTasks = p.completedTasks * 5;
    const normalizedHours = p.totalHours * 0.5;
    return {
      班组: p.team,
      工作量: Math.min(100, normalizedArea),
      效率: Math.min(100, normalizedEfficiency),
      任务数: Math.min(100, normalizedTasks),
      工时: Math.min(100, normalizedHours),
    };
  }) : [];

  const trendChartData = [
    { month: '1月', 张三: 2.8, 李四: 2.5, 王五: 2.4, 赵六: 2.6 },
    { month: '2月', 张三: 2.9, 李四: 2.7, 王五: 2.5, 赵六: 2.7 },
    { month: '3月', 张三: 3.125, 李四: 2.96, 王五: 2.70, 赵六: 2.50 },
  ];

  const COLORS = ['#22c55e', '#3b82f6', '#a855f7', '#f97316', '#ec4899', '#f59e0b'];

  // 排班管理函数
  const loadSchedules = () => {
    const scheduleData = localStorage.getItem('smart_agriculture_schedules');
    if (scheduleData) {
      try {
        const loadedSchedules: Schedule[] = JSON.parse(scheduleData);
        setSchedules(loadedSchedules);
      } catch (error) {
        console.error('加载排班数据失败:', error);
        toast.error('加载排班数据失败');
      }
    }
  };

  useEffect(() => {
    loadSchedules();
  }, []);

  const handleCreateSchedule = () => {
    setSelectedSchedule(null);
    setShowScheduleEditor(true);
  };

  const handleEditSchedule = (schedule: Schedule) => {
    setSelectedSchedule(schedule);
    setShowScheduleEditor(true);
  };

  const handleDeleteSchedule = (id: string) => {
    if (!confirm('确定要删除该排班吗？此操作不可恢复。')) return;
    
    const scheduleData = localStorage.getItem('smart_agriculture_schedules');
    if (scheduleData) {
      let loadedSchedules: Schedule[] = JSON.parse(scheduleData);
      loadedSchedules = loadedSchedules.filter(s => s.id !== id);
      localStorage.setItem('smart_agriculture_schedules', JSON.stringify(loadedSchedules));
      setSchedules(loadedSchedules);
      toast.success('排班已删除');
    }
  };

  const handleCopySchedule = (schedule: Schedule) => {
    // 生成副本名称
    const newName = `${schedule.name}（副本）`;
    
    // 计算日期范围
    const today = new Date();
    const startDate = today.toISOString().split('T')[0];
    
    const daysDiff = new Date(schedule.endDate).getTime() - new Date(schedule.startDate).getTime();
    const endDay = new Date(today);
    endDay.setTime(endDay.getTime() + daysDiff);
    const endDate = endDay.toISOString().split('T')[0];
    
    // 计算日期偏移量，用于调整所有班次的日期
    const originalStartDate = new Date(schedule.startDate);
    const newStartDate = new Date(startDate);
    const dateOffset = newStartDate.getTime() - originalStartDate.getTime();
    
    // 创建副本数据，调整所有班次的日期
    const copiedSchedule: Schedule = {
      id: `schedule-${Date.now()}`,
      name: newName,
      type: schedule.type,
      startDate,
      endDate,
      status: '草稿',
      createdAt: new Date().toISOString(),
      shifts: schedule.shifts.map(shift => {
        // 根据原始日期和偏移量计算新日期
        const originalDate = new Date(shift.date);
        const newDate = new Date(originalDate.getTime() + dateOffset);
        return {
          ...shift,
          date: newDate.toISOString().split('T')[0],
        };
      }),
    };
    
    // 打开编辑器，让用户修改排班名称和其他信息
    setSelectedSchedule(copiedSchedule);
    setShowScheduleEditor(true);
    toast.success('排班已复制，请修改名称后保存');
  };

  const handlePublishSchedule = (id: string) => {
    const scheduleData = localStorage.getItem('smart_agriculture_schedules');
    if (scheduleData) {
      let loadedSchedules: Schedule[] = JSON.parse(scheduleData);
      loadedSchedules = loadedSchedules.map(s =>
        s.id === id ? { ...s, status: '已发布' as const } : s
      );
      localStorage.setItem('smart_agriculture_schedules', JSON.stringify(loadedSchedules));
      setSchedules(loadedSchedules);
      toast.success('排班已发布');
    }
  };

  const handleSaveSchedule = (schedule: Schedule) => {
    const scheduleData = localStorage.getItem('smart_agriculture_schedules');
    let loadedSchedules: Schedule[] = scheduleData ? JSON.parse(scheduleData) : [];

    if (selectedSchedule) {
      // 编辑模式
      loadedSchedules = loadedSchedules.map(s =>
        s.id === selectedSchedule.id ? schedule : s
      );
      toast.success('排班更新成功');
    } else {
      // 新建模式
      loadedSchedules.unshift(schedule);
      toast.success('排班创建成功');
    }

    localStorage.setItem('smart_agriculture_schedules', JSON.stringify(loadedSchedules));
    setSchedules(loadedSchedules);
    setShowScheduleEditor(false);
    setSelectedSchedule(null);
  };

  const handleExportSchedule = (schedule: Schedule) => {
    // 生成CSV格式的班表
    let csv = '姓名,班组,日期,班次,工作时间,任务\n';
    schedule.shifts.forEach(shift => {
      csv += `${shift.staffName},${shift.team},${shift.date},${shift.shift},${shift.workHours},${shift.task || '-'}\n`;
    });
    
    // 创建下载链接
    const blob = new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `${schedule.name}_${schedule.startDate}.csv`;
    link.click();
    
    toast.success('班表已导出');
  };



  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-success">
          {activeTab === 'staff' ? '人员管理' : '绩效管理'}
        </h2>
        <p className="text-muted-foreground">
          {activeTab === 'staff' 
            ? '查看员工信息、组织架构与团队配置'
            : '人员管理、工时记录、绩效统计与排班管理'
          }
        </p>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="staff">人员管理</TabsTrigger>
          <TabsTrigger value="hours">工时记录</TabsTrigger>
          <TabsTrigger value="statistics">绩效统计</TabsTrigger>
          <TabsTrigger value="schedule">排班管理</TabsTrigger>
        </TabsList>

        {/* 人员管理 */}
        <TabsContent value="staff" className="space-y-4">
          {/* 说明和快捷操作 */}
          <Card className="p-4 bg-info-muted border-info">
            <div className="flex items-start justify-between">
              <div className="flex items-start gap-2">
                <Users className="w-5 h-5 text-info flex-shrink-0 mt-0.5" />
                <div className="text-sm text-info-muted-foreground">
                  <p className="mb-2">人员管理说明：</p>
                  <ul className="space-y-1 text-xs">
                    <li>• <strong>数据同步</strong>：自动从"系统配置 → 用户管理 → 员工管理"同步员工信息</li>
                    <li>• <strong>只读显示</strong>：本页面仅用于查看员工信息，不支持新增、编辑或删除</li>
                    <li>• <strong>维护入口</strong>：如需维护员工信息，请前往"系统配置 → 用户管理 → 员工管理"</li>
                    <li>• <strong>数据用途</strong>：为任务分配、工时统计、绩效计算提供基础数据源</li>
                    <li>• <strong>在职筛选</strong>：仅显示状态为"在职"的员工</li>
                  </ul>
                </div>
              </div>
              <div className="flex flex-col gap-2">
                <Button 
                  variant="outline" 
                  size="sm"
                  onClick={() => {
                    // 这里应该跳转到配置管理的员工管理
                    toast.info('请前往"系统配置 → 用户管理 → 员工管理"进行人员信息维护');
                  }}
                >
                  <Users className="w-4 h-4 mr-2" />
                  前往员工管理
                </Button>
                <Button 
                  variant="outline" 
                  size="sm"
                  onClick={loadStaffData}
                >
                  <Activity className="w-4 h-4 mr-2" />
                  刷新数据
                </Button>
              </div>
            </div>
          </Card>

          {/* 筛选器 */}
          <Card className="p-4">
            <div className="flex items-center gap-4">
              <Filter className="w-4 h-4 text-muted-foreground" />
              <Select value={filterTeam} onValueChange={setFilterTeam}>
                <SelectTrigger className="w-48">
                  <SelectValue placeholder="选择班组" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部班组</SelectItem>
                  <SelectItem value="第一作业组">第一作业组</SelectItem>
                  <SelectItem value="第二作业组">第二作业组</SelectItem>
                  <SelectItem value="第三作业组">第三作业组</SelectItem>
                </SelectContent>
              </Select>

              <Select value={filterStatus} onValueChange={setFilterStatus}>
                <SelectTrigger className="w-48">
                  <SelectValue placeholder="人员状态" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部状态</SelectItem>
                  <SelectItem value="在职">在职</SelectItem>
                  <SelectItem value="休假">休假</SelectItem>
                  <SelectItem value="离职">离职</SelectItem>
                </SelectContent>
              </Select>

            </div>
          </Card>

          {/* 人员列表 */}
          <div className="grid grid-cols-2 gap-4">
            {filteredStaff.length === 0 ? (
              <Card className="col-span-2 p-12">
                <div className="text-center text-muted-foreground">
                  <Users className="w-16 h-16 mx-auto mb-4 opacity-20" />
                  <p className="mb-2">暂无员工数据</p>
                  <p className="text-sm mb-4">
                    {staffList.length === 0 
                      ? '请先在"系统配置 > 用户管理 > 员工管理"中维护员工信息'
                      : '当前筛选条件下没有匹配的员工'
                    }
                  </p>
                  {staffList.length === 0 && (
                    <Button 
                      variant="outline" 
                      size="sm"
                      onClick={() => {
                        toast.info('请前往"系统配置 > 用户管理 > 员工管理"进行人员信息维护');
                      }}
                    >
                      <Users className="w-4 h-4 mr-2" />
                      前往员工管理
                    </Button>
                  )}
                </div>
              </Card>
            ) : (
              filteredStaff.map(staff => (
                <Card key={staff.id} className="p-6">
                <div className="flex items-start justify-between mb-4">
                  <div className="flex items-start gap-3">
                    <div className="w-12 h-12 bg-success-muted rounded-full flex items-center justify-center">
                      <User className="w-6 h-6 text-success" />
                    </div>
                    <div>
                      <div className="flex items-center gap-2 mb-1">
                        <h4>{staff.name}</h4>
                        <Badge className={
                          staff.status === '在职' ? 'bg-success-muted text-success-muted-foreground' :
                          staff.status === '休假' ? 'bg-warning-muted text-warning-muted-foreground' :
                          'bg-muted text-muted-foreground'
                        }>
                          {staff.status}
                        </Badge>
                      </div>
                      <p className="text-sm text-muted-foreground">
                        {staff.position} | {staff.team}
                      </p>
                    </div>
                  </div>
                </div>

                <div className="space-y-3">
                  <div className="flex items-center gap-2 text-sm">
                    <Phone className="w-4 h-4 text-muted-foreground" />
                    <span>{staff.phone}</span>
                  </div>
                  <div className="flex items-center gap-2 text-sm">
                    <Mail className="w-4 h-4 text-muted-foreground" />
                    <span>{staff.email}</span>
                  </div>
                  <div className="flex items-center gap-2 text-sm">
                    <MapPin className="w-4 h-4 text-muted-foreground" />
                    <span>{staff.address}</span>
                  </div>
                  <div className="flex items-center gap-2 text-sm">
                    <Calendar className="w-4 h-4 text-muted-foreground" />
                    <span>入职日期: {staff.joinDate}</span>
                  </div>
                </div>

                <div className="mt-4">
                  <p className="text-xs text-muted-foreground mb-2">技能标签</p>
                  <div className="flex flex-wrap gap-2">
                    {(staff.skills || []).map(skill => (
                      <Badge key={skill} variant="outline" className="text-xs">
                        {skill}
                      </Badge>
                    ))}
                  </div>
                </div>
              </Card>
              ))
            )}
          </div>
        </TabsContent>

        {/* 工时记录 */}
        <TabsContent value="hours" className="space-y-4">
          {/* 说明 */}
          <Card className="p-4 bg-success-muted border-success">
            <div className="flex items-start gap-2">
              <Clock className="w-5 h-5 text-success flex-shrink-0 mt-0.5" />
              <div className="text-sm text-success-muted-foreground">
                <p className="mb-2">工时记录功能说明：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>自动同步</strong>：与"农事管理 → 任务管理"联动，点击"从任务同步工时"自动导入已完成任务的工时记录</li>
                  <li>• <strong>手动补录</strong>：支持手动录入历史工时或未关联任务的工时记录</li>
                  <li>• <strong>完整CRUD</strong>：提供工时的增加、删除、修改、查询功能，确保数据可维护</li>
                  <li>• <strong>审核流程</strong>：工时状态管理（待审核 → 已审核/已驳回），保证数据质量</li>
                  <li>• <strong>薪酬核算</strong>：准确记录工作时长、作业面积、工作类型，为薪酬计算提供可靠依据</li>
                  <li>• <strong>数据溯源</strong>：区分"自动记录"和"手动录入"，支持追溯工时来源</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 操作栏 */}
          <Card className="p-4">
            <div className="flex items-center justify-between">
              <div className="flex gap-2">
                <Button variant="outline" onClick={syncWorkHoursFromTasks}>
                  <Download className="w-4 h-4 mr-2" />
                  从任务同步工时
                </Button>
                <Button variant="outline" onClick={loadWorkHours}>
                  <Activity className="w-4 h-4 mr-2" />
                  刷新数据
                </Button>
              </div>
              <Button className="bg-green-600 hover:bg-green-700" onClick={handleCreateHour}>
                <Plus className="w-4 h-4 mr-2" />
                手动录入工时
              </Button>
            </div>
          </Card>

          {/* 工时列表 */}
          <div className="space-y-4">
            {workHours.length === 0 ? (
              <Card className="p-12">
                <div className="text-center text-muted-foreground">
                  <Clock className="w-16 h-16 mx-auto mb-4 opacity-20" />
                  <p className="mb-2">暂无工时记录</p>
                  <p className="text-sm mb-4">
                    可以点击"从任务同步工时"自动导入任务工时，或"手动录入工时"补录历史记录
                  </p>
                  <div className="flex gap-2 justify-center">
                    <Button variant="outline" size="sm" onClick={syncWorkHoursFromTasks}>
                      <Download className="w-4 h-4 mr-2" />
                      从任务同步工时
                    </Button>
                    <Button size="sm" className="bg-green-600 hover:bg-green-700" onClick={handleCreateHour}>
                      <Plus className="w-4 h-4 mr-2" />
                      手动录入工时
                    </Button>
                  </div>
                </div>
              </Card>
            ) : (
              workHours.map(hour => {
                const efficiency = (hour.area / hour.totalHours).toFixed(2);
                const statusBgClass = hour.status === '已审核' ? 'bg-green-100' :
                  hour.status === '待审核' ? 'bg-orange-100' : 'bg-red-100';
                const statusIconClass = hour.status === '已审核' ? 'text-green-600' :
                  hour.status === '待审核' ? 'text-orange-600' : 'text-red-600';
                const statusBadgeClass = hour.status === '已审核' ? 'bg-green-100 text-green-800' :
                  hour.status === '待审核' ? 'bg-orange-100 text-orange-800' : 'bg-red-100 text-red-800';
                
                return (
                  <Card key={hour.id} className="p-4">
                    <div className="flex items-start justify-between mb-4">
                      <div className="flex items-start gap-3">
                        <div className={`p-2 rounded-lg ${statusBgClass}`}>
                          <Clock className={`w-5 h-5 ${statusIconClass}`} />
                        </div>
                        <div>
                          <div className="flex items-center gap-2 mb-1">
                            <h4>{hour.staffName} - {hour.workType}</h4>
                            <Badge className={statusBadgeClass}>
                              {hour.status}
                            </Badge>
                            <Badge variant="outline">
                              {hour.recordType}
                            </Badge>
                          </div>
                          <p className="text-sm text-muted-foreground">
                            {hour.date} {hour.startTime}-{hour.endTime} | {hour.totalHours}小时
                          </p>
                        </div>
                      </div>
                      <div className="flex gap-2">
                        {hour.status === '待审核' && (
                          <>
                            <Button size="sm" className="bg-green-600 hover:bg-green-700" onClick={() => handleApproveHour(hour.id)}>
                              <CheckCircle2 className="w-4 h-4 mr-2" />
                              审核通过
                            </Button>
                            <Button size="sm" variant="outline" onClick={() => handleRejectHour(hour.id)}>
                              驳回
                            </Button>
                          </>
                        )}
                        <Button size="sm" variant="outline" onClick={() => handleEditHour(hour)}>
                          <Edit className="w-4 h-4" />
                        </Button>
                        <Button size="sm" variant="outline" onClick={() => handleDeleteHour(hour.id)}>
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      </div>
                    </div>

                    <div className="grid grid-cols-4 gap-4">
                      <div className="p-3 bg-gray-50 rounded-lg">
                        <p className="text-xs text-muted-foreground">地块</p>
                        <p className="mt-1 font-medium">{hour.fieldName}</p>
                      </div>
                      <div className="p-3 bg-gray-50 rounded-lg">
                        <p className="text-xs text-muted-foreground">面积</p>
                        <p className="mt-1 font-medium">{hour.area} 亩</p>
                      </div>
                      <div className="p-3 bg-gray-50 rounded-lg">
                        <p className="text-xs text-muted-foreground">效率</p>
                        <p className="mt-1 font-medium">{efficiency} 亩/小时</p>
                      </div>
                      <div className="p-3 bg-gray-50 rounded-lg">
                        <p className="text-xs text-muted-foreground">关联任务</p>
                        <p className="mt-1 font-medium text-xs">{hour.taskName || '无'}</p>
                      </div>
                    </div>

                    {hour.notes && (
                      <div className="mt-3 p-3 bg-blue-50 rounded-lg">
                        <p className="text-xs text-blue-900">备注: {hour.notes}</p>
                      </div>
                    )}
                  </Card>
                );
              })
            )}
          </div>
        </TabsContent>

        {/* 绩效统计 */}
        <TabsContent value="statistics" className="space-y-4">
          {/* 说明 */}
          <Card className="p-4 bg-purple-50 border-purple-200">
            <div className="flex items-start gap-2">
              <Award className="w-5 h-5 text-purple-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-purple-900">
                <p className="mb-2">绩效统计功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>工作量统计</strong>: 基于已审核工时，统计完成亩数、任务数量</li>
                  <li>• <strong>效率计算</strong>: 动态计算亩/工时等效率指标</li>
                  <li>• <strong>排名展示</strong>: 个人和班组绩效自动排名</li>
                  <li>• <strong>多维度分析</strong>: 支持周/月/季/年多时间维度查询</li>
                  <li>• <strong>考评依据</strong>: 为管理层提供客观的考评和激励依据</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 筛选控制栏 */}
          <Card className="p-4">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-4">
                <div className="flex items-center gap-2">
                  <label className="text-xs">统计维度</label>
                  <Select value={perfViewType} onValueChange={(value: 'individual' | 'team') => setPerfViewType(value)}>
                    <SelectTrigger className="w-32 h-9">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="individual">个人绩效</SelectItem>
                      <SelectItem value="team">班组绩效</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="flex items-center gap-2">
                  <label className="text-xs">时间范围</label>
                  <Select value={perfTimeRange} onValueChange={(value: any) => setPerfTimeRange(value)}>
                    <SelectTrigger className="w-24 h-9">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="week">按周</SelectItem>
                      <SelectItem value="month">按月</SelectItem>
                      <SelectItem value="quarter">按季度</SelectItem>
                      <SelectItem value="year">按年</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="flex items-center gap-2">
                  <label className="text-xs">选择日期</label>
                  <Input
                    type="date"
                    value={perfPeriod}
                    onChange={(e) => setPerfPeriod(e.target.value)}
                    className="w-40 h-9"
                  />
                </div>
              </div>
              <div className="flex gap-2">
                <Button variant="outline" size="sm">
                  <Download className="w-4 h-4 mr-2" />
                  导出报表
                </Button>
              </div>
            </div>
          </Card>

          {/* 时间范围显示 */}
          <div className="p-3 bg-blue-50 rounded-lg">
            <p className="text-sm text-blue-900">
              <Calendar className="w-4 h-4 inline mr-1" />
              统计周期：
              <strong className="mx-2">{formatPeriodLabel()}</strong>
              ({perfStart.toLocaleDateString('zh-CN')} ~ {perfEnd.toLocaleDateString('zh-CN')})
              <span className="ml-4">
                统计对象：<strong>{perfViewType === 'individual' ? '个人' : '班组'}</strong>
              </span>
            </p>
          </div>

          {/* 关键指标卡片 */}
          <div className="grid grid-cols-4 gap-4">
            <Card className="p-4">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-lg bg-green-100 flex items-center justify-center">
                  <Target className="w-5 h-5 text-green-600" />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">总工作量</p>
                  <p className="text-2xl text-green-600 mt-1">
                    {currentPerfData.reduce((sum, p) => sum + p.completedArea, 0).toFixed(1)}
                  </p>
                  <p className="text-xs text-muted-foreground">亩</p>
                </div>
              </div>
            </Card>

            <Card className="p-4">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-lg bg-blue-100 flex items-center justify-center">
                  <Clock className="w-5 h-5 text-blue-600" />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">总工时</p>
                  <p className="text-2xl text-blue-600 mt-1">
                    {currentPerfData.reduce((sum, p) => sum + p.totalHours, 0).toFixed(1)}
                  </p>
                  <p className="text-xs text-muted-foreground">小时</p>
                </div>
              </div>
            </Card>

            <Card className="p-4">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-lg bg-purple-100 flex items-center justify-center">
                  <CheckCircle2 className="w-5 h-5 text-purple-600" />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">完成任务</p>
                  <p className="text-2xl text-purple-600 mt-1">
                    {currentPerfData.reduce((sum, p) => sum + p.completedTasks, 0)}
                  </p>
                  <p className="text-xs text-muted-foreground">个</p>
                </div>
              </div>
            </Card>

            <Card className="p-4">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-lg bg-orange-100 flex items-center justify-center">
                  <TrendingUp className="w-5 h-5 text-orange-600" />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">平均效率</p>
                  <p className="text-2xl text-orange-600 mt-1">
                    {currentPerfData.length > 0 
                      ? (currentPerfData.reduce((sum, p) => sum + p.efficiency, 0) / currentPerfData.length).toFixed(2)
                      : '0.00'
                    }
                  </p>
                  <p className="text-xs text-muted-foreground">亩每小时</p>
                </div>
              </div>
            </Card>
          </div>

          {/* 绩效排行榜 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <Trophy className="w-5 h-5 text-yellow-600" />
              {perfViewType === 'individual' ? '个人' : '班组'}绩效排行榜
            </h3>
            {currentPerfData.length === 0 ? (
              <div className="text-center py-12 text-muted-foreground">
                <Award className="w-16 h-16 mx-auto mb-3 opacity-20" />
                <p>该时间范围内暂无绩效数据</p>
                <p className="text-sm mt-1">请确保有已审核的工时记录</p>
              </div>
            ) : (
              <div className="space-y-3">
                {currentPerfData.map((perf, index) => {
                  const cardBorderClass = index === 0 ? 'border-2 border-yellow-400 bg-yellow-50' :
                    index === 1 ? 'border-2 border-gray-300 bg-gray-50' :
                    index === 2 ? 'border-2 border-orange-300 bg-orange-50' : '';
                  const rankBgClass = index === 0 ? 'bg-yellow-400' :
                    index === 1 ? 'bg-gray-400' :
                    index === 2 ? 'bg-orange-400' : 'bg-gray-200';
                  const trendBadgeClass = perf.trend === '上升' ? 'bg-green-100 text-green-800' :
                    perf.trend === '下降' ? 'bg-red-100 text-red-800' : 'bg-gray-100 text-gray-800';
                  const trendIcon = perf.trend === '上升' ? '↗' : perf.trend === '下降' ? '↘' : '→';
                  const efficiencyText = `${perf.efficiency} 亩每小时`;
                  
                  return (
                    <Card key={perf.staffId} className={`p-4 ${cardBorderClass}`}>
                      <div className="flex items-center gap-4">
                        <div className={`w-12 h-12 rounded-full flex items-center justify-center ${rankBgClass}`}>
                          <span className="text-xl font-bold text-white">{perf.ranking}</span>
                        </div>
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-1">
                            <h4>{perf.staffName}</h4>
                            <Badge variant="outline">{perf.team}</Badge>
                            <Badge className={trendBadgeClass}>
                              {trendIcon} {perf.trend}
                            </Badge>
                          </div>
                          <div className="grid grid-cols-5 gap-4 text-sm">
                            <div>
                              <span className="text-muted-foreground">总工时: </span>
                              <span className="font-medium">{perf.totalHours}h</span>
                            </div>
                            <div>
                              <span className="text-muted-foreground">完成任务: </span>
                              <span className="font-medium">{perf.completedTasks}个</span>
                            </div>
                            <div>
                              <span className="text-muted-foreground">完成面积: </span>
                              <span className="font-medium">{perf.completedArea}亩</span>
                            </div>
                            <div>
                              <span className="text-muted-foreground">效率: </span>
                              <span className="font-medium text-green-600">{efficiencyText}</span>
                            </div>
                            <div>
                              <span className="text-muted-foreground">评分: </span>
                              <span className="font-medium text-purple-600">{perf.score}分</span>
                            </div>
                          </div>
                        </div>
                        <div className="flex items-center gap-1">
                          {[1, 2, 3, 4, 5].map((star) => {
                            const scoreValue = perf.score;
                            const threshold = scoreValue * 0.05;
                            const filled = star <= Math.floor(threshold);
                            return (
                              <Star 
                                key={star} 
                                className={filled ? 'w-5 h-5 fill-yellow-400 text-yellow-400' : 'w-5 h-5 text-gray-300'} 
                              />
                            );
                          })}
                        </div>
                      </div>
                    </Card>
                  );
                })}
            </div>
            )}
          </Card>

          {/* 绩效图表 */}
          <div className="grid grid-cols-2 gap-4">
            <Card className="p-6">
              <h3 className="mb-4 flex items-center gap-2">
                <BarChart3 className="w-5 h-5 text-blue-600" />
                效率与工作量对比
              </h3>
              <div className="h-80">
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={efficiencyChartData}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="name" />
                    <YAxis yAxisId="left" label={{ value: '效率(亩每小时)', angle: -90, position: 'insideLeft' }} />
                    <YAxis yAxisId="right" orientation="right" label={{ value: '工作量(亩)', angle: 90, position: 'insideRight' }} />
                    <Tooltip />
                    <Legend />
                    <Bar yAxisId="left" dataKey="效率" fill="#3b82f6" name="效率(亩每小时)" />
                    <Bar yAxisId="right" dataKey="工作量" fill="#22c55e" name="工作量(亩)" />
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </Card>

            <Card className="p-6">
              <h3 className="mb-4 flex items-center gap-2">
                <Target className="w-5 h-5 text-purple-600" />
                工时与任务数分布
              </h3>
              <div className="h-80">
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={efficiencyChartData.map((d, i) => {
                    return {
                      ...d,
                      任务数: currentPerfData[i]?.completedTasks || 0
                    };
                  })}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="name" />
                    <YAxis />
                    <Tooltip />
                    <Legend />
                    <Bar dataKey="工时" fill="#f59e0b" name="工时(小时)" />
                    <Bar dataKey="任务数" fill="#a855f7" name="完成任务(个)" />
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </Card>
          </div>

          {/* 班组综合对比雷达图（仅班组视图显示） */}
          {perfViewType === 'team' && teamRadarData.length > 0 && (
            <Card className="p-6">
              <h3 className="mb-4 flex items-center gap-2">
                <Award className="w-5 h-5 text-orange-600" />
                班组综合能力雷达图
              </h3>
              <div className="h-96">
                <ResponsiveContainer width="100%" height="100%">
                  <RadarChart data={teamRadarData}>
                    <PolarGrid />
                    <PolarAngleAxis dataKey="班组" />
                    <PolarRadiusAxis angle={90} domain={[0, 100]} />
                    <Tooltip />
                    <Legend />
                    <Radar name="工作量" dataKey="工作量" stroke="#22c55e" fill="#22c55e" fillOpacity={0.3} />
                    <Radar name="效率" dataKey="效率" stroke="#3b82f6" fill="#3b82f6" fillOpacity={0.3} />
                    <Radar name="任务数" dataKey="任务数" stroke="#a855f7" fill="#a855f7" fillOpacity={0.3} />
                    <Radar name="工时" dataKey="工时" stroke="#f59e0b" fill="#f59e0b" fillOpacity={0.3} />
                  </RadarChart>
                </ResponsiveContainer>
              </div>
              <p className="text-xs text-muted-foreground mt-2 text-center">
                雷达图综合展示各班组在工作量、效率、任务数和工时四个维度的表现（数值已归一化至0-100）
              </p>
            </Card>
          )}

          {/* 效率趋势（示例数据） */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h3 className="flex items-center gap-2">
                <TrendingUp className="w-5 h-5 text-green-600" />
                效率趋势分析（近3个月）
              </h3>
              <p className="text-xs text-muted-foreground">示例数据 - 实际使用时将基于历史数据动态生成</p>
            </div>
            <div className="h-80">
              <ResponsiveContainer width="100%" height="100%">
                <LineChart data={trendChartData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="month" />
                  <YAxis label={{ value: '效率(亩每小时)', angle: -90, position: 'insideLeft' }} />
                  <Tooltip />
                  <Legend />
                  <Line type="monotone" dataKey="张三" stroke="#22c55e" strokeWidth={2} />
                  <Line type="monotone" dataKey="李四" stroke="#3b82f6" strokeWidth={2} />
                  <Line type="monotone" dataKey="王五" stroke="#a855f7" strokeWidth={2} />
                  <Line type="monotone" dataKey="赵六" stroke="#f97316" strokeWidth={2} />
                </LineChart>
              </ResponsiveContainer>
            </div>
          </Card>
        </TabsContent>

        {/* 排班管理 */}
        <TabsContent value="schedule" className="space-y-4">
          {showScheduleEditor ? (
            <ScheduleEditor
              schedule={selectedSchedule}
              staffList={staffList.map(s => ({ id: s.id, name: s.name, team: s.team || '未分配' }))}
              onSave={handleSaveSchedule}
              onCancel={() => {
                setShowScheduleEditor(false);
                setSelectedSchedule(null);
              }}
            />
          ) : (
            <>
              {/* 说明 */}
              <Card className="p-4 bg-orange-50 border-orange-200">
                <div className="flex items-start gap-2">
                  <Calendar className="w-5 h-5 text-orange-600 flex-shrink-0 mt-0.5" />
                  <div className="text-sm text-orange-900">
                    <p className="mb-2">排班管理功能：</p>
                    <ul className="space-y-1 text-xs">
                      <li>• <strong>周/月排班</strong>: 支持按周（7天）或按月（30天）制定排班计划</li>
                      <li>• <strong>人员分配</strong>: 可视化的人员时间分配界面，支持单独调整和批量操作</li>
                      <li>• <strong>班次管理</strong>: 早班（08:00-16:00）、中班（12:00-20:00）、晚班（16:00-00:00）、休息</li>
                      <li>• <strong>复制功能</strong>: 支持复制某一天的排班到其他日期，快速完成排班</li>
                      <li>• <strong>灵活编辑</strong>: 每个班次可单独设置工作时间和任务内容</li>
                      <li>• <strong>导出功能</strong>: 导出CSV格式班表，方便通知员工</li>
                    </ul>
                  </div>
                </div>
              </Card>

              <div className="flex items-center justify-between">
                <div className="flex gap-2">
                  <Button 
                    variant="outline"
                    onClick={() => {
                      if (schedules.length > 0) {
                        setShowCopyDialog(true);
                      } else {
                        toast.info('暂无排班可复制');
                      }
                    }}
                    disabled={schedules.length === 0}
                  >
                    <Copy className="w-4 h-4 mr-2" />
                    复制历史排班
                  </Button>
                </div>
                <Button className="bg-green-600 hover:bg-green-700" onClick={handleCreateSchedule}>
                  <Plus className="w-4 h-4 mr-2" />
                  新建排班
                </Button>
              </div>

              {/* 排班列表 */}
              {schedules.length === 0 ? (
                <Card className="p-12">
                  <div className="text-center text-muted-foreground">
                    <Calendar className="w-16 h-16 mx-auto mb-4 opacity-20" />
                    <p className="mb-2">暂无排班数据</p>
                    <p className="text-sm">点击"新建排班"开始创建周排班或月排班</p>
                  </div>
                </Card>
              ) : (
                <div className="space-y-4">
                  {schedules.map(schedule => (
                    <Card key={schedule.id} className="p-6">
                      <div className="flex items-center justify-between mb-4">
                        <div>
                          <div className="flex items-center gap-2 mb-1">
                            <h4>{schedule.name}</h4>
                            <Badge className={
                              schedule.status === '已发布' ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'
                            }>
                              {schedule.status}
                            </Badge>
                            <Badge variant="outline">
                              {schedule.type === 'week' ? '周排班' : '月排班'}
                            </Badge>
                          </div>
                          <p className="text-sm text-muted-foreground">
                            {schedule.startDate} ~ {schedule.endDate} · 共 {schedule.shifts.length} 个班次
                          </p>
                        </div>
                        <div className="flex gap-2">
                          <Button 
                            size="sm" 
                            variant="outline"
                            onClick={() => handleEditSchedule(schedule)}
                          >
                            <Edit className="w-4 h-4 mr-2" />
                            编辑
                          </Button>
                          <Button 
                            size="sm" 
                            variant="outline"
                            onClick={() => handleCopySchedule(schedule)}
                          >
                            <Copy className="w-4 h-4 mr-2" />
                            复制
                          </Button>
                          <Button 
                            size="sm" 
                            variant="outline"
                            onClick={() => handleExportSchedule(schedule)}
                          >
                            <Download className="w-4 h-4 mr-2" />
                            导出
                          </Button>
                          {schedule.status === '草稿' && (
                            <Button 
                              size="sm"
                              className="bg-green-600 hover:bg-green-700"
                              onClick={() => handlePublishSchedule(schedule.id)}
                            >
                              <CheckCircle2 className="w-4 h-4 mr-2" />
                              发布
                            </Button>
                          )}
                          <Button 
                            size="sm" 
                            variant="outline"
                            onClick={() => handleDeleteSchedule(schedule.id)}
                          >
                            <Trash2 className="w-4 h-4 text-red-500" />
                          </Button>
                        </div>
                      </div>

                      {/* 排班表格预览（显示前10条） */}
                      <div className="overflow-x-auto">
                        <table className="w-full text-sm">
                          <thead>
                            <tr className="border-b bg-gray-50">
                              <th className="text-left p-2">姓名</th>
                              <th className="text-left p-2">班组</th>
                              <th className="text-left p-2">日期</th>
                              <th className="text-left p-2">班次</th>
                              <th className="text-left p-2">工作时间</th>
                              <th className="text-left p-2">任务</th>
                            </tr>
                          </thead>
                          <tbody>
                            {schedule.shifts.slice(0, 10).map((shift, index) => (
                              <tr key={index} className="border-b hover:bg-gray-50">
                                <td className="p-2">{shift.staffName}</td>
                                <td className="p-2">{shift.team}</td>
                                <td className="p-2">{shift.date}</td>
                                <td className="p-2">
                                  <Badge className={
                                    shift.shift === '早班' ? 'bg-blue-100 text-blue-800' :
                                    shift.shift === '中班' ? 'bg-green-100 text-green-800' :
                                    shift.shift === '晚班' ? 'bg-purple-100 text-purple-800' :
                                    'bg-gray-100 text-gray-800'
                                  }>
                                    {shift.shift}
                                  </Badge>
                                </td>
                                <td className="p-2">{shift.workHours}</td>
                                <td className="p-2">{shift.task || '-'}</td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                        {schedule.shifts.length > 10 && (
                          <div className="p-2 text-center text-sm text-muted-foreground bg-gray-50">
                            还有 {schedule.shifts.length - 10} 个班次，点击"编辑"查看全部
                          </div>
                        )}
                      </div>
                    </Card>
                  ))}
                </div>
              )}
            </>
          )}
        </TabsContent>
      </Tabs>

      {/* 创建/编辑工时对话框 */}
      <Dialog open={showHourDialog} onOpenChange={setShowHourDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>{selectedHour ? '编辑工时记录' : '手动录入工时'}</DialogTitle>
            <DialogDescription>
              {selectedHour ? '修改员工工时信息' : '手动补录员工工时，确保数据准确以供薪酬核算'}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 max-h-[500px] overflow-y-auto">
            {/* 员工和工作类型 */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label>员工 *</label>
                <Select
                  value={hourFormData.staffId}
                  onValueChange={(value) => {
                    const staff = staffList.find(s => s.id === value);
                    setHourFormData({
                      ...hourFormData,
                      staffId: value,
                      staffName: staff?.name || '',
                    });
                  }}
                >
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="选择员工" />
                  </SelectTrigger>
                  <SelectContent>
                    {staffList.length === 0 ? (
                      <div className="p-2 text-sm text-muted-foreground text-center">
                        暂无员工数据
                      </div>
                    ) : (
                      staffList.map(staff => (
                        <SelectItem key={staff.id} value={staff.id}>
                          {staff.name} - {staff.position}
                        </SelectItem>
                      ))
                    )}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <label>工作类型 *</label>
                <Select
                  value={hourFormData.workType}
                  onValueChange={(value) => setHourFormData({ ...hourFormData, workType: value })}
                >
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="选择类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="深翻">深翻</SelectItem>
                    <SelectItem value="旋耕">旋耕</SelectItem>
                    <SelectItem value="播种">播种</SelectItem>
                    <SelectItem value="撒肥">撒肥</SelectItem>
                    <SelectItem value="施肥">施肥</SelectItem>
                    <SelectItem value="灌溉">灌溉</SelectItem>
                    <SelectItem value="除草">除草</SelectItem>
                    <SelectItem value="喷药">喷药</SelectItem>
                    <SelectItem value="病虫害防治">病虫害防治</SelectItem>
                    <SelectItem value="修剪">修剪</SelectItem>
                    <SelectItem value="采收">采收</SelectItem>
                    <SelectItem value="机械维修">机械维修</SelectItem>
                    <SelectItem value="其他">其他</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* 关联任务��可选） */}
            <div>
              <label>关联任务（可选）</label>
              <Input
                placeholder="可填写关联的任务名称"
                className="mt-2"
                value={hourFormData.taskName}
                onChange={(e) => setHourFormData({ ...hourFormData, taskName: e.target.value })}
              />
              <p className="text-xs text-muted-foreground mt-1">
                手动录入时可选填，系统会自动从任务执行中同步
              </p>
            </div>

            {/* 日期和时间 */}
            <div className="grid grid-cols-3 gap-4">
              <div>
                <label>日期 *</label>
                <Input
                  type="date"
                  className="mt-2"
                  value={hourFormData.date}
                  onChange={(e) => setHourFormData({ ...hourFormData, date: e.target.value })}
                />
              </div>
              <div>
                <label>开始时间 *</label>
                <Input
                  type="time"
                  className="mt-2"
                  value={hourFormData.startTime}
                  onChange={(e) => setHourFormData({ ...hourFormData, startTime: e.target.value })}
                />
              </div>
              <div>
                <label>结束时间 *</label>
                <Input
                  type="time"
                  className="mt-2"
                  value={hourFormData.endTime}
                  onChange={(e) => setHourFormData({ ...hourFormData, endTime: e.target.value })}
                />
              </div>
            </div>

            {/* 工时预览 */}
            {hourFormData.startTime && hourFormData.endTime && (
              <Card className="p-3 bg-blue-50 border-blue-200">
                <div className="flex items-center gap-2 text-sm text-blue-900">
                  <Clock className="w-4 h-4" />
                  <span>
                    预计工时：
                    {(() => {
                      const start = new Date(`2024-01-01 ${hourFormData.startTime}`);
                      const end = new Date(`2024-01-01 ${hourFormData.endTime}`);
                      const hours = (end.getTime() - start.getTime()) / (1000 * 60 * 60);
                      return hours > 0 ? `${hours.toFixed(2)} 小时` : '请确认时间有效性';
                    })()}
                  </span>
                </div>
              </Card>
            )}

            {/* 地块和面积 */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label>地块名称</label>
                <Input
                  placeholder="如：东区1号地"
                  className="mt-2"
                  value={hourFormData.fieldName}
                  onChange={(e) => setHourFormData({ ...hourFormData, fieldName: e.target.value })}
                />
              </div>
              <div>
                <label>作业面积(亩)</label>
                <Input
                  type="number"
                  placeholder="请输入面积"
                  className="mt-2"
                  min="0"
                  step="0.1"
                  value={hourFormData.area || ''}
                  onChange={(e) => setHourFormData({ ...hourFormData, area: parseFloat(e.target.value) || 0 })}
                />
              </div>
            </div>

            {/* 备注 */}
            <div>
              <label>备注信息</label>
              <Textarea
                placeholder="请输入备注信息，如：工作情况、特殊说明等"
                className="mt-2"
                rows={3}
                value={hourFormData.notes}
                onChange={(e) => setHourFormData({ ...hourFormData, notes: e.target.value })}
              />
            </div>

            {/* 数据准确性提示 */}
            <Card className="p-3 bg-orange-50 border-orange-200">
              <p className="text-xs text-orange-900">
                <strong>数据准确性提示：</strong>工时记录将作为薪酬核算的重要依据，请确保录入的时间、地块、面���等信息准确无误。
              </p>
            </Card>

            {/* 操作按钮 */}
            <div className="flex gap-2 justify-end pt-4">
              <Button variant="outline" onClick={() => setShowHourDialog(false)}>
                取消
              </Button>
              <Button className="bg-green-600 hover:bg-green-700" onClick={handleSaveHour}>
                <Save className="w-4 h-4 mr-2" />
                保存工时记录
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 复制排班选择对话框 */}
      <Dialog open={showCopyDialog} onOpenChange={setShowCopyDialog}>
        <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>选择要复制的排班</DialogTitle>
            <DialogDescription>
              从历史排班中选择一个作为模板，系统将复制排班结构和人员安排
            </DialogDescription>
          </DialogHeader>
          
          <div className="space-y-3">
            {schedules.length === 0 ? (
              <div className="text-center py-12 text-muted-foreground">
                <Calendar className="w-16 h-16 mx-auto mb-4 opacity-20" />
                <p>暂无历��排班</p>
              </div>
            ) : (
              schedules.map(schedule => (
                <Card 
                  key={schedule.id} 
                  className="p-4 hover:shadow-md transition-shadow cursor-pointer border-2 hover:border-green-300"
                  onClick={() => {
                    handleCopySchedule(schedule);
                    setShowCopyDialog(false);
                  }}
                >
                  <div className="flex items-center justify-between">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-2">
                        <h4>{schedule.name}</h4>
                        <Badge className={
                          schedule.status === '已发布' ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'
                        }>
                          {schedule.status}
                        </Badge>
                        <Badge variant="outline">
                          {schedule.type === 'week' ? '周排班' : '月排班'}
                        </Badge>
                      </div>
                      <div className="space-y-1 text-sm text-muted-foreground">
                        <p>
                          <Calendar className="w-4 h-4 inline mr-1" />
                          排班周期：{schedule.startDate} ~ {schedule.endDate}
                        </p>
                        <p>
                          <Users className="w-4 h-4 inline mr-1" />
                          班次数量：{schedule.shifts.length} 个班次
                        </p>
                        <p>
                          <User className="w-4 h-4 inline mr-1" />
                          涉及人员：{new Set(schedule.shifts.map(s => s.staffId)).size} 人
                        </p>
                        <p>
                          <Clock className="w-4 h-4 inline mr-1" />
                          创建时间：{new Date(schedule.createdAt).toLocaleString('zh-CN')}
                        </p>
                      </div>
                    </div>
                    <div className="ml-4">
                      <Button 
                        size="sm"
                        className="bg-green-600 hover:bg-green-700"
                        onClick={(e) => {
                          e.stopPropagation();
                          handleCopySchedule(schedule);
                          setShowCopyDialog(false);
                        }}
                      >
                        <Copy className="w-4 h-4 mr-2" />
                        选择此排班
                      </Button>
                    </div>
                  </div>
                  
                  {/* 排班预览 */}
                  {schedule.shifts.length > 0 && (
                    <div className="mt-3 pt-3 border-t">
                      <p className="text-xs text-muted-foreground mb-2">排班预览（前5条）：</p>
                      <div className="space-y-1">
                        {schedule.shifts.slice(0, 5).map((shift, index) => (
                          <div key={index} className="text-xs flex items-center gap-2 text-muted-foreground">
                            <span className="font-medium">{shift.staffName}</span>
                            <span>·</span>
                            <span>{shift.date}</span>
                            <span>·</span>
                            <Badge className="h-5 text-xs">
                              {shift.shift}
                            </Badge>
                            <span>·</span>
                            <span>{shift.workHours}</span>
                            {shift.task && (
                              <>
                                <span>·</span>
                                <span>{shift.task}</span>
                              </>
                            )}
                          </div>
                        ))}
                        {schedule.shifts.length > 5 && (
                          <p className="text-xs text-muted-foreground">
                            还有 {schedule.shifts.length - 5} 个班次...
                          </p>
                        )}
                      </div>
                    </div>
                  )}
                </Card>
              ))
            )}
          </div>
          
          <div className="flex justify-end gap-2 mt-4 pt-4 border-t">
            <Button variant="outline" onClick={() => setShowCopyDialog(false)}>
              取消
            </Button>
          </div>
        </DialogContent>
      </Dialog>

    </div>
  );
}
