import React, { useState } from 'react';
import { useQuery, useMutation } from '@tanstack/react-query';
import { Plus, Edit, Trash2, Search, Eye } from 'lucide-react';
import { format } from 'date-fns';
import { Input } from '@d8d/shared-ui-components/components/ui/input';
import { Button } from '@d8d/shared-ui-components/components/ui/button';
import { Label } from '@d8d/shared-ui-components/components/ui/label';
import { Textarea } from '@d8d/shared-ui-components/components/ui/textarea';
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 { Skeleton } from '@d8d/shared-ui-components/components/ui/skeleton';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@d8d/shared-ui-components/components/ui/dialog';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@d8d/shared-ui-components/components/ui/form';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@d8d/shared-ui-components/components/ui/select';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { toast } from 'sonner';
import { DataTablePagination } from '@d8d/shared-ui-components/components/admin/DataTablePagination';
import { disabilityClientManager } from '../api/disabilityClient';
import { CreateDisabledPersonSchema, UpdateDisabledPersonSchema } from '@d8d/allin-disability-module/schemas';
import type { CreateDisabledPersonRequest, UpdateDisabledPersonRequest } from '../api/disabilityClient';
import { DISABILITY_TYPES, getDisabilityTypeLabel } from '@d8d/allin-enums';
import { DISABILITY_LEVELS, getDisabilityLevelLabel } from '@d8d/allin-enums';
import { BankNameSelector } from '@d8d/bank-name-management-ui';
import { ProvinceSelect, AreaSelectForm } from '@d8d/area-management-ui';
import PhotoUploadField, { type PhotoItem } from './PhotoUploadField';
import PhotoPreview from './PhotoPreview';
import BankCardManagement, { type BankCardItem } from './BankCardManagement';
import RemarkManagement, { type RemarkItem } from './RemarkManagement';
import VisitManagement, { type VisitItem } from './VisitManagement';

interface DisabilityPersonSearchParams {
  page: number;
  limit: number;
  search: string;
  bankNameId?: number;
  cardType?: string;
  disabilityType?: string;
  disabilityLevel?: string;
  province?: string;
}

const DisabilityPersonManagement: React.FC = () => {
  const [searchParams, setSearchParams] = useState<DisabilityPersonSearchParams>({ page: 1, limit: 10, search: '' });
  const [isModalOpen, setIsModalOpen] = useState(false);

  const [isCreateForm, setIsCreateForm] = useState(true);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [personToDelete, setPersonToDelete] = useState<number | null>(null);
  const [viewDialogOpen, setViewDialogOpen] = useState(false);
  const [personToView, setPersonToView] = useState<number | null>(null);
  const [createPhotos, setCreatePhotos] = useState<PhotoItem[]>([]);
  const [updatePhotos, setUpdatePhotos] = useState<PhotoItem[]>([]);
  const [createBankCards, setCreateBankCards] = useState<BankCardItem[]>([]);
  const [updateBankCards, setUpdateBankCards] = useState<BankCardItem[]>([]);
  const [createRemarks, setCreateRemarks] = useState<RemarkItem[]>([]);
  const [updateRemarks, setUpdateRemarks] = useState<RemarkItem[]>([]);
  const [createVisits, setCreateVisits] = useState<VisitItem[]>([]);
  const [updateVisits, setUpdateVisits] = useState<VisitItem[]>([]);
  const [currentUserId] = useState<number>(1); // 假设当前用户ID为1，实际应从认证状态获取

  // 表单实例 - 创建表单
  const createForm = useForm<CreateDisabledPersonRequest>({
    resolver: zodResolver(CreateDisabledPersonSchema),
    defaultValues: {
      name: '',
      gender: '男',
      idCard: '',
      disabilityId: '',
      disabilityType: '',
      disabilityLevel: '',
      idAddress: '',
      phone: '',
      province: '',
      city: '',
      district: '',
      detailedAddress: '',
      nation: '',
      isMarried: 0,
      canDirectContact: 1, // 默认值改为1（是），与原系统一致
      isInBlackList: 0,
      jobStatus: 0,
      specificDisability: '',
      idValidDate: undefined,
      disabilityValidDate: undefined
    }
  });

  // 表单实例 - 更新表单
  const updateForm = useForm<UpdateDisabledPersonRequest>({
    resolver: zodResolver(UpdateDisabledPersonSchema),
    defaultValues: {}
  });


  // 数据查询
  const { data, isLoading, refetch } = useQuery({
    queryKey: ['disabled-persons', searchParams],
    queryFn: async () => {
      const queryParams: any = {
        skip: (searchParams.page - 1) * searchParams.limit,
        take: searchParams.limit
      };

      // 添加筛选参数
      if (searchParams.search) {
        queryParams.keyword = searchParams.search;
      }
      if (searchParams.bankNameId) {
        queryParams.bankNameId = searchParams.bankNameId;
      }
      if (searchParams.cardType) {
        queryParams.cardType = searchParams.cardType;
      }
      if (searchParams.disabilityType) {
        queryParams.disabilityType = searchParams.disabilityType;
      }
      if (searchParams.disabilityLevel) {
        queryParams.disabilityLevel = searchParams.disabilityLevel;
      }
      if (searchParams.province) {
        queryParams.province = searchParams.province;
      }

      const res = await disabilityClientManager.get().getAllDisabledPersons.$get({
        query: queryParams
      });
      if (res.status !== 200) throw new Error('获取残疾人列表失败');
      return await res.json();
    },
    initialData: {
      data: [],
      total: 0
    }
  });

  // 查看详情查询 - 使用聚合API获取包含照片的完整数据
  const { data: viewData } = useQuery({
    queryKey: ['disabled-person-aggregated-detail', personToView],
    queryFn: async () => {
      if (!personToView) return null;
      const res = await disabilityClientManager.get().getAggregatedDisabledPerson[':id'].$get({
        param: { id: personToView }
      });
      if (res.status !== 200) throw new Error('获取残疾人详情失败');
      return await res.json();
    },
    enabled: !!personToView && viewDialogOpen
  });

  // 创建残疾人
  const createMutation = useMutation({
    mutationFn: async (data: CreateDisabledPersonRequest) => {
      // 准备聚合数据，包含照片、银行卡、备注、回访信息
      const aggregatedData = {
        personInfo: data,
        photos: createPhotos
          .filter(photo => photo.fileId !== null)
          .map(photo => ({
            photoType: photo.photoType,
            fileId: photo.fileId!,
            canDownload: photo.canDownload
          })),
        bankCards: createBankCards
          .filter(card => card.fileId !== null && card.bankNameId && card.subBankName && card.cardNumber && card.cardholderName)
          .map(card => ({
            subBankName: card.subBankName,
            bankNameId: card.bankNameId!,
            bankName: { id: card.bankNameId!, name: card.bankName || '', code: '', remark: null, createdAt: new Date(), updatedAt: new Date(), createdBy: null, updatedBy: null, status: 1 },
            cardNumber: card.cardNumber,
            cardholderName: card.cardholderName,
            cardType: card.cardType || null,
            fileId: card.fileId!,
            isDefault: card.isDefault
          })),
        remarks: createRemarks
          .filter(remark => remark.remarkContent)
          .map(remark => ({
            remarkContent: remark.remarkContent,
            isSpecialNeeds: remark.isSpecialNeeds,
            operatorId: remark.operatorId
          })),
        visits: createVisits
          .filter(visit => visit.visitContent && visit.visitDate)
          .map(visit => ({
            visitDate: visit.visitDate,
            visitType: visit.visitType,
            visitContent: visit.visitContent,
            visitResult: visit.visitResult,
            nextVisitDate: visit.nextVisitDate,
            visitorId: visit.visitorId
          }))
      };

      // 使用聚合API创建残疾人信息
      const res = await disabilityClientManager.get().createAggregatedDisabledPerson.$post({
        json: aggregatedData
      });
      if (res.status !== 200) {
        const errorData = await res.json();
        throw new Error(errorData.message || '创建残疾人失败');
      }
      return await res.json();
    },
    onSuccess: () => {
      toast.success('残疾人创建成功');
      setIsModalOpen(false);
      createForm.reset();
      setCreatePhotos([]); // 重置照片状态
      setCreateBankCards([]); // 重置银行卡状态
      setCreateRemarks([]); // 重置备注状态
      setCreateVisits([]); // 重置回访状态
      refetch();
    },
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : '创建残疾人失败');
    }
  });

  // 更新残疾人
  const updateMutation = useMutation({
    mutationFn: async (data: UpdateDisabledPersonRequest) => {
      // 准备聚合数据，包含照片
      // 注意：我们需要从表单中获取完整数据，因为data只包含更新的字段
      const formData = updateForm.getValues();

      // 为必填字段提供默认值，确保类型安全
      const personInfo = {
        name: formData.name || '',
        gender: formData.gender || '男',
        idCard: formData.idCard || '',
        disabilityId: formData.disabilityId || '',
        disabilityType: formData.disabilityType || '',
        disabilityLevel: formData.disabilityLevel || '',
        idAddress: formData.idAddress || '',
        phone: formData.phone || '',
        province: formData.province || '',
        city: formData.city || '',
        // 可选字段
        district: formData.district,
        detailedAddress: formData.detailedAddress,
        nation: formData.nation,
        isMarried: formData.isMarried,
        canDirectContact: formData.canDirectContact,
        isInBlackList: formData.isInBlackList,
        jobStatus: formData.jobStatus,
        // 日期字段
        idValidDate: formData.idValidDate,
        disabilityValidDate: formData.disabilityValidDate,
        id: data.id // 确保包含ID
      };

      const aggregatedData = {
        personInfo,
        photos: updatePhotos
          .filter(photo => photo.fileId !== null)
          .map(photo => ({
            photoType: photo.photoType,
            fileId: photo.fileId!,
            canDownload: photo.canDownload
          })),
        bankCards: updateBankCards
          .filter(card => card.fileId !== null && card.bankNameId && card.subBankName && card.cardNumber && card.cardholderName)
          .map(card => ({
            subBankName: card.subBankName,
            bankNameId: card.bankNameId!,
            bankName: { id: card.bankNameId!, name: card.bankName || '', code: '', remark: null, createdAt: new Date(), updatedAt: new Date(), createdBy: null, updatedBy: null, status: 1 },
            cardNumber: card.cardNumber,
            cardholderName: card.cardholderName,
            cardType: card.cardType || null,
            fileId: card.fileId!,
            isDefault: card.isDefault
          })),
        remarks: updateRemarks
          .filter(remark => remark.remarkContent)
          .map(remark => ({
            remarkContent: remark.remarkContent,
            isSpecialNeeds: remark.isSpecialNeeds,
            operatorId: remark.operatorId
          })),
        visits: updateVisits
          .filter(visit => visit.visitContent && visit.visitDate)
          .map(visit => ({
            visitDate: visit.visitDate,
            visitType: visit.visitType,
            visitContent: visit.visitContent,
            visitResult: visit.visitResult,
            nextVisitDate: visit.nextVisitDate,
            visitorId: visit.visitorId
          }))
      };

      // 使用聚合API更新残疾人信息
      const res = await disabilityClientManager.get().updateAggregatedDisabledPerson[':id']['$put']({
        param: { id: data.id! },
        json: aggregatedData
      });
      if (res.status !== 200) {
        const errorData = await res.json();
        throw new Error(errorData.message || '更新残疾人失败');
      }
      return await res.json();
    },
    onSuccess: () => {
      toast.success('残疾人更新成功');
      setIsModalOpen(false);
      setUpdatePhotos([]); // 重置照片状态
      setUpdateBankCards([]); // 重置银行卡状态
      setUpdateRemarks([]); // 重置备注状态
      setUpdateVisits([]); // 重置回访状态
      refetch();
    },
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : '更新残疾人失败');
    }
  });

  // 删除残疾人
  const deleteMutation = useMutation({
    mutationFn: async (id: number) => {
      const res = await disabilityClientManager.get().deleteDisabledPerson.$post({
        json: { id }
      });
      if (res.status !== 200) {
        const errorData = await res.json();
        throw new Error(errorData.message || '删除残疾人失败');
      }
      return await res.json();
    },
    onSuccess: () => {
      toast.success('残疾人删除成功');
      setDeleteDialogOpen(false);
      refetch();
    },
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : '删除残疾人失败');
    }
  });

  // 处理搜索
  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    refetch();
  };

  // 打开创建模态框
  const handleCreateOpen = () => {
    setIsCreateForm(true);
    createForm.reset();
    setCreatePhotos([]); // 重置创建照片状态
    setCreateBankCards([]); // 重置创建银行卡状态
    setCreateRemarks([]); // 重置创建备注状态
    setCreateVisits([]); // 重置创建回访状态
    setIsModalOpen(true);
  };

  // 打开编辑模态框
  const handleEditOpen = (person: any) => {
    setIsCreateForm(false);
    updateForm.reset(person);
    setUpdatePhotos([]); // 先重置，然后加载已有数据
    setUpdateBankCards([]);
    setUpdateRemarks([]);
    setUpdateVisits([]);

    // 加载聚合数据获取照片、银行卡、备注、回访信息
    if (person.id) {
      disabilityClientManager.get().getAggregatedDisabledPerson[':id']['$get']({
        param: { id: person.id }
      }).then(async (res) => {
        if (res.status === 200) {
          const aggregatedData = await res.json();

          // 加载照片信息
          if (aggregatedData && aggregatedData.photos) {
            const photos: PhotoItem[] = aggregatedData.photos.map((photo: any) => ({
              photoType: photo.photoType,
              fileId: photo.fileId,
              canDownload: photo.canDownload,
              tempId: `existing-photo-${photo.id || Date.now()}`
            }));
            setUpdatePhotos(photos);
          }

          // 加载银行卡信息
          if (aggregatedData && aggregatedData.bankCards) {
            const bankCards: BankCardItem[] = aggregatedData.bankCards.map((card: any) => ({
              subBankName: card.subBankName,
              bankNameId: card.bankNameId,
              bankName: card.bankName?.name || '',
              cardNumber: card.cardNumber,
              cardholderName: card.cardholderName,
              cardType: card.cardType || null,
              fileId: card.fileId,
              isDefault: card.isDefault,
              tempId: `existing-bankcard-${card.id || Date.now()}`
            }));
            setUpdateBankCards(bankCards);
          }

          // 加载备注信息
          if (aggregatedData && aggregatedData.remarks) {
            const remarks: RemarkItem[] = aggregatedData.remarks.map((remark: any) => ({
              remarkContent: remark.remarkContent,
              isSpecialNeeds: remark.isSpecialNeeds,
              operatorId: remark.operatorId,
              tempId: `existing-remark-${remark.id || Date.now()}`
            }));
            setUpdateRemarks(remarks);
          }

          // 加载回访信息
          if (aggregatedData && aggregatedData.visits) {
            const visits: VisitItem[] = aggregatedData.visits.map((visit: any) => ({
              visitDate: visit.visitDate,
              visitType: visit.visitType,
              visitContent: visit.visitContent,
              visitResult: visit.visitResult,
              nextVisitDate: visit.nextVisitDate,
              visitorId: visit.visitorId,
              tempId: `existing-visit-${visit.id || Date.now()}`
            }));
            setUpdateVisits(visits);
          }
        }
      }).catch(error => {
        console.error('加载聚合数据失败:', error);
        toast.error('加载数据失败');
      });
    }

    setIsModalOpen(true);
  };

  // 打开查看模态框
  const handleViewOpen = (id: number) => {
    setPersonToView(id);
    setViewDialogOpen(true);
  };

  // 打开删除确认对话框
  const handleDeleteOpen = (id: number) => {
    setPersonToDelete(id);
    setDeleteDialogOpen(true);
  };

  // 提交创建表单
  const onSubmitCreate = (data: CreateDisabledPersonRequest) => {
    createMutation.mutate(data);
  };

  // 提交更新表单
  const onSubmitUpdate = (data: UpdateDisabledPersonRequest) => {
    updateMutation.mutate(data);
  };

  // 确认删除
  const confirmDelete = () => {
    if (personToDelete) {
      deleteMutation.mutate(personToDelete);
    }
  };

  // 重置筛选条件
  const handleResetFilters = () => {
    setSearchParams({
      page: 1,
      limit: searchParams.limit,
      search: '',
      bankNameId: undefined,
      cardType: undefined,
      disabilityType: undefined,
      disabilityLevel: undefined,
      province: undefined
    });
  };

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>残疾人个人管理</CardTitle>
          <CardDescription>管理残疾人个人信息，包括创建、编辑、查看和删除操作</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-between mb-6">
            <div className="flex-1">
              <form onSubmit={handleSearch} className="flex flex-col space-y-4">
                {/* 关键词搜索行 */}
                <div className="flex items-center space-x-2">
                  <Input
                    placeholder="搜索姓名或身份证号"
                    value={searchParams.search}
                    onChange={(e) => setSearchParams({ ...searchParams, search: e.target.value })}
                    className="w-64"
                    data-testid="keyword-search-input"
                  />
                  <Button type="submit" size="sm">
                    <Search className="h-4 w-4 mr-2" />
                    搜索
                  </Button>
                  <Button type="button" variant="outline" size="sm" onClick={handleResetFilters}>
                    重置筛选
                  </Button>
                </div>

                {/* 筛选条件行 */}
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-3">
                  {/* 银行卡类别筛选 */}
                  <div className="space-y-1">
                    <Label htmlFor="bank-name-filter" className="text-xs">银行卡类别</Label>
                    <BankNameSelector
                      value={searchParams.bankNameId}
                      onChange={(value) => setSearchParams({ ...searchParams, bankNameId: value, page: 1 })}
                      placeholder="选择银行"
                      className="w-full"
                      testId="bank-name-filter"
                    />
                  </div>

                  {/* 残疾类型筛选 */}
                  <div className="space-y-1">
                    <Label htmlFor="disability-type-filter" className="text-xs">残疾类型</Label>
                    <Select
                      value={searchParams.disabilityType || 'all'}
                      onValueChange={(value) => setSearchParams({ ...searchParams, disabilityType: value === 'all' ? undefined : value, page: 1 })}
                    >
                      <SelectTrigger id="disability-type-filter" data-testid="disability-type-filter" className="w-full">
                        <SelectValue placeholder="选择残疾类型" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="all">全部</SelectItem>
                        {DISABILITY_TYPES.map((type) => (
                          <SelectItem key={type} value={getDisabilityTypeLabel(type)}>
                            {getDisabilityTypeLabel(type)}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  {/* 残疾级别筛选 */}
                  <div className="space-y-1">
                    <Label htmlFor="disability-level-filter" className="text-xs">残疾级别</Label>
                    <Select
                      value={searchParams.disabilityLevel || 'all'}
                      onValueChange={(value) => setSearchParams({ ...searchParams, disabilityLevel: value === 'all' ? undefined : value, page: 1 })}
                    >
                      <SelectTrigger id="disability-level-filter" data-testid="disability-level-filter" className="w-full">
                        <SelectValue placeholder="选择残疾级别" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="all">全部</SelectItem>
                        {DISABILITY_LEVELS.map((level) => (
                          <SelectItem key={level} value={getDisabilityLevelLabel(level)}>
                            {getDisabilityLevelLabel(level)}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  {/* 居住省份筛选 */}
                  <div className="space-y-1">
                    <Label htmlFor="province-filter" className="text-xs">居住省份</Label>
                    <ProvinceSelect
                      value={searchParams.province || ''}
                      onChange={(value) => setSearchParams({ ...searchParams, province: value || undefined, page: 1 })}
                      placeholder="选择省份"
                      className="w-full"
                      data-testid="province-filter"
                    />
                  </div>

                  {/* 银行卡类型筛选 */}
                  <div className="space-y-1">
                    <Label htmlFor="card-type-filter" className="text-xs">银行卡类型</Label>
                    <Select
                      value={searchParams.cardType || 'all'}
                      onValueChange={(value) => setSearchParams({ ...searchParams, cardType: value === 'all' ? undefined : value, page: 1 })}
                    >
                      <SelectTrigger id="card-type-filter" data-testid="card-type-filter" className="w-full">
                        <SelectValue placeholder="选择银行卡类型" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="all">全部</SelectItem>
                        <SelectItem value="一类卡">一类卡</SelectItem>
                        <SelectItem value="二类卡">二类卡</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
              </form>
            </div>
            <div className="ml-4">
              <Button onClick={handleCreateOpen} data-testid="add-disabled-person-button">
                <Plus className="h-4 w-4 mr-2" />
                新增残疾人
              </Button>
            </div>
          </div>

          {isLoading ? (
            <div className="space-y-2">
              {Array.from({ length: 5 }).map((_, i) => (
                <Skeleton key={i} className="h-12 w-full" />
              ))}
            </div>
          ) : (
            <>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>姓名</TableHead>
                    <TableHead>性别</TableHead>
                    <TableHead>身份证号</TableHead>
                    <TableHead>残疾证号</TableHead>
                    <TableHead>残疾类型</TableHead>
                    <TableHead>残疾等级</TableHead>
                    <TableHead>联系电话</TableHead>
                    <TableHead>创建时间</TableHead>
                    <TableHead className="text-right">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {data?.data && data.data.length > 0 ? (
                    data.data.map((person: any) => (
                      <TableRow key={person.id}>
                        <TableCell>{person.name}</TableCell>
                        <TableCell>{person.gender}</TableCell>
                        <TableCell>{person.idCard}</TableCell>
                        <TableCell>{person.disabilityId}</TableCell>
                        <TableCell>{person.disabilityType}</TableCell>
                        <TableCell>{person.disabilityLevel}</TableCell>
                        <TableCell>{person.phone}</TableCell>
                        <TableCell>{format(new Date(person.createTime), 'yyyy-MM-dd HH:mm')}</TableCell>
                        <TableCell className="text-right">
                          <div className="flex justify-end space-x-2">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleViewOpen(person.id)}
                              data-testid={`view-person-${person.id}`}
                            >
                              <Eye className="h-4 w-4" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleEditOpen(person)}
                              data-testid={`edit-person-${person.id}`}
                            >
                              <Edit className="h-4 w-4" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleDeleteOpen(person.id)}
                              data-testid={`delete-person-${person.id}`}
                            >
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))
                  ) : (
                    <TableRow>
                      <TableCell colSpan={9} className="text-center py-8">
                        <p className="text-muted-foreground">暂无数据</p>
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>

              {data.total > 0 && (
                <div className="mt-4">
                  <DataTablePagination
                    currentPage={searchParams.page}
                    pageSize={searchParams.limit}
                    totalCount={data.total}
                    onPageChange={(page, pageSize) => setSearchParams({ ...searchParams, page, limit: pageSize })}
                  />
                </div>
              )}
            </>
          )}
        </CardContent>
      </Card>

      {/* 创建/编辑模态框 */}
      <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
        <DialogContent className="w-[95vw] max-w-4xl max-h-[85vh] flex flex-col overflow-hidden">
          <DialogHeader>
            <DialogTitle data-testid={isCreateForm ? 'create-disabled-person-dialog-title' : 'edit-disabled-person-dialog-title'}>
              {isCreateForm ? '新增残疾人' : '编辑残疾人信息'}
            </DialogTitle>
            <DialogDescription>
              {isCreateForm ? '填写残疾人基本信息，带*的为必填项' : '修改残疾人信息'}
            </DialogDescription>
          </DialogHeader>
          <div className="flex-1 overflow-y-auto pr-2 overscroll-contain touch-auto py-2 scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-gray-100 hover:scrollbar-thumb-gray-400">
            {isCreateForm ? (
              <Form {...createForm}>
                <form id="create-form" onSubmit={createForm.handleSubmit(onSubmitCreate, (errors) => console.debug('创建表单验证错误:', errors))} className="space-y-4">
                  {/* 第一部分：小字段使用网格布局 */}
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    <FormField
                      control={createForm.control}
                      name="name"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>姓名 *</FormLabel>
                          <FormControl>
                            <Input placeholder="请输入姓名" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={createForm.control}
                      name="gender"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>性别 *</FormLabel>
                          <FormControl>
                            <select
                              className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                              data-testid="gender-select"
                              {...field}
                            >
                              <option value="男">男</option>
                              <option value="女">女</option>
                            </select>
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={createForm.control}
                      name="idCard"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>身份证号 *</FormLabel>
                          <FormControl>
                            <Input placeholder="请输入身份证号" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={createForm.control}
                      name="disabilityId"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>残疾证号 *</FormLabel>
                          <FormControl>
                            <Input placeholder="请输入残疾证号" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={createForm.control}
                      name="disabilityType"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>残疾类型 *</FormLabel>
                          <FormControl>
                            <select
                              className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                              data-testid="disability-type-select"
                              {...field}
                            >
                              <option value="">请选择残疾类型</option>
                              {DISABILITY_TYPES.map((type) => (
                                <option key={type} value={getDisabilityTypeLabel(type)}>
                                  {getDisabilityTypeLabel(type)}
                                </option>
                              ))}
                            </select>
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={createForm.control}
                      name="disabilityLevel"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>残疾等级 *</FormLabel>
                          <FormControl>
                            <select
                              className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                              data-testid="disability-level-select"
                              {...field}
                            >
                              <option value="">请选择残疾等级</option>
                              {DISABILITY_LEVELS.map((level) => (
                                <option key={level} value={getDisabilityLevelLabel(level)}>
                                  {getDisabilityLevelLabel(level)}
                                </option>
                              ))}
                            </select>
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={createForm.control}
                      name="phone"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>联系电话 *</FormLabel>
                          <FormControl>
                            <Input placeholder="请输入联系电话" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={createForm.control}
                      name="nation"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>民族</FormLabel>
                          <FormControl>
                            <Input placeholder="请输入民族" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={createForm.control}
                      name="isMarried"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>婚姻状况</FormLabel>
                          <FormControl>
                            <select
                              className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                              {...field}
                              value={field.value?.toString()}
                              onChange={(e) => field.onChange(Number(e.target.value))}
                            >
                              <option value="0">未婚</option>
                              <option value="1">已婚</option>
                            </select>
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={createForm.control}
                      name="canDirectContact"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>是否可直接联系</FormLabel>
                          <FormControl>
                            <select
                              className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                              {...field}
                              value={field.value?.toString()}
                              onChange={(e) => field.onChange(Number(e.target.value))}
                            >
                              <option value="1">是</option>
                              <option value="0">否</option>
                            </select>
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={createForm.control}
                      name="jobStatus"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>在职状态</FormLabel>
                          <FormControl>
                            <select
                              className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                              {...field}
                              value={field.value?.toString()}
                              onChange={(e) => field.onChange(Number(e.target.value))}
                            >
                              <option value="0">未在职</option>
                              <option value="1">已在职</option>
                            </select>
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={createForm.control}
                      name="isInBlackList"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>是否在黑名单</FormLabel>
                          <FormControl>
                            <select
                              className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                              {...field}
                              value={field.value?.toString()}
                              onChange={(e) => field.onChange(Number(e.target.value))}
                            >
                              <option value="0">否</option>
                              <option value="1">是</option>
                            </select>
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={createForm.control}
                      name="specificDisability"
                      render={({ field }) => (
                        <FormItem className="col-span-full">
                          <FormLabel>具体残疾部位和情况（可选）</FormLabel>
                          <FormControl>
                            <Textarea
                              placeholder="请输入具体残疾部位和情况，最多500字符"
                              className="min-h-[100px]"
                              {...field}
                              data-testid="specific-disability-textarea"
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                  </div>

                  {/* 第二部分：大字段脱离网格布局，各自独占一行 */}
                  <div className="space-y-4">
                    <FormField
                      control={createForm.control}
                      name="idAddress"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>身份证地址 *</FormLabel>
                          <FormControl>
                            <Input placeholder="请输入身份证地址" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                      <FormField
                        control={createForm.control}
                        name="idValidDate"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>身份证有效期</FormLabel>
                            <FormControl>
                              <Input
                                type="date"
                                placeholder="选择身份证有效期"
                                {...field}
                                value={field.value ? new Date(field.value).toISOString().split('T')[0] : ''}
                                onChange={(e) => field.onChange(e.target.value ? new Date(e.target.value) : undefined)}
                              />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />

                      <FormField
                        control={createForm.control}
                        name="disabilityValidDate"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>残疾证有效期</FormLabel>
                            <FormControl>
                              <Input
                                type="date"
                                placeholder="选择残疾证有效期"
                                {...field}
                                value={field.value ? new Date(field.value).toISOString().split('T')[0] : ''}
                                onChange={(e) => field.onChange(e.target.value ? new Date(e.target.value) : undefined)}
                              />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />

                    </div>

                    <div>
                      <FormLabel>居住地址 *</FormLabel>
                      <div className="space-y-4 mt-2">
                        <AreaSelectForm<CreateDisabledPersonRequest>
                          provinceName="province"
                          cityName="city"
                          districtName="district"
                          label=""
                          required={true}
                        />

                        <FormField
                          control={createForm.control}
                          name="detailedAddress"
                          render={({ field }) => (
                            <FormItem>
                              <FormControl>
                                <Input placeholder="详细地址（街道、门牌号等）" {...field} />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                      </div>
                    </div>

                    <div className="col-span-full">
                      <PhotoUploadField
                        value={createPhotos}
                        onChange={setCreatePhotos}
                        photoTypes={['身份证照片', '残疾证照片', '个人照片', '其他照片']}
                        maxPhotos={undefined}
                      />
                    </div>

                    <div className="col-span-full">
                      <BankCardManagement
                        value={createBankCards}
                        onChange={setCreateBankCards}
                        maxCards={5}
                      />
                    </div>

                    <div className="col-span-full">
                      <RemarkManagement
                        value={createRemarks}
                        onChange={setCreateRemarks}
                        maxRemarks={10}
                        currentUserId={currentUserId}
                      />
                    </div>

                    <div className="col-span-full">
                      <VisitManagement
                        value={createVisits}
                        onChange={setCreateVisits}
                        maxVisits={10}
                        currentUserId={currentUserId}
                        visitTypes={['电话回访', '上门回访', '视频回访', '微信回访', '其他']}
                      />
                    </div>
                  </div>
                </form>
            </Form>
          ) : (
            <Form {...updateForm}>
              <form id="update-form" onSubmit={updateForm.handleSubmit(onSubmitUpdate)} className="space-y-4">
                {/* 第一部分：小字段使用网格布局 */}
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                  <FormField
                    control={updateForm.control}
                    name="name"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>姓名 *</FormLabel>
                        <FormControl>
                          <Input placeholder="请输入姓名" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={updateForm.control}
                    name="gender"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>性别 *</FormLabel>
                        <FormControl>
                          <select
                            className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                            data-testid="gender-select"
                            {...field}
                          >
                            <option value="男">男</option>
                            <option value="女">女</option>
                          </select>
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={updateForm.control}
                    name="idCard"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>身份证号 *</FormLabel>
                        <FormControl>
                          <Input placeholder="请输入身份证号" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={updateForm.control}
                    name="disabilityId"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>残疾证号 *</FormLabel>
                        <FormControl>
                          <Input placeholder="请输入残疾证号" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={updateForm.control}
                    name="disabilityType"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>残疾类型 *</FormLabel>
                        <FormControl>
                          <select
                            className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                            data-testid="gender-select"
                            {...field}
                          >
                            <option value="">请选择残疾类型</option>
                            {DISABILITY_TYPES.map((type) => (
                              <option key={type} value={getDisabilityTypeLabel(type)}>
                                {getDisabilityTypeLabel(type)}
                              </option>
                            ))}
                          </select>
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={updateForm.control}
                    name="disabilityLevel"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>残疾等级 *</FormLabel>
                        <FormControl>
                          <select
                            className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                            data-testid="gender-select"
                            {...field}
                          >
                            <option value="">请选择残疾等级</option>
                            {DISABILITY_LEVELS.map((level) => (
                              <option key={level} value={getDisabilityLevelLabel(level)}>
                                {getDisabilityLevelLabel(level)}
                              </option>
                            ))}
                          </select>
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={updateForm.control}
                    name="phone"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>联系电话 *</FormLabel>
                        <FormControl>
                          <Input placeholder="请输入联系电话" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={updateForm.control}
                    name="nation"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>民族</FormLabel>
                        <FormControl>
                          <Input placeholder="请输入民族" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={updateForm.control}
                    name="isMarried"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>婚姻状况</FormLabel>
                        <FormControl>
                          <select
                            className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                            {...field}
                            value={field.value?.toString()}
                            onChange={(e) => field.onChange(Number(e.target.value))}
                          >
                            <option value="0">未婚</option>
                            <option value="1">已婚</option>
                          </select>
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={updateForm.control}
                    name="canDirectContact"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>是否可直接联系</FormLabel>
                        <FormControl>
                          <select
                            className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                            {...field}
                            value={field.value?.toString()}
                            onChange={(e) => field.onChange(Number(e.target.value))}
                          >
                            <option value="1">是</option>
                            <option value="0">否</option>
                          </select>
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={updateForm.control}
                    name="jobStatus"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>在职状态</FormLabel>
                        <FormControl>
                          <select
                            className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                            {...field}
                            value={field.value?.toString()}
                            onChange={(e) => field.onChange(Number(e.target.value))}
                          >
                            <option value="0">未在职</option>
                            <option value="1">已在职</option>
                          </select>
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={updateForm.control}
                    name="isInBlackList"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>是否在黑名单</FormLabel>
                        <FormControl>
                          <select
                            className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                            {...field}
                            value={field.value?.toString()}
                            onChange={(e) => field.onChange(Number(e.target.value))}
                          >
                            <option value="0">否</option>
                            <option value="1">是</option>
                          </select>
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={updateForm.control}
                    name="specificDisability"
                    render={({ field }) => (
                      <FormItem className="col-span-full">
                        <FormLabel>具体残疾部位和情况（可选）</FormLabel>
                        <FormControl>
                          <Textarea
                            placeholder="请输入具体残疾部位和情况，最多500字符"
                            className="min-h-[100px]"
                            {...field}
                            data-testid="specific-disability-textarea"
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />





                </div>

                {/* 第二部分：大字段脱离网格布局，各自独占一行 */}
                <div className="space-y-4">
                  <FormField
                    control={updateForm.control}
                    name="idAddress"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>身份证地址 *</FormLabel>
                        <FormControl>
                          <Input placeholder="请输入身份证地址" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <FormField
                      control={updateForm.control}
                      name="idValidDate"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>身份证有效期</FormLabel>
                          <FormControl>
                            <Input
                              type="date"
                              placeholder="选择身份证有效期"
                              {...field}
                              value={field.value ? (field.value instanceof Date ? field.value : new Date(field.value)).toISOString().split('T')[0] : ''}
                              onChange={(e) => field.onChange(e.target.value ? new Date(e.target.value) : undefined)}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={updateForm.control}
                      name="disabilityValidDate"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>残疾证有效期</FormLabel>
                          <FormControl>
                            <Input
                              type="date"
                              placeholder="选择残疾证有效期"
                              {...field}
                              value={field.value ? (field.value instanceof Date ? field.value : new Date(field.value)).toISOString().split('T')[0] : ''}
                              onChange={(e) => field.onChange(e.target.value ? new Date(e.target.value) : undefined)}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                  </div>

                  <div>
                    <FormLabel>居住地址 *</FormLabel>
                    <div className="space-y-4 mt-2">
                      <AreaSelectForm<UpdateDisabledPersonRequest>
                        provinceName="province"
                        cityName="city"
                        districtName="district"
                        label=""
                        required={true}
                      />

                      <FormField
                        control={updateForm.control}
                        name="detailedAddress"
                        render={({ field }) => (
                          <FormItem>
                            <FormControl>
                              <Input placeholder="详细地址（街道、门牌号等）" {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    </div>

                    {/* 照片上传 */}
                    <div className="col-span-full">
                      <PhotoUploadField
                        value={updatePhotos}
                        onChange={setUpdatePhotos}
                        photoTypes={['身份证照片', '残疾证照片', '个人照片', '其他照片']}
                        maxPhotos={undefined}
                      />
                    </div>

                    {/* 银行卡管理 */}
                    <div className="col-span-full">
                      <BankCardManagement
                        value={updateBankCards}
                        onChange={setUpdateBankCards}
                        maxCards={5}
                      />
                    </div>

                    {/* 备注管理 */}
                    <div className="col-span-full">
                      <RemarkManagement
                        value={updateRemarks}
                        onChange={setUpdateRemarks}
                        maxRemarks={10}
                        currentUserId={currentUserId}
                      />
                    </div>

                    {/* 回访管理 */}
                    <div className="col-span-full">
                      <VisitManagement
                        value={updateVisits}
                        onChange={setUpdateVisits}
                        maxVisits={10}
                        currentUserId={currentUserId}
                        visitTypes={['电话回访', '上门回访', '视频回访', '微信回访', '其他']}
                      />
                    </div>
                  </div>
                </div>
              </form>
            </Form>
          )}
          </div>
          <DialogFooter className="mt-4">
            <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
              取消
            </Button>
            {isCreateForm ? (
              <Button type="submit" form="create-form" disabled={createMutation.isPending}>
                {createMutation.isPending ? '创建中...' : '创建'}
              </Button>
            ) : (
              <Button type="submit" form="update-form" disabled={updateMutation.isPending}>
                {updateMutation.isPending ? '更新中...' : '更新'}
              </Button>
            )}
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 查看详情模态框 */}
      <Dialog open={viewDialogOpen} onOpenChange={setViewDialogOpen}>
        <DialogContent className="max-w-4xl max-h-[85vh] flex flex-col overflow-hidden">
          <DialogHeader>
            <DialogTitle>残疾人详情</DialogTitle>
            <DialogDescription>查看残疾人详细信息</DialogDescription>
          </DialogHeader>

          {viewData && (
            <div className="flex-1 overflow-y-auto pr-2 overscroll-contain touch-auto py-2">
              <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-sm font-medium">姓名</label>
                  <p className="text-sm text-muted-foreground">{viewData.personInfo.name}</p>
                </div>
                <div>
                  <label className="text-sm font-medium">性别</label>
                  <p className="text-sm text-muted-foreground">{viewData.personInfo.gender}</p>
                </div>
                <div>
                  <label className="text-sm font-medium">身份证号</label>
                  <p className="text-sm text-muted-foreground">{viewData.personInfo.idCard}</p>
                </div>
                <div>
                  <label className="text-sm font-medium">残疾证号</label>
                  <p className="text-sm text-muted-foreground">{viewData.personInfo.disabilityId}</p>
                </div>
                <div>
                  <label className="text-sm font-medium">残疾类型</label>
                  <p className="text-sm text-muted-foreground">{viewData.personInfo.disabilityType}</p>
                </div>
                <div>
                  <label className="text-sm font-medium">残疾等级</label>
                  <p className="text-sm text-muted-foreground">{viewData.personInfo.disabilityLevel}</p>
                </div>
                <div>
                  <label className="text-sm font-medium">联系电话</label>
                  <p className="text-sm text-muted-foreground">{viewData.personInfo.phone}</p>
                </div>
                <div>
                  <label className="text-sm font-medium">身份证地址</label>
                  <p className="text-sm text-muted-foreground">{viewData.personInfo.idAddress}</p>
                </div>
                <div className="col-span-1 md:col-span-2">
                  <label className="text-sm font-medium">居住地址</label>
                  <p className="text-sm text-muted-foreground">
                    {viewData.personInfo.province} {viewData.personInfo.city} {viewData.personInfo.district} {viewData.personInfo.detailedAddress}
                  </p>
                </div>
                <div>
                  <label className="text-sm font-medium">民族</label>
                  <p className="text-sm text-muted-foreground">{viewData.personInfo.nation || '未填写'}</p>
                </div>
                <div>
                  <label className="text-sm font-medium">婚姻状况</label>
                  <p className="text-sm text-muted-foreground">
                    {viewData.personInfo.isMarried === 1 ? '已婚' : viewData.personInfo.isMarried === 0 ? '未婚' : '未知'}
                  </p>
                </div>
                <div>
                  <label className="text-sm font-medium">身份证有效期</label>
                  <p className="text-sm text-muted-foreground">
                    {viewData.personInfo.idValidDate ? format(new Date(viewData.personInfo.idValidDate), 'yyyy-MM-dd') : '未填写'}
                  </p>
                </div>
                <div>
                  <label className="text-sm font-medium">残疾证有效期</label>
                  <p className="text-sm text-muted-foreground">
                    {viewData.personInfo.disabilityValidDate ? format(new Date(viewData.personInfo.disabilityValidDate), 'yyyy-MM-dd') : '未填写'}
                  </p>
                </div>
                <div className="col-span-1 md:col-span-2">
                  <label className="text-sm font-medium">具体残疾部位和情况</label>
                  <p className="text-sm text-muted-foreground whitespace-pre-wrap">
                    {viewData.personInfo.specificDisability || '未填写'}
                  </p>
                </div>
                <div>
                  <label className="text-sm font-medium">创建时间</label>
                  <p className="text-sm text-muted-foreground">
                    {format(new Date(viewData.personInfo.createTime), 'yyyy-MM-dd HH:mm:ss')}
                  </p>
                </div>
                <div>
                  <label className="text-sm font-medium">更新时间</label>
                  <p className="text-sm text-muted-foreground">
                    {format(new Date(viewData.personInfo.updateTime), 'yyyy-MM-dd HH:mm:ss')}
                  </p>
                </div>
              </div>

              {/* 照片预览 */}
              {viewData.photos && viewData.photos.length > 0 && (
                <div className="mt-6 pt-6 border-t">
                  <PhotoPreview
                    photos={viewData.photos.map((photo: any) => ({
                      id: photo.id,
                      photoType: photo.photoType,
                      fileId: photo.fileId,
                      fileUrl: photo.file?.fullUrl,
                      fileName: photo.file?.name || `照片-${photo.photoType}`,
                      canDownload: photo.canDownload,
                      uploadTime: photo.uploadTime
                    }))}
                    title="照片"
                    showDownloadButton={true}
                  />
                </div>
              )}

              {/* 银行卡信息 */}
              {viewData.bankCards && viewData.bankCards.length > 0 && (
                <div className="mt-6 pt-6 border-t">
                  <h3 className="text-lg font-medium mb-4">银行卡信息</h3>
                  <div className="space-y-4">
                    {viewData.bankCards.map((card: any, index: number) => (
                      <Card key={card.id || index}>
                        <CardContent className="pt-6">
                          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                              <Label>银行名称</Label>
                              <p className="text-sm text-muted-foreground">{card.bankName}</p>
                            </div>
                            <div>
                              <Label>发卡支行</Label>
                              <p className="text-sm text-muted-foreground">{card.subBankName}</p>
                            </div>
                            <div>
                              <Label>银行卡号</Label>
                              <p className="text-sm text-muted-foreground">{card.cardNumber}</p>
                            </div>
                            <div>
                              <Label>持卡人姓名</Label>
                              <p className="text-sm text-muted-foreground">{card.cardholderName}</p>
                            </div>
                            <div>
                              <Label>是否默认</Label>
                              <p className="text-sm text-muted-foreground">
                                {card.isDefault === 1 ? '是' : '否'}
                              </p>
                            </div>
                            {card.file?.fullUrl && (
                              <div className="md:col-span-2">
                                <Label>银行卡照片</Label>
                                <div className="mt-2">
                                  <img
                                    src={card.file.fullUrl}
                                    alt="银行卡照片"
                                    className="max-w-xs rounded-md border"
                                  />
                                </div>
                              </div>
                            )}
                          </div>
                        </CardContent>
                      </Card>
                    ))}
                  </div>
                </div>
              )}

              {/* 备注信息 */}
              {viewData.remarks && viewData.remarks.length > 0 && (
                <div className="mt-6 pt-6 border-t">
                  <h3 className="text-lg font-medium mb-4">备注信息</h3>
                  <div className="space-y-4">
                    {viewData.remarks.map((remark: any, index: number) => (
                      <Card key={remark.id || index}>
                        <CardContent className="pt-6">
                          <div className="space-y-2">
                            <div className="flex justify-between items-start">
                              <div>
                                <Label>备注内容</Label>
                                <p className="text-sm text-muted-foreground">{remark.remarkContent}</p>
                              </div>
                              {remark.isSpecialNeeds === 1 && (
                                <span className="inline-flex items-center rounded-full bg-amber-100 px-2 py-1 text-xs font-medium text-amber-800">
                                  特殊需求
                                </span>
                              )}
                            </div>
                            <div className="text-xs text-muted-foreground">
                              <p>操作人ID：{remark.operatorId}</p>
                              <p>备注时间：{format(new Date(remark.remarkTime), 'yyyy-MM-dd HH:mm:ss')}</p>
                            </div>
                          </div>
                        </CardContent>
                      </Card>
                    ))}
                  </div>
                </div>
              )}

              {/* 回访信息 */}
              {viewData.visits && viewData.visits.length > 0 && (
                <div className="mt-6 pt-6 border-t">
                  <h3 className="text-lg font-medium mb-4">回访记录</h3>
                  <div className="space-y-4">
                    {viewData.visits.map((visit: any, index: number) => (
                      <Card key={visit.id || index}>
                        <CardContent className="pt-6">
                          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                              <Label>回访日期</Label>
                              <p className="text-sm text-muted-foreground">
                                {format(new Date(visit.visitDate), 'yyyy-MM-dd')}
                              </p>
                            </div>
                            <div>
                              <Label>回访类型</Label>
                              <p className="text-sm text-muted-foreground">{visit.visitType}</p>
                            </div>
                            <div className="md:col-span-2">
                              <Label>回访内容</Label>
                              <p className="text-sm text-muted-foreground">{visit.visitContent}</p>
                            </div>
                            {visit.visitResult && (
                              <div>
                                <Label>回访结果</Label>
                                <p className="text-sm text-muted-foreground">{visit.visitResult}</p>
                              </div>
                            )}
                            {visit.nextVisitDate && (
                              <div>
                                <Label>下次回访日期</Label>
                                <p className="text-sm text-muted-foreground">
                                  {format(new Date(visit.nextVisitDate), 'yyyy-MM-dd')}
                                </p>
                              </div>
                            )}
                            <div>
                              <Label>回访人ID</Label>
                              <p className="text-sm text-muted-foreground">{visit.visitorId}</p>
                            </div>
                            <div>
                              <Label>记录时间</Label>
                              <p className="text-sm text-muted-foreground">
                                {format(new Date(visit.visitTime), 'yyyy-MM-dd HH:mm:ss')}
                              </p>
                            </div>
                          </div>
                        </CardContent>
                      </Card>
                    ))}
                  </div>
                </div>
              )}
            </div>
            </div>
          )}

          <DialogFooter>
            <Button onClick={() => setViewDialogOpen(false)}>关闭</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除确认对话框 */}
      <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle data-testid="delete-confirmation-dialog-title">确认删除</DialogTitle>
            <DialogDescription>
              确定要删除这个残疾人记录吗？此操作不可恢复。
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>
              取消
            </Button>
            <Button variant="destructive" onClick={confirmDelete} disabled={deleteMutation.isPending}>
              {deleteMutation.isPending ? '删除中...' : '确认删除'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default DisabilityPersonManagement;