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 { Avatar } from '../ui/avatar';
import {
  AlertCircle,
  Plus,
  Edit,
  Trash2,
  Eye,
  Search,
  Filter,
  Download,
  Upload,
  Camera,
  MapPin,
  Clock,
  User,
  Users,
  Send,
  MessageSquare,
  CheckCircle2,
  XCircle,
  AlertTriangle,
  Settings,
  Wrench,
  Bug,
  Sprout,
  Droplet,
  Zap,
  FileText,
  Image as ImageIcon,
  ThumbsUp,
  Reply,
  Link2,
  Bell,
  Target,
  GitBranch,
  Activity,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
} from 'recharts';

// 图表配色方案（使用CSS变量对应的颜色值）
const COLORS = [
  'hsl(var(--success))',
  'hsl(var(--info))',
  'hsl(var(--warning))',
  'hsl(var(--error))',
  'hsl(var(--accent))',
];

interface OperationIssueProps {
  activePath?: string;
}

type IssueType = '病虫害' | '设备故障' | '灌溉问题' | '施肥问题' | '其他';
type IssueSeverity = '低' | '中' | '高' | '紧急';
type IssueStatus = '待分派' | '处理中' | '待验收' | '已解决' | '已关闭';

interface Issue {
  id: string;
  title: string;
  type: IssueType;
  severity: IssueSeverity;
  status: IssueStatus;
  description: string;
  fieldId: string;
  fieldName: string;
  reporterId: string;
  reporterName: string;
  reporterPhone: string;
  assigneeId?: string;
  assigneeName?: string;
  resolverId?: string;
  resolverName?: string;
  solution?: string;
  location: {
    latitude: number;
    longitude: number;
    address: string;
  };
  photos: string[];
  createdAt: string;
  updatedAt: string;
  resolvedAt?: string;
  discussions: Discussion[];
  tags: string[];
}

interface Discussion {
  id: string;
  userId: string;
  userName: string;
  userRole: string;
  content: string;
  type: 'comment' | 'diagnosis' | 'solution' | 'question';
  images?: string[];
  createdAt: string;
  likes: number;
  replies?: Reply[];
}

interface Reply {
  id: string;
  userId: string;
  userName: string;
  content: string;
  createdAt: string;
}

export function OperationIssue({ activePath }: OperationIssueProps) {
  const [activeTab, setActiveTab] = useState('report');
  const [showIssueDialog, setShowIssueDialog] = useState(false);
  const [showDiscussionDialog, setShowDiscussionDialog] = useState(false);
  const [showAssignDialog, setShowAssignDialog] = useState(false);
  const [showResolveDialog, setShowResolveDialog] = useState(false);
  const [selectedIssue, setSelectedIssue] = useState<Issue | null>(null);
  const [issueToAssign, setIssueToAssign] = useState<Issue | null>(null);
  const [issueToResolve, setIssueToResolve] = useState<Issue | null>(null);
  const [solutionText, setSolutionText] = useState('');
  const [filterType, setFilterType] = useState<string>('all');
  const [filterStatus, setFilterStatus] = useState<string>('all');
  const [filterSeverity, setFilterSeverity] = useState<string>('all');

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

  // 模拟问题数据
  const [issues, setIssues] = useState<Issue[]>([
    {
      id: 'issue-1',
      title: '东区1号地发现水稻稻飞虱',
      type: '病虫害',
      severity: '高',
      status: '处理中',
      description: '今天巡田时发现东区1号地有大量稻飞虱，叶片发黄，需要紧急处理。',
      fieldId: 'field-1',
      fieldName: '东区1号地',
      reporterId: 'user-1',
      reporterName: '张三',
      reporterPhone: '13800138001',
      assigneeId: 'user-3',
      assigneeName: '王五（植保专家）',
      location: {
        latitude: 30.25,
        longitude: 120.15,
        address: '浙江省杭州市余杭区东区1号地',
      },
      photos: ['pest1.jpg', 'pest2.jpg', 'pest3.jpg'],
      createdAt: '2024-03-20 09:30',
      updatedAt: '2024-03-20 14:20',
      discussions: [
        {
          id: 'disc-1',
          userId: 'user-3',
          userName: '王五',
          userRole: '植保专家',
          content: '根据照片判断是褐飞虱，属于严重虫害。建议使用吡虫啉或噻虫嗪进行防治。',
          type: 'diagnosis',
          createdAt: '2024-03-20 10:15',
          likes: 3,
        },
        {
          id: 'disc-2',
          userId: 'user-3',
          userName: '王五',
          userRole: '植保专家',
          content: '防治方案：\n1. 使用25%吡虫啉可湿性粉剂，每亩20-30克\n2. 兑水45公斤均匀喷雾\n3. 选择晴朗无风天气施药\n4. 注意安全间隔期15天',
          type: 'solution',
          images: ['solution.jpg'],
          createdAt: '2024-03-20 10:30',
          likes: 5,
          replies: [
            {
              id: 'reply-1',
              userId: 'user-1',
              userName: '张三',
              content: '收到，我立即准备农药，下午开始喷洒',
              createdAt: '2024-03-20 11:00',
            },
          ],
        },
      ],
      tags: ['水稻', '褐飞虱', '紧急处理'],
    },
    {
      id: 'issue-2',
      title: '旋耕机液压系统异常',
      type: '设备故障',
      severity: '中',
      status: '待分派',
      description: '旋耕机在作业时液压系统压力不稳定，作业效率明显下降。',
      fieldId: 'field-2',
      fieldName: '西区2号地',
      reporterId: 'user-2',
      reporterName: '李四',
      reporterPhone: '13800138002',
      location: {
        latitude: 30.28,
        longitude: 120.12,
        address: '浙江省杭州市余杭区西区2号地',
      },
      photos: ['machine1.jpg'],
      createdAt: '2024-03-21 08:00',
      updatedAt: '2024-03-21 08:00',
      discussions: [],
      tags: ['旋耕机', '液压系统', '设备维修'],
    },
    {
      id: 'issue-3',
      title: '南区3号地灌溉系统堵塞',
      type: '灌溉问题',
      severity: '高',
      status: '已解决',
      description: '滴灌系统多个滴头堵塞，影响灌溉效果。',
      fieldId: 'field-3',
      fieldName: '南区3号地',
      reporterId: 'user-4',
      reporterName: '赵六',
      reporterPhone: '13800138004',
      assigneeId: 'user-4',
      assigneeName: '赵六（灌溉技术员）',
      resolverId: 'user-4',
      resolverName: '赵六（灌溉技术员）',
      solution: '问题原因分析：经现场检查发现，滴灌系统堵塞是由于水质中含有较多杂质和悬浮物导致的。\n\n解决措施：\n1. 清洗主管道滤网，去除积累的杂质\n2. 逐个检查并清洗堵塞的滴头\n3. 对整个管道系统进行高压冲洗\n4. 更换了老化的滤网\n\n处理结果：所有滴头恢复正常工作，灌溉效果良好，已进行测试验证。\n\n预防建议：建议每周检查滤网，每月进行一次管道冲洗，并考虑安装前置过滤系统。',
      location: {
        latitude: 30.22,
        longitude: 120.18,
        address: '浙江省杭州市余杭区南区3号地',
      },
      photos: ['irrigation1.jpg', 'irrigation2.jpg'],
      createdAt: '2024-03-19 14:00',
      updatedAt: '2024-03-20 16:30',
      resolvedAt: '2024-03-20 16:30',
      discussions: [
        {
          id: 'disc-3',
          userId: 'user-4',
          userName: '赵六',
          userRole: '灌溉技术员',
          content: '检查发现是水质问题导致的堵塞，已清洗滤网并冲洗管道，问题已解决。',
          type: 'solution',
          createdAt: '2024-03-20 16:00',
          likes: 2,
        },
      ],
      tags: ['滴灌', '堵塞', '已解决'],
    },
  ]);

  // 人员数据 - 按专业分类
  const staffMembers = [
    // 植保专家
    {
      id: 'user-3',
      name: '王五',
      role: '植保专家',
      specialty: '病虫害',
      department: '技术部',
      phone: '13800138003',
      workload: 2,
      rating: 4.8,
    },
    {
      id: 'user-6',
      name: '李四',
      role: '植保技术员',
      specialty: '病虫害',
      department: '技术部',
      phone: '13800138006',
      workload: 1,
      rating: 4.5,
    },
    // 设备维修人员
    {
      id: 'user-5',
      name: '周七',
      role: '维修工',
      specialty: '设备故障',
      department: '维修部',
      phone: '13800138005',
      workload: 3,
      rating: 4.6,
    },
    {
      id: 'user-7',
      name: '孙八',
      role: '机械师',
      specialty: '设备故障',
      department: '维修部',
      phone: '13800138007',
      workload: 2,
      rating: 4.7,
    },
    // 灌溉技术人员
    {
      id: 'user-4',
      name: '赵六',
      role: '灌溉技术员',
      specialty: '灌溉问题',
      department: '灌溉部',
      phone: '13800138004',
      workload: 1,
      rating: 4.9,
    },
    {
      id: 'user-8',
      name: '钱九',
      role: '水利工程师',
      specialty: '灌溉问题',
      department: '灌溉部',
      phone: '13800138008',
      workload: 0,
      rating: 5.0,
    },
    // 农艺师
    {
      id: 'user-9',
      name: '吴十',
      role: '农艺师',
      specialty: '施肥问题',
      department: '技术部',
      phone: '13800138009',
      workload: 1,
      rating: 4.7,
    },
    {
      id: 'user-10',
      name: '郑十一',
      role: '高级农艺师',
      specialty: '施肥问题',
      department: '技术部',
      phone: '13800138010',
      workload: 2,
      rating: 4.9,
    },
  ];

  const getTypeIcon = (type: IssueType) => {
    switch (type) {
      case '病虫害': return <Bug className="w-4 h-4" />;
      case '设备故障': return <Settings className="w-4 h-4" />;
      case '灌溉问题': return <Droplet className="w-4 h-4" />;
      case '施肥问题': return <Sprout className="w-4 h-4" />;
      case '其他': return <AlertCircle className="w-4 h-4" />;
      default: return <AlertCircle className="w-4 h-4" />;
    }
  };

  const getTypeColor = (type: IssueType) => {
    switch (type) {
      case '病虫害': return 'bg-error-muted text-error-muted-foreground';
      case '设备故障': return 'bg-warning-muted text-warning-muted-foreground';
      case '灌溉问题': return 'bg-info-muted text-info-muted-foreground';
      case '施肥问题': return 'bg-success-muted text-success-muted-foreground';
      case '其他': return 'bg-muted text-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getSeverityColor = (severity: IssueSeverity) => {
    switch (severity) {
      case '低': return 'bg-secondary text-secondary-foreground';
      case '中': return 'bg-warning text-warning-foreground';
      case '高': return 'bg-warning text-warning-foreground';
      case '紧急': return 'bg-destructive text-destructive-foreground';
      default: return 'bg-secondary text-secondary-foreground';
    }
  };

  const getStatusColor = (status: IssueStatus) => {
    switch (status) {
      case '待分派': return 'bg-secondary text-secondary-foreground';
      case '处理中': return 'bg-info text-info-foreground';
      case '待验收': return 'bg-accent text-accent-foreground';
      case '已解决': return 'bg-success text-success-foreground';
      case '已关闭': return 'bg-muted text-muted-foreground';
      default: return 'bg-secondary text-secondary-foreground';
    }
  };

  const getDiscussionTypeColor = (type: string) => {
    switch (type) {
      case 'comment': return 'bg-muted';
      case 'diagnosis': return 'bg-info-muted border border-info/30';
      case 'solution': return 'bg-success-muted border border-success/30';
      case 'question': return 'bg-warning-muted border border-warning/30';
      default: return 'bg-muted';
    }
  };

  const handleCreateIssue = () => {
    setSelectedIssue(null);
    setShowIssueDialog(true);
  };

  const handleViewIssue = (issue: Issue) => {
    setSelectedIssue(issue);
    setShowDiscussionDialog(true);
  };

  const handleOpenAssignDialog = (issue: Issue) => {
    setIssueToAssign(issue);
    setShowAssignDialog(true);
  };

  const handleAssignIssue = (issueId: string, assigneeId: string, assigneeName: string) => {
    setIssues(issues.map(issue =>
      issue.id === issueId
        ? { ...issue, assigneeId, assigneeName, status: '处理中', updatedAt: new Date().toLocaleString('zh-CN') }
        : issue
    ));
    setShowAssignDialog(false);
    setIssueToAssign(null);
    toast.success(`已分派给 ${assigneeName}`);
  };

  const handleResolveIssue = (issueId: string) => {
    const issue = issues.find(i => i.id === issueId);
    if (issue) {
      setIssueToResolve(issue);
      setSolutionText('');
      setShowResolveDialog(true);
    }
  };

  const handleConfirmResolve = () => {
    if (!issueToResolve) return;
    
    if (!solutionText.trim()) {
      toast.error('请输入解决方案');
      return;
    }

    const now = new Date().toLocaleString('zh-CN');
    setIssues(issues.map(issue =>
      issue.id === issueToResolve.id
        ? { 
            ...issue, 
            status: '已解决', 
            updatedAt: now, 
            resolvedAt: now,
            resolverId: issue.assigneeId,
            resolverName: issue.assigneeName,
            solution: solutionText
          }
        : issue
    ));
    
    setShowResolveDialog(false);
    setIssueToResolve(null);
    setSolutionText('');
    toast.success('问题已标记为已解决');
  };

  const filteredIssues = issues.filter(issue => {
    if (filterType !== 'all' && issue.type !== filterType) return false;
    if (filterStatus !== 'all' && issue.status !== filterStatus) return false;
    if (filterSeverity !== 'all' && issue.severity !== filterSeverity) return false;
    return true;
  });

  // 统计数据
  const totalIssues = issues.length;
  const pendingIssues = issues.filter(i => i.status === '待分派').length;
  const processingIssues = issues.filter(i => i.status === '处理中').length;
  const resolvedIssues = issues.filter(i => i.status === '已解决').length;

  // 问题类型统计
  const issueTypeStats = [
    { name: '病虫害', value: issues.filter(i => i.type === '病虫害').length },
    { name: '设备故障', value: issues.filter(i => i.type === '设备故障').length },
    { name: '灌溉问题', value: issues.filter(i => i.type === '灌溉问题').length },
    { name: '施肥问题', value: issues.filter(i => i.type === '施肥问题').length },
    { name: '其他', value: issues.filter(i => i.type === '其他').length },
  ];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2>农事问题协同</h2>
          <p className="text-muted-foreground">
            问题一键上报、智能分派与在线协同解决
          </p>
        </div>
        <Button onClick={handleCreateIssue}>
          <Plus className="w-4 h-4 mr-2" />
          上报问题
        </Button>
      </div>

      {/* 统计概览 */}
      <div className="grid grid-cols-4 gap-4">
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">总问题数</p>
              <p className="mt-2 text-3xl text-accent-foreground">{totalIssues}</p>
            </div>
            <AlertCircle className="w-12 h-12 text-accent-foreground opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">待分派</p>
              <p className="mt-2 text-3xl text-muted-foreground">{pendingIssues}</p>
            </div>
            <Target className="w-12 h-12 text-muted-foreground opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">处理中</p>
              <p className="mt-2 text-3xl text-info">{processingIssues}</p>
            </div>
            <Activity className="w-12 h-12 text-info opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">已解决</p>
              <p className="mt-2 text-3xl text-success">{resolvedIssues}</p>
            </div>
            <CheckCircle2 className="w-12 h-12 text-success opacity-50" />
          </div>
        </Card>
      </div>

      {/* 筛选器 */}
      <Card className="p-4">
        <div className="flex items-center gap-4">
          <Filter className="w-4 h-4 text-muted-foreground" />
          <Select value={filterType} onValueChange={setFilterType}>
            <SelectTrigger className="w-48">
              <SelectValue placeholder="问题类型" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部类型</SelectItem>
              <SelectItem value="病虫害">病虫害</SelectItem>
              <SelectItem value="设备故障">设备故障</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>
              <SelectItem value="已解决">已解决</SelectItem>
              <SelectItem value="已关闭">已关闭</SelectItem>
            </SelectContent>
          </Select>

          <Select value={filterSeverity} onValueChange={setFilterSeverity}>
            <SelectTrigger className="w-48">
              <SelectValue placeholder="严重程度" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部程度</SelectItem>
              <SelectItem value="低">低</SelectItem>
              <SelectItem value="中">中</SelectItem>
              <SelectItem value="高">高</SelectItem>
              <SelectItem value="紧急">紧急</SelectItem>
            </SelectContent>
          </Select>

          <div className="flex-1" />
          <div className="flex items-center gap-2">
            <Search className="w-4 h-4 text-muted-foreground" />
            <Input placeholder="搜索问题..." className="w-64" />
          </div>
        </div>
      </Card>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="report">问题一键上报</TabsTrigger>
          <TabsTrigger value="assign">问题处理与分派</TabsTrigger>
          <TabsTrigger value="collaborate">在线协同</TabsTrigger>
        </TabsList>

        {/* 问题一键上报 */}
        <TabsContent value="report" className="space-y-4">
          {/* 上报说明 */}
          <Card className="p-4 bg-info-muted border-info/30">
            <div className="flex items-start gap-2">
              <Upload 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>: 自动记录上报人、上报时间、GPS位置</li>
                  <li>• <strong>快速响应</strong>: 系统自动路由至相应责任人，及时处理</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 快速上报入口 */}
          <div className="grid grid-cols-3 gap-4">
            <Card className="p-6 hover:shadow-lg transition-shadow cursor-pointer" onClick={handleCreateIssue}>
              <div className="flex flex-col items-center text-center">
                <div className="p-4 bg-error-muted rounded-lg mb-3">
                  <Bug className="w-8 h-8 text-error" />
                </div>
                <h4 className="mb-2">病虫害问题</h4>
                <p className="text-xs text-muted-foreground">
                  发现病虫害，立即上报
                </p>
              </div>
            </Card>

            <Card className="p-6 hover:shadow-lg transition-shadow cursor-pointer" onClick={handleCreateIssue}>
              <div className="flex flex-col items-center text-center">
                <div className="p-4 bg-warning-muted rounded-lg mb-3">
                  <Settings className="w-8 h-8 text-warning" />
                </div>
                <h4 className="mb-2">设备故障</h4>
                <p className="text-xs text-muted-foreground">
                  农机设备出现故障
                </p>
              </div>
            </Card>

            <Card className="p-6 hover:shadow-lg transition-shadow cursor-pointer" onClick={handleCreateIssue}>
              <div className="flex flex-col items-center text-center">
                <div className="p-4 bg-info-muted rounded-lg mb-3">
                  <Droplet className="w-8 h-8 text-info" />
                </div>
                <h4 className="mb-2">灌溉问题</h4>
                <p className="text-xs text-muted-foreground">
                  灌溉系统异常
                </p>
              </div>
            </Card>
          </div>

          {/* 我的上报记录 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <FileText className="w-5 h-5 text-primary" />
              我的上报记录
            </h3>
            <div className="space-y-4">
              {filteredIssues.map(issue => (
                <Card key={issue.id} className="p-4 hover:shadow-md transition-shadow cursor-pointer" onClick={() => handleViewIssue(issue)}>
                  <div className="flex items-start gap-4">
                    <div className={`p-3 rounded-lg ${getTypeColor(issue.type)}`}>
                      {getTypeIcon(issue.type)}
                    </div>
                    <div className="flex-1">
                      <div className="flex items-start justify-between mb-2">
                        <div>
                          <div className="flex items-center gap-2 mb-1">
                            <h4>{issue.title}</h4>
                            <Badge className={getStatusColor(issue.status)}>
                              {issue.status}
                            </Badge>
                            <Badge className={getSeverityColor(issue.severity)}>
                              {issue.severity}
                            </Badge>
                          </div>
                          <p className="text-sm text-muted-foreground">
                            {issue.fieldName} | 上报人: {issue.reporterName}
                          </p>
                        </div>
                      </div>
                      <p className="text-sm text-muted-foreground mb-3 line-clamp-2">
                        {issue.description}
                      </p>
                      <div className="flex items-center justify-between text-xs text-muted-foreground">
                        <div className="flex items-center gap-4">
                          <span className="flex items-center gap-1">
                            <Clock className="w-3 h-3" />
                            {issue.createdAt}
                          </span>
                          <span className="flex items-center gap-1">
                            <Camera className="w-3 h-3" />
                            {issue.photos.length} 张照片
                          </span>
                          <span className="flex items-center gap-1">
                            <MessageSquare className="w-3 h-3" />
                            {issue.discussions.length} 条讨论
                          </span>
                        </div>
                        {issue.assigneeName && (
                          <span className="flex items-center gap-1">
                            <User className="w-3 h-3" />
                            负责人: {issue.assigneeName}
                          </span>
                        )}
                      </div>
                      
                      {/* 已完成问题显示解决信息 */}
                      {(issue.status === '已解决' || issue.status === '已关闭') && issue.resolverName && issue.resolvedAt && (
                        <div className="mt-3 pt-3 border-t border-success/30">
                          <div className="flex items-center gap-4 text-xs">
                            <span className="flex items-center gap-1 text-success">
                              <CheckCircle2 className="w-3 h-3" />
                              解决人: <strong>{issue.resolverName}</strong>
                            </span>
                            <span className="flex items-center gap-1 text-success">
                              <Clock className="w-3 h-3" />
                              解决时间: <strong>{issue.resolvedAt}</strong>
                            </span>
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                </Card>
              ))}
            </div>
          </Card>
        </TabsContent>

        {/* 问题处理与分派 */}
        <TabsContent value="assign" className="space-y-4">
          {/* 分派说明 */}
          <Card className="p-4 bg-success-muted border-success/30">
            <div className="flex items-start gap-2">
              <GitBranch 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>消息通知</strong>: 分派后自动发送通知给责任人</li>
                  <li>• <strong>状态跟踪</strong>: 实时跟踪问题处理进度</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 待分派问题 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <Target className="w-5 h-5 text-warning" />
              待分派问题 ({pendingIssues} 个)
            </h3>
            <div className="space-y-4">
              {issues.filter(i => i.status === '待分派').map(issue => (
                <Card key={issue.id} className="p-4 border-l-4 border-l-warning">
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-start gap-3">
                      <div className={`p-2 rounded-lg ${getTypeColor(issue.type)}`}>
                        {getTypeIcon(issue.type)}
                      </div>
                      <div>
                        <div className="flex items-center gap-2 mb-1">
                          <h4>{issue.title}</h4>
                          <Badge className={getSeverityColor(issue.severity)}>
                            {issue.severity}
                          </Badge>
                        </div>
                        <p className="text-sm text-muted-foreground mb-2">
                          {issue.fieldName} | {issue.reporterName} | {issue.createdAt}
                        </p>
                        <p className="text-sm text-muted-foreground">
                          {issue.description}
                        </p>
                      </div>
                    </div>
                  </div>

                  {/* 推荐责任人 */}
                  <div className="mb-3 p-3 bg-info-muted rounded-lg">
                    <p className="text-xs text-info-muted-foreground mb-2">💡 系统推荐责任人:</p>
                    <div className="flex gap-2">
                      {issue.type === '病虫害' && (
                        <>
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => handleAssignIssue(issue.id, 'user-3', '王五（植保专家）')}
                          >
                            王五（植保专家）
                          </Button>
                          <Button size="sm" variant="outline">
                            李四（植保技术员）
                          </Button>
                        </>
                      )}
                      {issue.type === '设备故障' && (
                        <>
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => handleAssignIssue(issue.id, 'user-5', '周七（维修工）')}
                          >
                            周七（维修工）
                          </Button>
                          <Button size="sm" variant="outline">
                            孙八（机械师）
                          </Button>
                        </>
                      )}
                      {issue.type === '灌溉问题' && (
                        <>
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => handleAssignIssue(issue.id, 'user-4', '赵六（灌溉技术员）')}
                          >
                            赵六（灌溉技术员）
                          </Button>
                        </>
                      )}
                    </div>
                  </div>

                  <div className="flex gap-2">
                    <Button size="sm" variant="outline" onClick={() => handleViewIssue(issue)}>
                      <Eye className="w-4 h-4 mr-2" />
                      查看详情
                    </Button>
                    <Button 
                      size="sm" 
                      variant="outline"
                      onClick={() => handleOpenAssignDialog(issue)}
                    >
                      <Users className="w-4 h-4 mr-2" />
                      手动分派
                    </Button>
                  </div>
                </Card>
              ))}
            </div>
          </Card>

          {/* 处理中问题 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <Activity className="w-5 h-5 text-info" />
              处理中问题 ({processingIssues} 个)
            </h3>
            <div className="space-y-4">
              {issues.filter(i => i.status === '处理中').map(issue => (
                <Card key={issue.id} className="p-4 border-l-4 border-l-info">
                  <div className="flex items-start justify-between">
                    <div className="flex items-start gap-3">
                      <div className={`p-2 rounded-lg ${getTypeColor(issue.type)}`}>
                        {getTypeIcon(issue.type)}
                      </div>
                      <div>
                        <div className="flex items-center gap-2 mb-1">
                          <h4>{issue.title}</h4>
                          <Badge className={getStatusColor(issue.status)}>
                            {issue.status}
                          </Badge>
                        </div>
                        <p className="text-sm text-muted-foreground mb-2">
                          负责人: {issue.assigneeName} | 更新时间: {issue.updatedAt}
                        </p>
                        <div className="flex items-center gap-3 text-xs text-muted-foreground">
                          <span className="flex items-center gap-1">
                            <MessageSquare className="w-3 h-3" />
                            {issue.discussions.length} 条讨论
                          </span>
                          <span className="flex items-center gap-1">
                            <Users className="w-3 h-3" />
                            {issue.discussions.filter(d => d.type === 'solution').length} 个方案
                          </span>
                        </div>
                      </div>
                    </div>
                    <div className="flex gap-2">
                      <Button size="sm" variant="outline" onClick={() => handleViewIssue(issue)}>
                        <Eye className="w-4 h-4 mr-2" />
                        查看进度
                      </Button>
                      <Button
                        size="sm"
                        className="bg-success hover:bg-success/90"
                        onClick={() => handleResolveIssue(issue.id)}
                      >
                        <CheckCircle2 className="w-4 h-4 mr-2" />
                        标记解决
                      </Button>
                    </div>
                  </div>
                </Card>
              ))}
            </div>
          </Card>

          {/* 问题类型统计 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <BarChart className="w-5 h-5 text-accent-foreground" />
              问题类型统计
            </h3>
            <div className="h-80">
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie
                    data={issueTypeStats}
                    cx="50%"
                    cy="50%"
                    labelLine={false}
                    label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                    outerRadius={100}
                    fill="#8884d8"
                    dataKey="value"
                  >
                    {issueTypeStats.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                    ))}
                  </Pie>
                  <Tooltip />
                </PieChart>
              </ResponsiveContainer>
            </div>
          </Card>
        </TabsContent>

        {/* 在线协同 */}
        <TabsContent value="collaborate" className="space-y-4">
          {/* 协同说明 */}
          <Card className="p-4 bg-accent border-border">
            <div className="flex items-start gap-2">
              <MessageSquare className="w-5 h-5 text-accent-foreground flex-shrink-0 mt-0.5" />
              <div className="text-sm text-accent-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>
          </Card>

          {/* 活跃协同 */}
          <div className="space-y-4">
            {issues.filter(i => i.discussions.length > 0).map(issue => (
              <Card key={issue.id} className="p-6">
                <div className="flex items-start justify-between mb-4">
                  <div className="flex items-start gap-3">
                    <div className={`p-2 rounded-lg ${getTypeColor(issue.type)}`}>
                      {getTypeIcon(issue.type)}
                    </div>
                    <div>
                      <div className="flex items-center gap-2 mb-1">
                        <h4>{issue.title}</h4>
                        <Badge className={getStatusColor(issue.status)}>
                          {issue.status}
                        </Badge>
                      </div>
                      <p className="text-sm text-muted-foreground">
                        {issue.fieldName} | 参与人数: {new Set(issue.discussions.map(d => d.userId)).size}
                      </p>
                    </div>
                  </div>
                  <Button size="sm" variant="outline" onClick={() => handleViewIssue(issue)}>
                    <Eye className="w-4 h-4 mr-2" />
                    查看全部
                  </Button>
                </div>

                {/* 讨论列表 */}
                <div className="space-y-3">
                  {issue.discussions.slice(0, 2).map(discussion => (
                    <Card key={discussion.id} className={`p-4 border ${getDiscussionTypeColor(discussion.type)}`}>
                      <div className="flex items-start gap-3">
                        <div className="w-10 h-10 bg-primary/10 rounded-full flex items-center justify-center flex-shrink-0">
                          <User className="w-5 h-5 text-primary" />
                        </div>
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-2">
                            <span className="font-medium">{discussion.userName}</span>
                            <Badge variant="outline" className="text-xs">
                              {discussion.userRole}
                            </Badge>
                            <Badge variant="outline" className="text-xs">
                              {discussion.type === 'comment' ? '💬 评论' :
                               discussion.type === 'diagnosis' ? '🔍 诊断' :
                               discussion.type === 'solution' ? '💡 方案' :
                               '❓ 提问'}
                            </Badge>
                            <span className="text-xs text-muted-foreground ml-auto">
                              {discussion.createdAt}
                            </span>
                          </div>
                          <p className="text-sm whitespace-pre-line mb-2">
                            {discussion.content}
                          </p>
                          {discussion.images && discussion.images.length > 0 && (
                            <div className="flex gap-2 mb-2">
                              {discussion.images.map((img, i) => (
                                <div key={i} className="w-20 h-20 bg-muted rounded flex items-center justify-center">
                                  <ImageIcon className="w-8 h-8 text-muted-foreground" />
                                </div>
                              ))}
                            </div>
                          )}
                          <div className="flex items-center gap-4 text-xs text-muted-foreground">
                            <button className="flex items-center gap-1 hover:text-info">
                              <ThumbsUp className="w-3 h-3" />
                              {discussion.likes}
                            </button>
                            <button className="flex items-center gap-1 hover:text-info">
                              <Reply className="w-3 h-3" />
                              回复 {discussion.replies?.length || 0}
                            </button>
                          </div>

                          {/* 回复列表 */}
                          {discussion.replies && discussion.replies.length > 0 && (
                            <div className="mt-3 pl-4 border-l-2 border-border space-y-2">
                              {discussion.replies.map(reply => (
                                <div key={reply.id} className="text-sm">
                                  <span className="font-medium">{reply.userName}</span>
                                  <span className="text-muted-foreground">: {reply.content}</span>
                                  <span className="text-xs text-muted-foreground ml-2">
                                    {reply.createdAt}
                                  </span>
                                </div>
                              ))}
                            </div>
                          )}
                        </div>
                      </div>
                    </Card>
                  ))}
                </div>

                {/* 已完成问题显示解决信息 */}
                {(issue.status === '已解决' || issue.status === '已关闭') && issue.resolverName && issue.resolvedAt && (
                  <div className="mt-4 p-3 bg-success-muted border border-success/30 rounded-lg">
                    <div className="flex items-center gap-4 text-sm">
                      <div className="flex items-center gap-2 text-success">
                        <CheckCircle2 className="w-4 h-4" />
                        <span>解决人: <strong>{issue.resolverName}</strong></span>
                      </div>
                      <div className="flex items-center gap-2 text-success">
                        <Clock className="w-4 h-4" />
                        <span>解决时间: <strong>{issue.resolvedAt}</strong></span>
                      </div>
                    </div>
                  </div>
                )}

                {issue.discussions.length > 2 && (
                  <div className="text-center mt-3">
                    <Button size="sm" variant="outline" onClick={() => handleViewIssue(issue)}>
                      查看全部 {issue.discussions.length} 条讨论
                    </Button>
                  </div>
                )}
              </Card>
            ))}
          </div>
        </TabsContent>
      </Tabs>

      {/* 创建问题对话框 */}
      <Dialog open={showIssueDialog} onOpenChange={setShowIssueDialog}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>上报问题</DialogTitle>
            <DialogDescription>
              详细描述田间问题，系统将自动分派给相应责任人
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label>问题标题</label>
                <Input placeholder="简要描述问题" className="mt-2" />
              </div>
              <div>
                <label>问题类型</label>
                <Select>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="选择类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="病虫害">病虫害</SelectItem>
                    <SelectItem value="设备故障">设备故障</SelectItem>
                    <SelectItem value="灌溉问题">灌溉问题</SelectItem>
                    <SelectItem value="施肥问题">施肥问题</SelectItem>
                    <SelectItem value="其他">其他</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label>严重程度</label>
                <Select>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="选择程度" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="低">低</SelectItem>
                    <SelectItem value="中">中</SelectItem>
                    <SelectItem value="高">高</SelectItem>
                    <SelectItem value="紧急">紧急</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <label>所在地块</label>
                <Select>
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="选择地块" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="field-1">东区1号地</SelectItem>
                    <SelectItem value="field-2">西区2号地</SelectItem>
                    <SelectItem value="field-3">南区3号地</SelectItem>
                    <SelectItem value="field-4">北区4号地</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div>
              <label>问题描述</label>
              <Textarea
                placeholder="详细描述问题的具体情况..."
                className="mt-2"
                rows={5}
              />
            </div>

            <div>
              <label>现场照片</label>
              <div className="mt-2">
                <Button variant="outline" className="w-full">
                  <Camera className="w-4 h-4 mr-2" />
                  上传照片
                </Button>
              </div>
            </div>

            <Card className="p-3 bg-muted">
              <p className="text-xs text-muted-foreground mb-2">自动附带信息:</p>
              <div className="space-y-1 text-xs">
                <p>• 上报人: 张三</p>
                <p>• 联系方式: 13800138001</p>
                <p>• 上报时间: {new Date().toLocaleString('zh-CN')}</p>
                <p>• GPS位置: 东经120.15°, 北纬30.25°</p>
              </div>
            </Card>

            <div className="flex gap-2 justify-end">
              <Button variant="outline" onClick={() => setShowIssueDialog(false)}>
                取消
              </Button>
              <Button className="bg-success hover:bg-success/90">
                <Send className="w-4 h-4 mr-2" />
                提交上报
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 问题详情和协同对话框 */}
      <Dialog open={showDiscussionDialog} onOpenChange={setShowDiscussionDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>问题详情与协同</DialogTitle>
            <DialogDescription>
              查看问题详情，参与在线协同讨论
            </DialogDescription>
          </DialogHeader>
          {selectedIssue && (
            <div className="space-y-4">
              {/* 问题基本信息 */}
              <Card className="p-4 bg-muted">
                <div className="flex items-start gap-3 mb-3">
                  <div className={`p-2 rounded-lg ${getTypeColor(selectedIssue.type)}`}>
                    {getTypeIcon(selectedIssue.type)}
                  </div>
                  <div className="flex-1">
                    <div className="flex items-center gap-2 mb-1">
                      <h4>{selectedIssue.title}</h4>
                      <Badge className={getStatusColor(selectedIssue.status)}>
                        {selectedIssue.status}
                      </Badge>
                      <Badge className={getSeverityColor(selectedIssue.severity)}>
                        {selectedIssue.severity}
                      </Badge>
                    </div>
                    <p className="text-sm text-muted-foreground">
                      {selectedIssue.fieldName} | 上报人: {selectedIssue.reporterName}
                    </p>
                  </div>
                </div>
                <p className="text-sm mb-3">{selectedIssue.description}</p>
                
                {/* 解决信息 - 仅在已解决或已关闭时显示 */}
                {(selectedIssue.status === '已解决' || selectedIssue.status === '已关闭') && selectedIssue.resolverName && selectedIssue.resolvedAt && (
                  <div className="mb-3 p-4 bg-success-muted border border-success/30 rounded-lg space-y-3">
                    <div className="flex items-center gap-4 text-sm">
                      <div className="flex items-center gap-2 text-success">
                        <CheckCircle2 className="w-4 h-4" />
                        <span>解决人: <strong>{selectedIssue.resolverName}</strong></span>
                      </div>
                      <div className="flex items-center gap-2 text-success">
                        <Clock className="w-4 h-4" />
                        <span>解决时间: <strong>{selectedIssue.resolvedAt}</strong></span>
                      </div>
                    </div>
                    {selectedIssue.solution && (
                      <div className="pt-3 border-t border-success/30">
                        <div className="flex items-center gap-2 mb-2">
                          <FileText className="w-4 h-4 text-success" />
                          <span className="text-sm text-success">解决方案：</span>
                        </div>
                        <div className="text-sm text-gray-700 whitespace-pre-line bg-white p-3 rounded border border-green-200">
                          {selectedIssue.solution}
                        </div>
                      </div>
                    )}
                  </div>
                )}
                
                {selectedIssue.photos.length > 0 && (
                  <div className="flex gap-2">
                    {selectedIssue.photos.map((photo, i) => (
                      <div key={i} className="w-24 h-24 bg-gray-200 rounded flex items-center justify-center">
                        <ImageIcon className="w-8 h-8 text-gray-400" />
                      </div>
                    ))}
                  </div>
                )}
              </Card>

              {/* 协作讨论区 */}
              <Card className="p-4">
                <h4 className="mb-3 flex items-center gap-2">
                  <MessageSquare className="w-4 h-4" />
                  协作讨论 ({selectedIssue.discussions.length})
                </h4>
                <div className="space-y-4">
                  {selectedIssue.discussions.map(discussion => (
                    <Card key={discussion.id} className={`p-4 border ${getDiscussionTypeColor(discussion.type)}`}>
                      <div className="flex items-start gap-3">
                        <div className="w-10 h-10 bg-primary/10 rounded-full flex items-center justify-center flex-shrink-0">
                          <User className="w-5 h-5 text-primary" />
                        </div>
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-2">
                            <span className="font-medium">{discussion.userName}</span>
                            <Badge variant="outline" className="text-xs">
                              {discussion.userRole}
                            </Badge>
                            <Badge variant="outline" className="text-xs">
                              {discussion.type === 'comment' ? '💬 评论' :
                               discussion.type === 'diagnosis' ? '🔍 诊断' :
                               discussion.type === 'solution' ? '💡 方案' :
                               '❓ 提问'}
                            </Badge>
                            <span className="text-xs text-muted-foreground ml-auto">
                              {discussion.createdAt}
                            </span>
                          </div>
                          <p className="text-sm whitespace-pre-line mb-2">
                            {discussion.content}
                          </p>
                          {discussion.images && discussion.images.length > 0 && (
                            <div className="flex gap-2 mb-2">
                              {discussion.images.map((img, i) => (
                                <div key={i} className="w-20 h-20 bg-muted rounded flex items-center justify-center">
                                  <ImageIcon className="w-8 h-8 text-muted-foreground" />
                                </div>
                              ))}
                            </div>
                          )}
                          <div className="flex items-center gap-4 text-xs text-muted-foreground">
                            <button className="flex items-center gap-1 hover:text-info">
                              <ThumbsUp className="w-3 h-3" />
                              {discussion.likes}
                            </button>
                            <button className="flex items-center gap-1 hover:text-info">
                              <Reply className="w-3 h-3" />
                              回复
                            </button>
                          </div>
                        </div>
                      </div>
                    </Card>
                  ))}
                </div>

                {/* 发表讨论 */}
                <div className="mt-4 p-4 bg-muted rounded-lg">
                  <div className="mb-3">
                    <Select>
                      <SelectTrigger>
                        <SelectValue placeholder="选择讨论类型" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="comment">💬 评论</SelectItem>
                        <SelectItem value="diagnosis">🔍 诊断意见</SelectItem>
                        <SelectItem value="solution">💡 解决方案</SelectItem>
                        <SelectItem value="question">❓ 提问</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <Textarea
                    placeholder="发表你的意见..."
                    rows={3}
                    className="mb-2"
                  />
                  <div className="flex gap-2">
                    <Button variant="outline" size="sm">
                      <ImageIcon className="w-4 h-4 mr-2" />
                      添加图片
                    </Button>
                    <Button size="sm" className="ml-auto">
                      <Send className="w-4 h-4 mr-2" />
                      发送
                    </Button>
                  </div>
                </div>
              </Card>
              
              {/* 关闭按钮 */}
              <div className="flex justify-end pt-4 border-t">
                <Button
                  variant="outline"
                  onClick={() => setShowDiscussionDialog(false)}
                >
                  关闭
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 手动分派对话框 */}
      <Dialog open={showAssignDialog} onOpenChange={setShowAssignDialog}>
        <DialogContent className="max-w-4xl max-h-[85vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>手动分派问题</DialogTitle>
            <DialogDescription>
              选择合适的人员处理此问题
            </DialogDescription>
          </DialogHeader>

          {issueToAssign && (
            <div className="space-y-4">
              {/* 问题概要 */}
              <Card className="p-4 bg-info-muted border-info/30">
                <div className="flex items-start gap-3">
                  <div className={`p-2 rounded-lg ${getTypeColor(issueToAssign.type)}`}>
                    {getTypeIcon(issueToAssign.type)}
                  </div>
                  <div className="flex-1">
                    <div className="flex items-center gap-2 mb-1">
                      <h4>{issueToAssign.title}</h4>
                      <Badge className={getSeverityColor(issueToAssign.severity)}>
                        {issueToAssign.severity}
                      </Badge>
                    </div>
                    <p className="text-sm text-muted-foreground">
                      {issueToAssign.fieldName} | {issueToAssign.reporterName}
                    </p>
                    <p className="text-sm mt-2">{issueToAssign.description}</p>
                  </div>
                </div>
              </Card>

              {/* 推荐人员 */}
              <div>
                <div className="flex items-center gap-2 mb-3">
                  <Target className="w-5 h-5 text-success" />
                  <h4>系统推荐人员</h4>
                  <Badge variant="outline" className="ml-auto">
                    根据专业匹配度推荐
                  </Badge>
                </div>
                <div className="grid grid-cols-2 gap-3">
                  {staffMembers
                    .filter(staff => staff.specialty === issueToAssign.type)
                    .map(staff => (
                      <Card
                        key={staff.id}
                        className="p-4 hover:shadow-md transition-all cursor-pointer border-2 hover:border-success/30"
                        onClick={() => handleAssignIssue(issueToAssign.id, staff.id, `${staff.name}（${staff.role}）`)}
                      >
                        <div className="flex items-start gap-3">
                          <div className="w-12 h-12 bg-success-muted rounded-full flex items-center justify-center flex-shrink-0">
                            <User className="w-6 h-6 text-success" />
                          </div>
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-2 mb-1">
                              <h4 className="truncate">{staff.name}</h4>
                              <Badge className="bg-success-muted text-success shrink-0">
                                推荐
                              </Badge>
                            </div>
                            <p className="text-sm text-muted-foreground mb-2">{staff.role}</p>
                            <div className="space-y-1 text-xs text-muted-foreground">
                              <p className="flex items-center gap-1">
                                <Settings className="w-3 h-3" />
                                专业: {staff.specialty}
                              </p>
                              <p className="flex items-center gap-1">
                                <Activity className="w-3 h-3" />
                                当前负载: {staff.workload} 个问题
                              </p>
                              <p className="flex items-center gap-1">
                                <ThumbsUp className="w-3 h-3" />
                                评分: {staff.rating} ⭐
                              </p>
                            </div>
                          </div>
                          <Button
                            size="sm"
                            className="shrink-0"
                            onClick={(e) => {
                              e.stopPropagation();
                              handleAssignIssue(issueToAssign.id, staff.id, `${staff.name}（${staff.role}）`);
                            }}
                          >
                            选择
                          </Button>
                        </div>
                      </Card>
                    ))}
                </div>
              </div>

              {/* 所有人员 */}
              <div>
                <div className="flex items-center gap-2 mb-3">
                  <Users className="w-5 h-5 text-muted-foreground" />
                  <h4>全部技术人员</h4>
                  <Badge variant="outline" className="ml-auto">
                    共 {staffMembers.length} 人
                  </Badge>
                </div>
                <div className="grid grid-cols-2 gap-3">
                  {staffMembers
                    .filter(staff => staff.specialty !== issueToAssign.type)
                    .map(staff => (
                      <Card
                        key={staff.id}
                        className="p-4 hover:shadow-md transition-all cursor-pointer border-2 hover:border-info/20"
                        onClick={() => handleAssignIssue(issueToAssign.id, staff.id, `${staff.name}（${staff.role}）`)}
                      >
                        <div className="flex items-start gap-3">
                          <div className="w-12 h-12 bg-muted rounded-full flex items-center justify-center flex-shrink-0">
                            <User className="w-6 h-6 text-muted-foreground" />
                          </div>
                          <div className="flex-1 min-w-0">
                            <h4 className="mb-1 truncate">{staff.name}</h4>
                            <p className="text-sm text-muted-foreground mb-2">{staff.role}</p>
                            <div className="space-y-1 text-xs text-muted-foreground">
                              <p className="flex items-center gap-1">
                                <Settings className="w-3 h-3" />
                                专业: {staff.specialty}
                              </p>
                              <p className="flex items-center gap-1">
                                <Activity className="w-3 h-3" />
                                当前负载: {staff.workload} 个问题
                              </p>
                              <p className="flex items-center gap-1">
                                <ThumbsUp className="w-3 h-3" />
                                评分: {staff.rating} ⭐
                              </p>
                            </div>
                          </div>
                          <Button
                            size="sm"
                            variant="outline"
                            className="shrink-0"
                            onClick={(e) => {
                              e.stopPropagation();
                              handleAssignIssue(issueToAssign.id, staff.id, `${staff.name}（${staff.role}）`);
                            }}
                          >
                            选择
                          </Button>
                        </div>
                      </Card>
                    ))}
                </div>
              </div>

              <div className="flex justify-end gap-2 pt-4 border-t">
                <Button variant="outline" onClick={() => {
                  setShowAssignDialog(false);
                  setIssueToAssign(null);
                }}>
                  取消
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 解决方案输入对话框 */}
      <Dialog open={showResolveDialog} onOpenChange={setShowResolveDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <CheckCircle2 className="w-5 h-5 text-success" />
              标记问题已解决
            </DialogTitle>
            <DialogDescription>
              请输入问题的解决方案，以便后续知识沉淀和经验分享
            </DialogDescription>
          </DialogHeader>

          {issueToResolve && (
            <div className="space-y-4">
              {/* 问题概要 */}
              <Card className="p-4 bg-success-muted border-success/30">
                <div className="flex items-start gap-3">
                  <div className={`p-2 rounded-lg ${getTypeColor(issueToResolve.type)}`}>
                    {getTypeIcon(issueToResolve.type)}
                  </div>
                  <div className="flex-1">
                    <div className="flex items-center gap-2 mb-1">
                      <h4>{issueToResolve.title}</h4>
                      <Badge className={getSeverityColor(issueToResolve.severity)}>
                        {issueToResolve.severity}
                      </Badge>
                    </div>
                    <p className="text-sm text-muted-foreground">
                      {issueToResolve.fieldName} | {issueToResolve.reporterName}
                    </p>
                    <p className="text-sm mt-2">{issueToResolve.description}</p>
                  </div>
                </div>
              </Card>

              {/* 解决方案输入 */}
              <div className="space-y-2">
                <label className="flex items-center gap-2">
                  <FileText className="w-4 h-4 text-green-600" />
                  解决方案 <span className="text-destructive">*</span>
                </label>
                <Textarea
                  value={solutionText}
                  onChange={(e) => setSolutionText(e.target.value)}
                  placeholder={`请详细描述问题的解决方案，包括：\n1. 问题原因分析\n2. 采取的解决措施\n3. 处理结果\n4. 预防建议（可选）`}
                  className="min-h-[200px] resize-none"
                />
                <p className="text-xs text-muted-foreground">
                  提示：详细的解决方案将自动录入知识库，为后续类似问题提供参考
                </p>
              </div>

              {/* 操作按钮 */}
              <div className="flex justify-end gap-2 pt-4 border-t">
                <Button 
                  variant="outline" 
                  onClick={() => {
                    setShowResolveDialog(false);
                    setIssueToResolve(null);
                    setSolutionText('');
                  }}
                >
                  取消
                </Button>
                <Button 
                  onClick={handleConfirmResolve}
                >
                  <CheckCircle2 className="w-4 h-4 mr-2" />
                  确认解决
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
