import React, { useState, useEffect } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { Button } from "@d8d/shared-ui-components/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@d8d/shared-ui-components/components/ui/dialog";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@d8d/shared-ui-components/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@d8d/shared-ui-components/components/ui/table";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@d8d/shared-ui-components/components/ui/select";
import { Badge } from "@d8d/shared-ui-components/components/ui/badge";
import { Input } from "@d8d/shared-ui-components/components/ui/input";
import { toast } from "sonner";
import { Users, FileText, Calendar, Play, CheckCircle, X } from "lucide-react";
import {
  OrderStatus,
  WorkStatus,
  getOrderStatusLabel,
  getWorkStatusLabel,
} from "@d8d/allin-enums";
import { orderClientManager } from "../api/orderClient";
import { salaryClientManager } from "@d8d/allin-salary-management-ui";
import { DisabledPersonSelector } from "@d8d/allin-disability-person-management-ui";
import OrderAssetModal from "./OrderAssetModal";
import AttendanceModal from "./AttendanceModal";
import type { DisabledPersonData } from "@d8d/allin-disability-person-management-ui";

interface OrderDetailModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  orderId: number | null;
  onSuccess?: () => void;
}

interface PendingPerson {
  personId: number;
  name: string;
  gender: string;
  disabilityType: string;
  phone: string;
  salaryDetail: number;
  province?: string; // 原系统使用字符串
  city?: string; // 原系统使用字符串
}


const OrderDetailModal: React.FC<OrderDetailModalProps> = ({
  open,
  onOpenChange,
  orderId,
  onSuccess,
}) => {
  const [isPersonSelectorOpen, setIsPersonSelectorOpen] = useState(false);
  const [isAssetAssociationOpen, setIsAssetAssociationOpen] = useState(false);
  const [isAttendanceModalOpen, setIsAttendanceModalOpen] = useState(false);
  const [isActionLoading, setIsActionLoading] = useState(false);
  const [pendingPersons, setPendingPersons] = useState<PendingPerson[]>([]);

  // 查询订单详情
  const {
    data: order,
    isLoading,
    error,
    refetch,
  } = useQuery({
    queryKey: ["orderDetail", orderId],
    queryFn: async () => {
      if (!orderId) return null;
      const response = await orderClientManager.get().detail[":id"].$get({
        param: { id: orderId },
      });
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || "获取订单详情失败");
      }
      return await response.json();
    },
    enabled: open && !!orderId,
  });


  // 激活订单
  const activateMutation = useMutation({
    mutationFn: async (orderId: number) => {
      const response = await orderClientManager
        .get()
        .activate[":orderId"].$post({
          param: { orderId },
        });
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || "激活订单失败");
      }
      return await response.json();
    },
    onSuccess: () => {
      toast.success("订单激活成功");
      refetch();
      onSuccess?.();
    },
    onError: (error) => {
      toast.error(error.message || "激活订单失败");
    },
  });

  // 关闭订单
  const closeMutation = useMutation({
    mutationFn: async (orderId: number) => {
      const response = await orderClientManager.get().close[":orderId"].$post({
        param: { orderId },
      });
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || "关闭订单失败");
      }
      return await response.json();
    },
    onSuccess: () => {
      toast.success("订单关闭成功");
      refetch();
      onSuccess?.();
    },
    onError: (error) => {
      toast.error(error.message || "关闭订单失败");
    },
  });

  // 更新人员工作状态
  const updateWorkStatusMutation = useMutation({
    mutationFn: async ({
      orderId,
      personId,
      workStatus,
    }: {
      orderId: number;
      personId: number;
      workStatus: WorkStatus;
    }) => {
      const orderClient = orderClientManager.get();
      const response = await orderClient.persons['work-status'].$put({
        json: { orderId, personId, workStatus }
      });

      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.message || "更新工作状态失败");
      }

      return await response.json();
    },
    onSuccess: () => {
      toast.success("工作状态更新成功");
      refetch();
    },
    onError: (error) => {
      toast.error(error.message || "工作状态更新失败");
    },
  });

  // 批量添加人员
  const batchAddPersonsMutation = useMutation({
    mutationFn: async (persons: PendingPerson[]) => {
      if (!orderId) throw new Error("订单ID不能为空");

      const batchData = {
        persons: persons.map(person => ({
          personId: person.personId,
          joinDate: new Date().toISOString().split('T')[0], // 当前日期，格式：YYYY-MM-DD
          salaryDetail: person.salaryDetail,
          workStatus: WorkStatus.NOT_WORKING, // 默认未入职
        })),
      };

      const response = await orderClientManager.get()[':orderId'].persons.batch.$post({
        param: { orderId },
        json: batchData,
      });

      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.message || "批量添加人员失败");
      }
      return response.json();
    },
    onSuccess: () => {
      toast.success("批量添加人员成功");
      setIsPersonSelectorOpen(false);
      setPendingPersons([]); // 清空待添加列表
      refetch();
      onSuccess?.();
    },
    onError: (error: Error) => {
      toast.error(`批量添加人员失败: ${error.message}`);
    },
  });

  // 模拟薪资查询功能（根据省、市信息查询默认薪资）
  // 支持字符串（原系统格式）和数字ID两种格式
  const getSalaryByLocation = async (province?: string | number, city?: string | number): Promise<number> => {
    try {
      // 获取薪资客户端
      const salaryClient = salaryClientManager.get();

      // 如果province是字符串（汉字），需要转换为ID
      // 这里简化处理，实际应该调用地区服务查询ID
      let provinceId: number | undefined;
      let cityId: number | undefined;

      if (typeof province === 'string') {
        // 简单映射：北京->1, 上海->2, 广州->3, 深圳->4
        const provinceMap: Record<string, number> = {
          '北京': 1, '上海': 2, '广州': 3, '深圳': 4,
          '江苏': 5, '浙江': 6, '广东': 7
        };
        provinceId = provinceMap[province];
      } else if (typeof province === 'number') {
        provinceId = province;
      }

      if (typeof city === 'string') {
        // 简单映射：北京市->2, 上海市->2, 广州市->3, 深圳市->4
        const cityMap: Record<string, number> = {
          '北京市': 2, '上海市': 2, '广州市': 3, '深圳市': 4
        };
        cityId = cityMap[city];
      } else if (typeof city === 'number') {
        cityId = city;
      }

      // 如果有省份ID和城市ID，调用API查询薪资
      if (provinceId && cityId) {
        const response = await salaryClient.byProvinceCity.$get({
          query: { provinceId, cityId }
        });

        if (response.ok) {
          const salaryData = await response.json();
          return salaryData?.totalSalary || 5000; // 返回查询到的总薪资
        }
      }

      // API调用失败或没有ID，使用默认值
      return 5000;
    } catch (error) {
      console.error('查询薪资失败:', error);
      return 5000; // 出错时返回默认值
    }
  };

  // 处理添加人员
  const handleAddPersons = () => {
    if (!orderId) return;
    setIsPersonSelectorOpen(true);
  };

  // 处理残疾人选择 - 将选择的人员添加到待添加列表
  const handlePersonSelect = async (persons: DisabledPersonData | DisabledPersonData[]) => {
    const personsArray = Array.isArray(persons) ? persons : [persons];

    // 获取已绑定人员的ID列表
    const existingPersonIds = (order?.orderPersons || []).map(p => p.personId);
    // 获取待添加人员的ID列表
    const pendingPersonIds = pendingPersons.map(p => p.personId);

    // 使用Promise.all并行查询所有人员的薪资
    const salaryPromises = personsArray.map(async person => {
      // 检查是否已在订单中或已在待添加列表中
      if (existingPersonIds.includes(person.id) || pendingPersonIds.includes(person.id)) {
        // toast.warning(`人员 ${person.name} 已存在，跳过添加`);
        return null;
      }

      // 根据省、市信息查询默认薪资
      // 注意：原系统使用字符串存储省市信息
      const defaultSalary = await getSalaryByLocation(person.province, person.city);

      return {
        personId: person.id,
        name: person.name,
        gender: person.gender,
        disabilityType: person.disabilityType,
        phone: person.phone,
        salaryDetail: defaultSalary,
        province: person.province,
        city: person.city,
      };
    });

    // 等待所有薪资查询完成
    const pendingPersonResults = await Promise.all(salaryPromises);

    // 过滤掉null（已存在的人员）
    const validPendingPersons = pendingPersonResults.filter((p): p is NonNullable<typeof p> => p !== null);

    if (validPendingPersons.length > 0) {
      setPendingPersons(prev => [...prev, ...validPendingPersons]);
      toast.success(`已添加 ${validPendingPersons.length} 名人员到待添加列表`);
    }
  };

  // 处理添加资产
  const handleAddAsset = () => {
    if (!orderId) return;
    setIsAssetAssociationOpen(true);
  };

  // 处理出勤导出
  const handleAttendanceExport = () => {
    if (!orderId || !order) return;
    setIsAttendanceModalOpen(true);
  };

  // 更新待添加人员的薪资
  const updatePendingPersonSalary = (personId: number, salary: number) => {
    setPendingPersons(prev =>
      prev.map(person =>
        person.personId === personId ? { ...person, salaryDetail: salary } : person
      )
    );
  };

  // 从待添加列表中移除人员
  const removePendingPerson = (personId: number) => {
    setPendingPersons(prev => prev.filter(person => person.personId !== personId));
  };

  // 确认添加待添加人员
  const handleConfirmAddPersons = () => {
    if (pendingPersons.length === 0) {
      toast.warning("没有待添加的人员");
      return;
    }

    batchAddPersonsMutation.mutate(pendingPersons);
  };

  // 处理激活订单
  const handleActivateOrder = () => {
    if (!orderId) return;
    setIsActionLoading(true);
    activateMutation.mutate(orderId, {
      onSettled: () => setIsActionLoading(false),
    });
  };

  // 处理关闭订单
  const handleCloseOrder = () => {
    if (!orderId) return;
    setIsActionLoading(true);
    closeMutation.mutate(orderId, {
      onSettled: () => setIsActionLoading(false),
    });
  };

  // 处理更新工作状态
  const handleUpdateWorkStatus = (personId: number, workStatus: WorkStatus) => {
    if (!orderId) return;
    updateWorkStatusMutation.mutate({ orderId, personId, workStatus });
  };

  // 获取订单状态徽章样式
  const getOrderStatusBadge = (status: OrderStatus) => {
    const variants = {
      [OrderStatus.DRAFT]: "secondary",
      [OrderStatus.CONFIRMED]: "default",
      [OrderStatus.IN_PROGRESS]: "default",
      [OrderStatus.COMPLETED]: "outline",
      [OrderStatus.CANCELLED]: "destructive",
    } as const;

    return (
      <Badge variant={variants[status]}>{getOrderStatusLabel(status)}</Badge>
    );
  };

  // 获取工作状态徽章样式
  const getWorkStatusBadge = (status: WorkStatus) => {
    const variants = {
      [WorkStatus.NOT_WORKING]: "secondary",
      [WorkStatus.PRE_WORKING]: "default",
      [WorkStatus.WORKING]: "default",
      [WorkStatus.RESIGNED]: "destructive",
    } as const;

    return (
      <Badge variant={variants[status]}>{getWorkStatusLabel(status)}</Badge>
    );
  };

  // 格式化日期
  const formatDate = (dateString?: string) => {
    if (!dateString) return "-";
    try {
      return new Date(dateString).toLocaleDateString("zh-CN");
    } catch {
      return dateString;
    }
  };

  // 当弹窗关闭时清空待添加人员列表
  useEffect(() => {
    if (!open) {
      setPendingPersons([]);
    }
  }, [open]);

  // 人员列表表格列
  const personColumns = [
    { key: "personId", label: "ID", width: "60px" },
    { key: "person.name", label: "姓名" },
    { key: "person.gender", label: "性别", width: "80px" },
    { key: "person.disabilityType", label: "残疾类型" },
    { key: "person.phone", label: "联系电话" },
    { key: "joinDate", label: "入职日期", width: "120px" },
    { key: "leaveDate", label: "离职日期", width: "120px" },
    { key: "workStatus", label: "工作状态", width: "120px" },
    { key: "salaryDetail", label: "薪资", width: "100px" },
  ];

  return (
    <>
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent
          className="max-w-[95vw] sm:max-w-7xl max-h-[90vh] overflow-y-auto"
          data-testid="order-detail-dialog"
        >
          <DialogHeader>
            <DialogTitle data-testid="order-detail-dialog-title">
              订单详情
            </DialogTitle>
            <DialogDescription data-testid="order-detail-dialog-description">
              查看订单完整信息和管理相关资源
            </DialogDescription>
          </DialogHeader>

          {isLoading ? (
            <div className="py-8 text-center">加载中...</div>
          ) : error ? (
            <div className="py-8 text-center text-destructive">
              加载失败: {error.message}
            </div>
          ) : order ? (
            <div className="space-y-6">
              {/* 订单信息卡片 */}
              <Card>
                <CardHeader>
                  <CardTitle>订单信息</CardTitle>
                  <CardDescription>订单基本信息和状态</CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    <div className="space-y-2">
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-medium">订单ID:</span>
                        <span data-testid="order-detail-id">{order.id}</span>
                      </div>
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-medium">订单名称:</span>
                        <span data-testid="order-detail-name">
                          {order.orderName}
                        </span>
                      </div>
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-medium">平台:</span>
                        <span data-testid="order-detail-platform">
                          平台{order.platformId}
                        </span>
                      </div>
                    </div>
                    <div className="space-y-2">
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-medium">公司:</span>
                        <span data-testid="order-detail-company">
                          公司{order.companyId}
                        </span>
                      </div>
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-medium">渠道:</span>
                        <span data-testid="order-detail-channel">
                          渠道{order.channelId || "-"}
                        </span>
                      </div>
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-medium">订单状态:</span>
                        <span data-testid="order-detail-status">
                          {getOrderStatusBadge(order.orderStatus)}
                        </span>
                      </div>
                    </div>
                    <div className="space-y-2">
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-medium">工作状态:</span>
                        <span data-testid="order-detail-work-status">
                          {getWorkStatusBadge(order.workStatus)}
                        </span>
                      </div>
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-medium">
                          预计开始日期:
                        </span>
                        <span data-testid="order-detail-expected-start">
                          {formatDate(order.expectedStartDate || undefined)}
                        </span>
                      </div>
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-medium">
                          实际开始日期:
                        </span>
                        <span data-testid="order-detail-actual-start">
                          {formatDate(order.actualStartDate || undefined)}
                        </span>
                      </div>
                    </div>
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mt-4">
                    <div className="space-y-2">
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-medium">
                          实际结束日期:
                        </span>
                        <span data-testid="order-detail-actual-end">
                          {formatDate(order.actualEndDate || undefined)}
                        </span>
                      </div>
                    </div>
                    <div className="space-y-2">
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-medium">创建时间:</span>
                        <span data-testid="order-detail-create-time">
                          {formatDate(order.createTime)}
                        </span>
                      </div>
                    </div>
                    <div className="space-y-2">
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-medium">更新时间:</span>
                        <span data-testid="order-detail-update-time">
                          {formatDate(order.updateTime)}
                        </span>
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* 待添加人员列表 */}
              <div data-testid="pending-persons-debug" style={{ display: 'none' }}>
                {JSON.stringify({ length: pendingPersons.length, persons: pendingPersons })}
              </div>
              {pendingPersons.length > 0 ? (
                <Card data-testid="pending-persons-card">
                  <CardHeader>
                    <div className="flex items-center justify-between">
                      <div>
                        <CardTitle>待添加人员列表</CardTitle>
                        <CardDescription>
                          已选择但尚未添加到订单的人员，可编辑薪资后确认添加
                        </CardDescription>
                      </div>
                      <Button
                        onClick={handleConfirmAddPersons}
                        size="sm"
                        disabled={batchAddPersonsMutation.isPending}
                        data-testid="confirm-add-persons-button"
                      >
                        <CheckCircle className="mr-2 h-4 w-4" />
                        确认添加 ({pendingPersons.length})
                      </Button>
                    </div>
                  </CardHeader>
                  <CardContent>
                    <div className="border rounded-md">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead style={{ width: "60px" }}>ID</TableHead>
                            <TableHead>姓名</TableHead>
                            <TableHead style={{ width: "80px" }}>性别</TableHead>
                            <TableHead>残疾类型</TableHead>
                            <TableHead>联系电话</TableHead>
                            <TableHead style={{ width: "120px" }}>薪资（可编辑）</TableHead>
                            <TableHead style={{ width: "80px" }}>操作</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {pendingPersons.map((person) => (
                            <TableRow
                              key={person.personId}
                              data-testid={`pending-person-${person.personId}`}
                            >
                              <TableCell>{person.personId}</TableCell>
                              <TableCell>{person.name}</TableCell>
                              <TableCell>{person.gender}</TableCell>
                              <TableCell>{person.disabilityType}</TableCell>
                              <TableCell>{person.phone}</TableCell>
                              <TableCell>
                                <Input
                                  type="number"
                                  value={person.salaryDetail}
                                  onChange={(e) =>
                                    updatePendingPersonSalary(
                                      person.personId,
                                      parseInt(e.target.value) || 0
                                    )
                                  }
                                  className="w-full"
                                  data-testid={`pending-person-salary-input-${person.personId}`}
                                />
                              </TableCell>
                              <TableCell>
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => removePendingPerson(person.personId)}
                                  data-testid={`remove-pending-person-button-${person.personId}`}
                                >
                                  <X className="h-4 w-4" />
                                </Button>
                              </TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </div>
                  </CardContent>
                </Card>
              ) : (
                <div data-testid="no-pending-persons">没有待添加人员</div>
              )}

              {/* 绑定人员列表 */}
              <Card>
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <div>
                      <CardTitle>绑定人员列表</CardTitle>
                      <CardDescription>已绑定到订单的人员信息</CardDescription>
                    </div>
                    <Button
                      onClick={handleAddPersons}
                      size="sm"
                      data-testid="order-detail-card-add-persons-button"
                    >
                      <Users className="mr-2 h-4 w-4" />
                      添加人员
                    </Button>
                  </div>
                </CardHeader>
                <CardContent>
                  {order?.orderPersons && order.orderPersons.length > 0 ? (
                    <div className="border rounded-md">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            {personColumns.map((column) => (
                              <TableHead
                                key={column.key}
                                style={{ width: column.width }}
                              >
                                {column.label}
                              </TableHead>
                            ))}
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {(order?.orderPersons || []).map((person) => (
                            <TableRow
                              key={person.personId}
                              data-testid={`order-detail-person-${person.personId}`}
                            >
                              <TableCell>{person.personId}</TableCell>
                              <TableCell>{person.person?.name || `人员${person.personId}`}</TableCell>
                              <TableCell>{person.person?.gender || '未知'}</TableCell>
                              <TableCell>{person.person?.disabilityType || '未知'}</TableCell>
                              <TableCell>{person.person?.phone || '未知'}</TableCell>
                              <TableCell>
                                {formatDate(person.joinDate)}
                              </TableCell>
                              <TableCell>
                                {formatDate(person.leaveDate ? person.leaveDate.toString() : undefined)}
                              </TableCell>
                              <TableCell>
                                <Select
                                  value={person.workStatus?.toString()}
                                  onValueChange={(value) =>
                                    handleUpdateWorkStatus(
                                      person.personId,
                                      parseInt(value) as unknown as WorkStatus,
                                    )
                                  }
                                  data-testid={`order-detail-work-status-select-${person.personId}`}
                                >
                                  <SelectTrigger className="w-full">
                                    <SelectValue placeholder="选择状态" />
                                  </SelectTrigger>
                                  <SelectContent>
                                    <SelectItem
                                      value={WorkStatus.NOT_WORKING}
                                      data-testid={`work-status-option-not-working-${person.personId}`}
                                    >
                                      未入职
                                    </SelectItem>
                                    <SelectItem
                                      value={WorkStatus.PRE_WORKING}
                                      data-testid={`work-status-option-pre-working-${person.personId}`}
                                    >
                                      已入职
                                    </SelectItem>
                                    <SelectItem
                                      value={WorkStatus.WORKING}
                                      data-testid={`work-status-option-working-${person.personId}`}
                                    >
                                      工作中
                                    </SelectItem>
                                    <SelectItem
                                      value={WorkStatus.RESIGNED}
                                      data-testid={`work-status-option-resigned-${person.personId}`}
                                    >
                                      已离职
                                    </SelectItem>
                                  </SelectContent>
                                </Select>
                              </TableCell>
                              <TableCell>¥{person.salaryDetail || 0}</TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </div>
                  ) : (
                    <div className="text-center py-8 text-muted-foreground">
                      暂无绑定人员
                    </div>
                  )}
                </CardContent>
              </Card>
            </div>
          ) : (
            <div className="py-8 text-center text-muted-foreground">
              暂无订单数据
            </div>
          )}

          <DialogFooter className="flex flex-col sm:flex-row sm:justify-between sm:space-x-2">
            <div className="flex space-x-2">
              <Button
                onClick={handleAddPersons}
                variant="outline"
                data-testid="order-detail-bottom-add-persons-button"
              >
                <Users className="mr-2 h-4 w-4" />
                添加人员
              </Button>
              <Button
                onClick={handleAddAsset}
                variant="outline"
                data-testid="order-detail-bottom-add-asset-button"
              >
                <FileText className="mr-2 h-4 w-4" />
                资源上传
              </Button>
              <Button
                onClick={handleAttendanceExport}
                variant="outline"
                data-testid="order-detail-bottom-attendance-button"
                disabled={!order || order.orderPersons.length === 0}
              >
                <Calendar className="mr-2 h-4 w-4" />
                出勤导出
              </Button>
            </div>
            <div className="flex space-x-2 mt-2 sm:mt-0">
              <Button
                variant="outline"
                onClick={() => onOpenChange(false)}
                data-testid="order-detail-close-button"
              >
                关闭
              </Button>
              {order?.orderStatus === OrderStatus.DRAFT && (
                <Button
                  onClick={handleActivateOrder}
                  disabled={isActionLoading}
                  data-testid="order-detail-activate-button"
                >
                  <Play className="mr-2 h-4 w-4" />
                  {isActionLoading ? "激活中..." : "激活订单"}
                </Button>
              )}
              {(order?.orderStatus === OrderStatus.CONFIRMED ||
                order?.orderStatus === OrderStatus.IN_PROGRESS) && (
                <Button
                  onClick={handleCloseOrder}
                  variant="destructive"
                  disabled={isActionLoading}
                  data-testid="order-detail-close-order-button"
                >
                  <CheckCircle className="mr-2 h-4 w-4" />
                  {isActionLoading ? "关闭中..." : "关闭订单"}
                </Button>
              )}
            </div>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 残疾人选择器 */}
      <DisabledPersonSelector
        open={isPersonSelectorOpen}
        onOpenChange={setIsPersonSelectorOpen}
        onSelect={handlePersonSelect}
        mode="multiple"
        disabledIds={(order?.orderPersons || []).map(p => p.personId)}
      />

      {/* 资产上传模态框 */}
      {orderId && order?.orderPersons && (
        <OrderAssetModal
          orderId={orderId}
          orderPersons={order.orderPersons.map((op) => ({
            personId: op.personId,
            personName: op.person?.name || '未知',
            disabilityId: op.person?.disabilityId,
            disabilityType: op.person?.disabilityType,
          }))}
          open={isAssetAssociationOpen}
          onOpenChange={setIsAssetAssociationOpen}
        />
      )}

      {/* 出勤导出模态框 */}
      {orderId && order && (
        <AttendanceModal
          orderId={orderId}
          orderName={order.orderName || `订单${orderId}`}
          orderPersons={order.orderPersons.map((op) => ({
            personId: op.personId,
            personName: op.person?.name || '未知',
            disabilityId: op.person?.disabilityId,
            disabilityType: op.person?.disabilityType,
          }))}
          open={isAttendanceModalOpen}
          onOpenChange={setIsAttendanceModalOpen}
        />
      )}

    </>
  );
};

export default OrderDetailModal;
