import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Badge } from '../ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '../ui/dialog';
import { Label } from '../ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Checkbox } from '../ui/checkbox';
import { Textarea } from '../ui/textarea';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { Employee, Role, AuditStatusType } from '../../types/user-management';
import { Department } from '../../types/department';
import { Search, Plus, Edit, Trash2, Lock, Eye, UserX, UserCheck, CheckCircle, XCircle } from 'lucide-react';
import { toast } from 'sonner@2.0.3';

export function EmployeeManagement() {
  const [employees, setEmployees] = useState<Employee[]>([]);
  const [roles, setRoles] = useState<Role[]>([]);
  const [departments, setDepartments] = useState<Department[]>([]);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [auditStatusFilter, setAuditStatusFilter] = useState<string>('all');
  const [showForm, setShowForm] = useState(false);
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [showAuditDialog, setShowAuditDialog] = useState(false);
  const [editingEmployee, setEditingEmployee] = useState<Employee | null>(null);
  const [selectedEmployee, setSelectedEmployee] = useState<Employee | null>(null);
  const [auditingEmployee, setAuditingEmployee] = useState<Employee | null>(null);
  const [auditAction, setAuditAction] = useState<'approve' | 'reject'>('approve');
  const [auditReason, setAuditReason] = useState('');
  const [formData, setFormData] = useState<Partial<Employee>>({
    enterpriseId: 'ent-2',
    enterpriseName: '丰收现代农业集团',
    status: 'active',
    auditStatus: 'pending',
    roleIds: [],
    idCard: '',
    address: '',
  });

  useEffect(() => {
    loadEmployees();
    loadRoles();
    loadDepartments();
  }, []);

  const loadRoles = () => {
    const data = localStorage.getItem('smart_agriculture_roles');
    if (data) {
      setRoles(JSON.parse(data));
    } else {
      // 初始化角色示例数据
      const mockRoles: Role[] = [
        {
          id: 'role-1',
          code: 'SUPER_ADMIN',
          name: '超级管理员',
          description: '系统最高权限，可管理所有功能和数据',
          permissions: [],
          status: 'active',
          createdAt: '2024-01-01T08:00:00',
          updatedAt: '2024-01-01T08:00:00',
        },
        {
          id: 'role-2',
          code: 'ENTERPRISE_ADMIN',
          name: '企业管理员',
          description: '管理本企业的所有业务和员工',
          permissions: [],
          status: 'active',
          createdAt: '2024-01-01T08:00:00',
          updatedAt: '2024-01-01T08:00:00',
        },
        {
          id: 'role-3',
          code: 'OPERATOR',
          name: '操作员',
          description: '执行日常生产作业任务',
          permissions: [],
          status: 'active',
          createdAt: '2024-01-01T08:00:00',
          updatedAt: '2024-01-01T08:00:00',
        },
        {
          id: 'role-4',
          code: 'VIEWER',
          name: '查看者',
          description: '只能查看数据，不能修改',
          permissions: [],
          status: 'active',
          createdAt: '2024-01-01T08:00:00',
          updatedAt: '2024-01-01T08:00:00',
        },
        {
          id: 'role-5',
          code: 'TECHNICIAN',
          name: '技术员',
          description: '负责技术支持和设备维护',
          permissions: [],
          status: 'active',
          createdAt: '2024-01-01T08:00:00',
          updatedAt: '2024-01-01T08:00:00',
        },
      ];
      localStorage.setItem('smart_agriculture_roles', JSON.stringify(mockRoles));
      setRoles(mockRoles);
    }
  };

  const loadDepartments = () => {
    const data = localStorage.getItem('smart_agriculture_departments');
    if (data) {
      setDepartments(JSON.parse(data));
    }
  };

  // 获取所有部门（包括子部门）的扁平列表
  const getAllDepartments = (depts: Department[]): Department[] => {
    const result: Department[] = [];
    const traverse = (items: Department[]) => {
      items.forEach(item => {
        result.push(item);
        if (item.children) {
          traverse(item.children);
        }
      });
    };
    traverse(depts);
    return result.filter(d => d.status === 'active');
  };

  const allDepartments = getAllDepartments(departments);

  const loadEmployees = () => {
    const data = localStorage.getItem('smart_agriculture_employees');
    if (data) {
      setEmployees(JSON.parse(data));
    } else {
      // 初始化示例数据
      const mockEmployees: Employee[] = [
        {
          id: 'emp-1',
          enterpriseId: 'ent-2',
          enterpriseName: '丰收现代农业集团',
          username: 'zhangsan',
          name: '张三',
          phone: '13800138001',
          email: 'zhangsan@example.com',
          department: '技术部',
          idCard: '330108199001011234',
          address: '浙江省杭州市余杭区',
          roleIds: ['role-3', 'role-5'],
          roles: ['操作员', '技术员'],
          status: 'active',
          auditStatus: 'approved',
          auditTime: '2024-10-01T09:00:00',
          auditor: '管理员',
          createdAt: '2024-10-01T08:00:00',
          updatedAt: '2024-10-01T08:00:00',
          lastLoginTime: '2024-10-27T09:30:00',
        },
        {
          id: 'emp-2',
          enterpriseId: 'ent-2',
          enterpriseName: '丰收现代农业集团',
          username: 'lisi',
          name: '李四',
          phone: '13900139002',
          email: 'lisi@example.com',
          department: '管理部',
          idCard: '330108198505052345',
          address: '浙江省杭州市西湖区',
          roleIds: ['role-2'],
          roles: ['企业管理员'],
          status: 'active',
          auditStatus: 'pending',
          createdAt: '2024-10-02T10:00:00',
          updatedAt: '2024-10-02T10:00:00',
        },
        {
          id: 'emp-3',
          enterpriseId: 'ent-2',
          enterpriseName: '丰收现代农业集团',
          username: 'wangwu',
          name: '王五',
          phone: '13700137003',
          department: '维修部',
          idCard: '330108199203153456',
          address: '浙江省杭州市萧山区',
          roleIds: ['role-3'],
          roles: ['操作员'],
          status: 'frozen',
          auditStatus: 'rejected',
          auditReason: '资质不符合要求',
          auditTime: '2024-10-10T16:00:00',
          auditor: '管理员',
          createdAt: '2024-09-28T14:00:00',
          updatedAt: '2024-10-10T16:00:00',
        },
        {
          id: 'emp-4',
          enterpriseId: 'ent-2',
          enterpriseName: '丰收现代农业集团',
          username: 'zhaoliu',
          name: '赵六',
          phone: '13600136004',
          email: 'zhaoliu@example.com',
          department: '技术部',
          roleIds: ['role-4'],
          roles: ['查看者'],
          status: 'active',
          auditStatus: 'approved',
          auditTime: '2024-10-15T14:20:00',
          auditor: '管理员',
          createdAt: '2024-10-15T14:00:00',
          updatedAt: '2024-10-15T14:00:00',
          lastLoginTime: '2024-10-26T16:45:00',
        },
      ];
      localStorage.setItem('smart_agriculture_employees', JSON.stringify(mockEmployees));
      setEmployees(mockEmployees);
    }
  };

  const filteredEmployees = employees.filter(emp => {
    const matchKeyword = !searchKeyword ||
      emp.name.includes(searchKeyword) ||
      emp.username.includes(searchKeyword) ||
      emp.phone.includes(searchKeyword) ||
      (emp.department && emp.department.includes(searchKeyword));

    const matchStatus = statusFilter === 'all' || emp.status === statusFilter;
    const matchAuditStatus = auditStatusFilter === 'all' || emp.auditStatus === auditStatusFilter;

    return matchKeyword && matchStatus && matchAuditStatus;
  });

  const handleAdd = () => {
    setEditingEmployee(null);
    setFormData({
      enterpriseId: 'ent-2',
      enterpriseName: '丰收现代农业集团',
      status: 'active',
      auditStatus: 'pending',
      roleIds: [],
      idCard: '',
      address: '',
    });
    setShowForm(true);
  };

  const handleEdit = (employee: Employee) => {
    setEditingEmployee(employee);
    setFormData(employee);
    setShowForm(true);
  };

  const handleSave = () => {
    if (!formData.username || !formData.name || !formData.phone) {
      toast.error('请填写必填项');
      return;
    }

    // 身份证格式验证
    if (formData.idCard && !/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/.test(formData.idCard)) {
      toast.error('身份证号格式不正确');
      return;
    }

    // 手机号格式验证
    if (!/^1[3456789]\d{9}$/.test(formData.phone)) {
      toast.error('手机号格式不正确');
      return;
    }

    // 验证角色选择
    if (!formData.roleIds || formData.roleIds.length === 0) {
      toast.error('请至少选择一个角色');
      return;
    }

    // 根据角色ID设置角色名称
    const selectedRoles = roles.filter(r => formData.roleIds?.includes(r.id));
    const roleNames = selectedRoles.map(r => r.name);

    if (editingEmployee) {
      // 更新
      const updated = employees.map(emp =>
        emp.id === editingEmployee.id
          ? {
              ...emp,
              ...formData,
              roles: roleNames,
              updatedAt: new Date().toISOString(),
            }
          : emp
      );
      setEmployees(updated);
      localStorage.setItem('smart_agriculture_employees', JSON.stringify(updated));
      toast.success('员工信息更新成功');
    } else {
      // 新增
      const newEmployee: Employee = {
        id: `emp-${Date.now()}`,
        ...formData as Employee,
        roles: roleNames,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };
      const updated = [...employees, newEmployee];
      setEmployees(updated);
      localStorage.setItem('smart_agriculture_employees', JSON.stringify(updated));
      toast.success('员工添加成功');
    }

    setShowForm(false);
  };

  const handleDelete = (id: string) => {
    if (!confirm('确定要删除该员工吗？')) return;

    const updated = employees.filter(emp => emp.id !== id);
    setEmployees(updated);
    localStorage.setItem('smart_agriculture_employees', JSON.stringify(updated));
    toast.success('员工删除成功');
  };

  const handleToggleStatus = (employee: Employee) => {
    const newStatus = employee.status === 'active' ? 'frozen' : 'active';
    const updated = employees.map(emp =>
      emp.id === employee.id
        ? { ...emp, status: newStatus, updatedAt: new Date().toISOString() }
        : emp
    );
    setEmployees(updated);
    localStorage.setItem('smart_agriculture_employees', JSON.stringify(updated));
    toast.success(newStatus === 'active' ? '账户已激活' : '账户已冻结');
  };

  const handleResetPassword = (employee: Employee) => {
    if (!confirm(`确定要重置 ${employee.name} 的密码吗？`)) return;
    toast.success('密码已重置为：123456');
  };

  const handleViewDetail = (employee: Employee) => {
    setSelectedEmployee(employee);
    setShowDetailDialog(true);
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'active':
        return <Badge className="bg-success-muted text-success-muted-foreground">正常</Badge>;
      case 'frozen':
        return <Badge className="bg-muted text-muted-foreground">已冻结</Badge>;
      case 'inactive':
        return <Badge className="bg-error-muted text-error-muted-foreground">停用</Badge>;
      default:
        return <Badge>{status}</Badge>;
    }
  };

  const getAuditStatusBadge = (auditStatus: AuditStatusType) => {
    switch (auditStatus) {
      case 'pending':
        return <Badge className="bg-warning-muted text-warning-muted-foreground">待审核</Badge>;
      case 'approved':
        return <Badge className="bg-success-muted text-success-muted-foreground">审核通过</Badge>;
      case 'rejected':
        return <Badge className="bg-error-muted text-error-muted-foreground">已驳回</Badge>;
      default:
        return <Badge>{auditStatus}</Badge>;
    }
  };

  const handleAudit = (employee: Employee, action: 'approve' | 'reject') => {
    setAuditingEmployee(employee);
    setAuditAction(action);
    setAuditReason('');
    setShowAuditDialog(true);
  };

  const handleAuditSubmit = () => {
    if (!auditingEmployee) return;

    if (auditAction === 'reject' && !auditReason.trim()) {
      toast.error('请填写驳回原因');
      return;
    }

    const now = new Date().toISOString();
    const updated = employees.map(emp =>
      emp.id === auditingEmployee.id
        ? {
            ...emp,
            auditStatus: auditAction === 'approve' ? 'approved' as AuditStatusType : 'rejected' as AuditStatusType,
            auditReason: auditAction === 'reject' ? auditReason : undefined,
            auditTime: now,
            auditor: '当前用户', // 实际应用中应该从登录信息获取
            updatedAt: now,
          }
        : emp
    );

    setEmployees(updated);
    localStorage.setItem('smart_agriculture_employees', JSON.stringify(updated));
    toast.success(auditAction === 'approve' ? '审核通过' : '已驳回');
    setShowAuditDialog(false);
    setAuditingEmployee(null);
    setAuditReason('');
  };

  const stats = [
    {
      label: '总员工数',
      value: employees.length,
      color: 'text-info',
      bg: 'bg-info-muted',
      icon: '📊',
    },
    {
      label: '待审核',
      value: employees.filter(e => e.auditStatus === 'pending').length,
      color: 'text-warning',
      bg: 'bg-warning-muted',
      icon: '⏳',
    },
    {
      label: '审核通过',
      value: employees.filter(e => e.auditStatus === 'approved').length,
      color: 'text-green-600 dark:text-green-400',
      bg: 'bg-green-50 dark:bg-green-100',
      icon: '✅',
    },
    {
      label: '已驳回',
      value: employees.filter(e => e.auditStatus === 'rejected').length,
      color: 'text-red-600 dark:text-red-400',
      bg: 'bg-red-50 dark:bg-red-100',
      icon: '❌',
    },
  ];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">员工管理</h2>
          <p className="text-muted-foreground">管理本企业员工账户体系</p>
        </div>
        <Button onClick={handleAdd}>
          <Plus className="w-4 h-4 mr-2" />
          添加员工
        </Button>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-4 gap-4">
        {stats.map((stat, index) => (
          <Card key={index} className={`p-4 ${stat.bg} border-none`}>
            <div className="flex items-center justify-between">
              <div>
                <div className="text-sm text-muted-foreground">{stat.label}</div>
                <div className={`mt-2 ${stat.color}`}>{stat.value}</div>
              </div>
              <div className="text-2xl">{stat.icon}</div>
            </div>
          </Card>
        ))}
      </div>

      {/* 搜索和筛选 */}
      <Card className="p-4">
        <div className="flex gap-4">
          <div className="flex-1">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
              <Input
                placeholder="搜索员工姓名、用户名、电话、部门..."
                value={searchKeyword}
                onChange={(e) => setSearchKeyword(e.target.value)}
                className="pl-10"
              />
            </div>
          </div>
          <Select value={statusFilter} onValueChange={setStatusFilter}>
            <SelectTrigger className="w-40">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部状态</SelectItem>
              <SelectItem value="active">正常</SelectItem>
              <SelectItem value="frozen">已冻结</SelectItem>
            </SelectContent>
          </Select>
          <Select value={auditStatusFilter} onValueChange={setAuditStatusFilter}>
            <SelectTrigger className="w-40">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部审核</SelectItem>
              <SelectItem value="pending">待审核</SelectItem>
              <SelectItem value="approved">审核通过</SelectItem>
              <SelectItem value="rejected">已驳回</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </Card>

      {/* 员工列表 */}
      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>姓名</TableHead>
              <TableHead>用户名</TableHead>
              <TableHead>电话</TableHead>
              <TableHead>部门</TableHead>
              <TableHead>角色</TableHead>
              <TableHead>账号状态</TableHead>
              <TableHead>审核状态</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredEmployees.length === 0 ? (
              <TableRow>
                <TableCell colSpan={8} className="text-center text-muted-foreground py-8">
                  暂无数据
                </TableCell>
              </TableRow>
            ) : (
              filteredEmployees.map((employee) => (
                <TableRow key={employee.id}>
                  <TableCell>{employee.name}</TableCell>
                  <TableCell className="text-muted-foreground">{employee.username}</TableCell>
                  <TableCell>{employee.phone}</TableCell>
                  <TableCell className="text-muted-foreground">{employee.department || '-'}</TableCell>
                  <TableCell>
                    {employee.roles && employee.roles.length > 0
                      ? employee.roles.join(', ')
                      : '-'}
                  </TableCell>
                  <TableCell>{getStatusBadge(employee.status)}</TableCell>
                  <TableCell>{getAuditStatusBadge(employee.auditStatus)}</TableCell>
                  <TableCell>
                    <div className="flex gap-1">
                      {employee.auditStatus === 'pending' ? (
                        <>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleAudit(employee, 'approve')}
                            title="审核通过"
                          >
                            <CheckCircle className="w-4 h-4 text-green-600 dark:text-green-400" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleAudit(employee, 'reject')}
                            title="驳回"
                          >
                            <XCircle className="w-4 h-4 text-red-600 dark:text-red-400" />
                          </Button>
                        </>
                      ) : null}
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleViewDetail(employee)}
                      >
                        <Eye className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleEdit(employee)}
                      >
                        <Edit className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleResetPassword(employee)}
                      >
                        <Lock className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleToggleStatus(employee)}
                      >
                        {employee.status === 'active' ? (
                          <UserX className="w-4 h-4 text-orange-600 dark:text-orange-400" />
                        ) : (
                          <UserCheck className="w-4 h-4 text-green-600 dark:text-green-400" />
                        )}
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleDelete(employee.id)}
                      >
                        <Trash2 className="w-4 h-4 text-destructive" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </Card>

      {/* 添加/编辑表单 */}
      <Dialog open={showForm} onOpenChange={setShowForm}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>{editingEmployee ? '编辑员工' : '添加员工'}</DialogTitle>
            <DialogDescription className="sr-only">
              {editingEmployee ? '编辑员工信息' : '添加新员工'}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 max-h-96 overflow-y-auto">
            {/* 基本信息 */}
            <div>
              <h4 className="mb-3 text-green-800">基本信息</h4>
              <div className="grid grid-cols-2 gap-4">
              <div>
                <Label htmlFor="username">用户名 *</Label>
                <Input
                  id="username"
                  value={formData.username || ''}
                  onChange={(e) => setFormData({ ...formData, username: e.target.value })}
                  placeholder="登录用户名"
                />
              </div>
              <div>
                <Label htmlFor="name">姓名 *</Label>
                <Input
                  id="name"
                  value={formData.name || ''}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="真实姓名"
                />
              </div>
              <div>
                <Label htmlFor="phone">手机号 *</Label>
                <Input
                  id="phone"
                  value={formData.phone || ''}
                  onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                  placeholder="11位手机号码"
                />
              </div>
              <div>
                <Label htmlFor="email">邮箱</Label>
                <Input
                  id="email"
                  type="email"
                  value={formData.email || ''}
                  onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                  placeholder="电子邮箱"
                />
              </div>
              <div>
                <Label htmlFor="idCard">身份证号</Label>
                <Input
                  id="idCard"
                  value={formData.idCard || ''}
                  onChange={(e) => setFormData({ ...formData, idCard: e.target.value })}
                  placeholder="18位身份证号码"
                />
              </div>
              <div>
                <Label htmlFor="address">住址</Label>
                <Input
                  id="address"
                  value={formData.address || ''}
                  onChange={(e) => setFormData({ ...formData, address: e.target.value })}
                  placeholder="详细住址"
                />
              </div>
            </div>
            </div>

            {/* 工作信息 */}
            <div>
              <h4 className="mb-3 text-green-800 dark:text-green-400">工作信息</h4>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="department">部门</Label>
                  <Select value={formData.department || ''} onValueChange={(value) => setFormData({ ...formData, department: value })}>
                    <SelectTrigger>
                      <SelectValue placeholder="选择部门" />
                    </SelectTrigger>
                    <SelectContent>
                      {allDepartments.length > 0 ? (
                        allDepartments.map(dept => (
                          <SelectItem key={dept.id} value={dept.name}>
                            {dept.level === 2 ? `　├ ${dept.name}` : dept.name}
                          </SelectItem>
                        ))
                      ) : (
                        <SelectItem value="暂无部门" disabled>暂无部门数据，请先在部门管理中添加</SelectItem>
                      )}
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </div>

            {/* 角色选择 */}
            <div>
              <Label>角色配置 *</Label>
              <Card className="mt-2 p-4 bg-gray-50">
                <div className="grid grid-cols-2 gap-3">
                  {roles
                    .filter(role => role.status === 'active')
                    .map((role) => (
                      <div key={role.id} className="flex items-start gap-2">
                        <Checkbox
                          id={`role-${role.id}`}
                          checked={formData.roleIds?.includes(role.id) || false}
                          onCheckedChange={(checked) => {
                            if (checked) {
                              setFormData({
                                ...formData,
                                roleIds: [...(formData.roleIds || []), role.id],
                              });
                            } else {
                              setFormData({
                                ...formData,
                                roleIds: (formData.roleIds || []).filter(id => id !== role.id),
                              });
                            }
                          }}
                        />
                        <div className="flex-1">
                          <Label htmlFor={`role-${role.id}`} className="cursor-pointer text-foreground">
                            {role.name}
                          </Label>
                          {role.description && (
                            <p className="text-xs text-muted-foreground mt-0.5">
                              {role.description}
                            </p>
                          )}
                        </div>
                      </div>
                    ))}
                </div>
                {roles.filter(r => r.status === 'active').length === 0 && (
                  <p className="text-sm text-muted-foreground text-center py-2">
                    暂无可用角色，请先在角色管理中创建角色
                  </p>
                )}
              </Card>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowForm(false)}>
              取消
            </Button>
            <Button onClick={handleSave}>保存</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 详情对话框 */}
      <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>员工详情</DialogTitle>
            <DialogDescription className="sr-only">
              查看员工的详细信息
            </DialogDescription>
          </DialogHeader>
          {selectedEmployee && (
            <div className="space-y-4 max-h-96 overflow-y-auto">
              {/* 基本信息 */}
              <div>
                <h4 className="mb-3 text-green-800">基本信息</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>姓名</Label>
                    <div className="mt-1 field-value-inline">{selectedEmployee.name}</div>
                  </div>
                  <div>
                    <Label>用户名</Label>
                    <div className="mt-1 field-value-inline">{selectedEmployee.username}</div>
                  </div>
                  <div>
                    <Label>手机号</Label>
                    <div className="mt-1 field-value-inline">{selectedEmployee.phone}</div>
                  </div>
                  <div>
                    <Label>邮箱</Label>
                    <div className="mt-1 field-value-inline">{selectedEmployee.email || '-'}</div>
                  </div>
                  <div>
                    <Label>身份证号</Label>
                    <div className="mt-1 field-value-inline">{selectedEmployee.idCard || '-'}</div>
                  </div>
                  <div>
                    <Label>住址</Label>
                    <div className="mt-1 field-value-inline">{selectedEmployee.address || '-'}</div>
                  </div>
                </div>
              </div>

              {/* 工作信息 */}
              <div>
                <h4 className="mb-3 text-green-800 dark:text-green-400">工作信息</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>部门</Label>
                    <div className="mt-1 field-value-inline">{selectedEmployee.department || '-'}</div>
                  </div>
                  <div>
                    <Label>账号状态</Label>
                    <div className="mt-1">{getStatusBadge(selectedEmployee.status)}</div>
                  </div>
                  <div>
                    <Label>审核状态</Label>
                    <div className="mt-1">{getAuditStatusBadge(selectedEmployee.auditStatus)}</div>
                  </div>
                  {selectedEmployee.auditReason && (
                    <div>
                      <Label>审核意见</Label>
                      <div className="mt-1 field-value-inline">{selectedEmployee.auditReason}</div>
                    </div>
                  )}
                  {selectedEmployee.auditor && (
                    <div>
                      <Label>审核人</Label>
                      <div className="mt-1 field-value-inline">{selectedEmployee.auditor}</div>
                    </div>
                  )}
                  {selectedEmployee.auditTime && (
                    <div>
                      <Label>审核时间</Label>
                      <div className="mt-1 field-value-inline">{new Date(selectedEmployee.auditTime).toLocaleString('zh-CN')}</div>
                    </div>
                  )}
                </div>
              </div>

              {/* 角色权限 */}
              <div>
                <h4 className="mb-3 text-green-800 dark:text-green-400">角色权限</h4>
                <div className="flex flex-wrap gap-2">
                  {selectedEmployee.roles && selectedEmployee.roles.length > 0 ? (
                    selectedEmployee.roles.map((role, index) => (
                      <Badge key={index} className="bg-purple-100 text-purple-700 dark:bg-purple-100 dark:text-purple-700">
                        {role}
                      </Badge>
                    ))
                  ) : (
                    <span className="text-muted-foreground">未分配角色</span>
                  )}
                </div>
              </div>

              {/* 系统信息 */}
              <div>
                <h4 className="mb-3 text-green-800">系统信息</h4>
                <div className="grid grid-cols-2 gap-4">
                  {selectedEmployee.lastLoginTime && (
                    <div>
                      <Label>最后登录</Label>
                      <div className="mt-1 field-value-inline">
                        {new Date(selectedEmployee.lastLoginTime).toLocaleString('zh-CN')}
                      </div>
                    </div>
                  )}
                  <div>
                    <Label>创建时间</Label>
                    <div className="mt-1 field-value-inline">
                      {new Date(selectedEmployee.createdAt).toLocaleString('zh-CN')}
                    </div>
                  </div>
                  <div>
                    <Label>更新时间</Label>
                    <div className="mt-1 field-value-inline">
                      {new Date(selectedEmployee.updatedAt).toLocaleString('zh-CN')}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDetailDialog(false)}>
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 审核对话框 */}
      <Dialog open={showAuditDialog} onOpenChange={setShowAuditDialog}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>
              {auditAction === 'approve' ? '审核通过' : '驳回'}
            </DialogTitle>
            <DialogDescription>
              {auditAction === 'approve' 
                ? '确认审核通过该员工吗？' 
                : '请填写驳回原因'}
            </DialogDescription>
          </DialogHeader>
          {auditingEmployee && (
            <div className="space-y-4">
              <div>
                <Label>员工姓名</Label>
                <div className="mt-1 field-value-inline">{auditingEmployee.name}</div>
              </div>
              <div>
                <Label>用户名</Label>
                <div className="mt-1 field-value-inline">{auditingEmployee.username}</div>
              </div>
              <div>
                <Label>手机号</Label>
                <div className="mt-1 field-value-inline">{auditingEmployee.phone}</div>
              </div>
              {auditAction === 'reject' && (
                <div>
                  <Label htmlFor="auditReason">驳回原因 *</Label>
                  <Textarea
                    id="auditReason"
                    value={auditReason}
                    onChange={(e) => setAuditReason(e.target.value)}
                    placeholder="请输入驳回原因..."
                    rows={4}
                  />
                </div>
              )}
              {auditAction === 'approve' && (
                <div>
                  <Label htmlFor="auditRemark">审核意见</Label>
                  <Textarea
                    id="auditRemark"
                    value={auditReason}
                    onChange={(e) => setAuditReason(e.target.value)}
                    placeholder="选填：可以输入审核意见..."
                    rows={3}
                  />
                </div>
              )}
            </div>
          )}
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowAuditDialog(false)}>
              取消
            </Button>
            <Button 
              onClick={handleAuditSubmit}
              className={auditAction === 'reject' ? 'bg-destructive hover:bg-destructive/90' : ''}
            >
              {auditAction === 'approve' ? '确认通过' : '确认驳回'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
