import React, { useState, useMemo } from 'react';
import { useQuery } from '@tanstack/react-query';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { Plus, Search, Edit, Trash2, GitCompare } from 'lucide-react';

import { submissionRecordsClient } from '@/client/api';
import type {
  SubmissionRecordsItem,
  CreateSubmissionRecordsRequest,
  UpdateSubmissionRecordsRequest
} from '@/client/admin/types/submission';
import { CreateSubmissionRecordsDto, UpdateSubmissionRecordsDto } from '@/server/modules/submission/submission-records.schema';

import { Button } from '@/client/components/ui/button';
import { Checkbox } from '@/client/components/ui/checkbox';
import { Input } from '@/client/components/ui/input';
import { Card, CardContent, CardHeader, CardTitle } from '@/client/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/client/components/ui/table';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/client/components/ui/dialog';
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/client/components/ui/form';
import { Skeleton } from '@/client/components/ui/skeleton';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/client/components/ui/alert-dialog';

import { DataTablePagination } from '@/client/admin/components/DataTablePagination';
import { SubmissionComparisonDialog } from '@/client/admin/components/SubmissionComparisonDialog';


// 表单schema
const createFormSchema = CreateSubmissionRecordsDto;
const updateFormSchema = UpdateSubmissionRecordsDto;

// 提交记录管理页面
export const SubmissionRecordsPage = () => {
  const [searchParams, setSearchParams] = useState({
    page: 1,
    limit: 10,
    search: ''
  });
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isCreateForm, setIsCreateForm] = useState(true);
  const [editingRecord, setEditingRecord] = useState<any>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [recordToDelete, setRecordToDelete] = useState<number | null>(null);
  const [selectedRecords, setSelectedRecords] = useState<number[]>([]);
  const [compareDialogOpen, setCompareDialogOpen] = useState(false);

  // 创建表单
  const createForm = useForm<CreateSubmissionRecordsRequest>({
    resolver: zodResolver(createFormSchema),
    defaultValues: {
      classroomNo: null,
      userId: null,
      score: null,
      code: null,
      trainingDate: null,
      mark: null,
      status: null,
      holdingStock: null,
      holdingCash: null,
      price: null,
      profitAmount: null,
      profitPercent: null,
      totalProfitAmount: null,
      totalProfitPercent: null
    }
  });

  // 更新表单
  const updateForm = useForm<UpdateSubmissionRecordsRequest>({
    resolver: zodResolver(updateFormSchema),
    defaultValues: {
      classroomNo: null,
      userId: null,
      score: null,
      code: null,
      trainingDate: null,
      mark: null,
      status: null,
      holdingStock: null,
      holdingCash: null,
      price: null,
      profitAmount: null,
      profitPercent: null,
      totalProfitAmount: null,
      totalProfitPercent: null
    }
  });

  // 获取提交记录列表
  const { data: recordsData, isLoading, refetch } = useQuery({
    queryKey: ['submission-records', searchParams],
    queryFn: async () => {
      const res = await submissionRecordsClient.$get({
        query: {
          page: searchParams.page,
          pageSize: searchParams.limit,
          keyword: searchParams.search
        }
      });
      if (res.status !== 200) {
        throw new Error('获取提交记录列表失败');
      }
      return await res.json();
    }
  });

  const records = recordsData?.data || [];
  const totalCount = recordsData?.pagination?.total || 0;

  // 处理搜索
  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    setSearchParams(prev => ({ ...prev, page: 1 }));
  };

  // 打开创建记录对话框
  const showCreateModal = () => {
    setIsCreateForm(true);
    setEditingRecord(null);
    createForm.reset();
    setIsModalOpen(true);
  };

  // 打开编辑记录对话框
  const showEditModal = (record: any) => {
    setIsCreateForm(false);
    setEditingRecord(record);
    updateForm.reset({
      classroomNo: record.classroomNo,
      userId: record.userId,
      score: record.score,
      code: record.code,
      trainingDate: record.trainingDate ? new Date(record.trainingDate) : null,
      mark: record.mark,
      status: record.status,
      holdingStock: record.holdingStock,
      holdingCash: record.holdingCash,
      price: record.price,
      profitAmount: record.profitAmount,
      profitPercent: record.profitPercent,
      totalProfitAmount: record.totalProfitAmount,
      totalProfitPercent: record.totalProfitPercent
    });
    setIsModalOpen(true);
  };

  // 处理创建记录
  const handleCreateSubmit = async (data: CreateSubmissionRecordsRequest) => {
    try {
      const res = await submissionRecordsClient.$post({ json: data });
      if (res.status !== 201) {
        const error = await res.json();
        throw new Error(error.message || '创建提交记录失败');
      }
      toast.success('提交记录创建成功');
      setIsModalOpen(false);
      createForm.reset();
      refetch();
    } catch (error) {
      toast.error(error instanceof Error ? error.message : '创建失败，请重试');
    }
  };

  // 处理更新记录
  const handleUpdateSubmit = async (data: UpdateSubmissionRecordsRequest) => {
    if (!editingRecord) return;
    
    try {
      const res = await submissionRecordsClient[':id']['$put']({
        param: { id: editingRecord.id.toString() },
        json: data
      });
      if (res.status !== 200) {
        const error = await res.json();
        throw new Error(error.message || '更新提交记录失败');
      }
      toast.success('提交记录更新成功');
      setIsModalOpen(false);
      updateForm.reset();
      refetch();
    } catch (error) {
      toast.error(error instanceof Error ? error.message : '更新失败，请重试');
    }
  };

  // 打开删除确认对话框
  const showDeleteDialog = (recordId: number) => {
    setRecordToDelete(recordId);
    setDeleteDialogOpen(true);
  };

  // 处理删除记录
  const handleDelete = async () => {
    if (!recordToDelete) return;
    
    try {
      const res = await submissionRecordsClient[':id']['$delete']({
        param: { id: recordToDelete.toString() }
      });
      if (res.status !== 204) {
        throw new Error('删除提交记录失败');
      }
      toast.success('提交记录删除成功');
      setDeleteDialogOpen(false);
      setRecordToDelete(null);
      refetch();
    } catch (error) {
      toast.error('删除失败，请重试');
    }
  };

  // 获取选中的记录数据
  const selectedRecordsData = useMemo(() => {
    return records.filter(record => selectedRecords.includes(record.id));
  }, [records, selectedRecords]);

  // 加载状态
  if (isLoading) {
    return (
      <div className="space-y-4">
        <div className="flex justify-between items-center">
          <Skeleton className="h-8 w-48" />
          <Skeleton className="h-10 w-32" />
        </div>
        
        <Card>
          <CardHeader>
            <Skeleton className="h-6 w-1/4" />
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {[...Array(5)].map((_, i) => (
                <div key={i} className="flex gap-4">
                  <Skeleton className="h-10 flex-1" />
                  <Skeleton className="h-10 flex-1" />
                  <Skeleton className="h-10 flex-1" />
                  <Skeleton className="h-10 w-20" />
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* 页面标题 */}
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-bold">提交记录管理</h1>
        <div className="flex gap-2">
          <Button
            variant="outline"
            onClick={() => setCompareDialogOpen(true)}
            disabled={selectedRecords.length < 2}
          >
            <GitCompare className="mr-2 h-4 w-4" />
            对比({selectedRecords.length})
          </Button>
          <Button onClick={showCreateModal}>
            <Plus className="mr-2 h-4 w-4" />
            添加记录
          </Button>
        </div>
      </div>

      {/* 搜索区域 */}
      <Card>
        <CardHeader>
          <CardTitle>提交记录列表</CardTitle>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSearch} className="flex gap-2 mb-4">
            <div className="relative flex-1 max-w-sm">
              <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder="搜索教室号、用户ID或代码..."
                value={searchParams.search}
                onChange={(e) => setSearchParams(prev => ({ ...prev, search: e.target.value }))}
                className="pl-8"
              />
            </div>
            <Button type="submit" variant="outline">
              搜索
            </Button>
          </form>

          {/* 提交记录表格 */}
          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-12">
                    <Checkbox
                      checked={selectedRecords.length === records.length && records.length > 0}
                      onCheckedChange={(checked) => {
                        if (checked) {
                          setSelectedRecords(records.map(record => record.id));
                        } else {
                          setSelectedRecords([]);
                        }
                      }}
                    />
                  </TableHead>
                  <TableHead>ID</TableHead>
                  <TableHead>教室号</TableHead>
                  <TableHead>用户</TableHead>
                  <TableHead>成绩</TableHead>
                  <TableHead>代码</TableHead>
                  <TableHead>训练日期</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>收益率</TableHead>
                  <TableHead>累计收益率</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {records.map((record) => (
                  <TableRow key={record.id}>
                    <TableCell>
                      <Checkbox
                        checked={selectedRecords.includes(record.id)}
                        onCheckedChange={(checked) => {
                          if (checked) {
                            setSelectedRecords(prev => [...prev, record.id]);
                          } else {
                            setSelectedRecords(prev => prev.filter(id => id !== record.id));
                          }
                        }}
                      />
                    </TableCell>
                    <TableCell className="font-medium">{record.id}</TableCell>
                    <TableCell>{record.classroomNo || '-'}</TableCell>
                    <TableCell>
                      {record.user ? (
                        <div className="flex flex-col">
                          <span className="font-medium">{record.user.username}</span>
                          <span className="text-xs text-muted-foreground">ID: {record.userId}</span>
                        </div>
                      ) : (
                        record.userId || '-'
                      )}
                    </TableCell>
                    <TableCell>{record.score || '-'}</TableCell>
                    <TableCell>{record.code || '-'}</TableCell>
                    <TableCell>
                      {record.trainingDate ? format(new Date(record.trainingDate), 'yyyy-MM-dd HH:mm', { locale: zhCN }) : '-'}
                    </TableCell>
                    <TableCell>{record.status || '-'}</TableCell>
                    <TableCell>{record.profitPercent ? `${record.profitPercent}%` : '-'}</TableCell>
                    <TableCell className={record.totalProfitPercent > 0 ? 'text-red-500' : record.totalProfitPercent < 0 ? 'text-green-500' : ''}>
                      {record.totalProfitPercent ? `${record.totalProfitPercent}%` : '-'}
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-2">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => showEditModal(record)}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => showDeleteDialog(record.id)}
                          className="text-destructive hover:text-destructive"
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>

          {records.length === 0 && (
            <div className="text-center py-8">
              <p className="text-muted-foreground">暂无数据</p>
            </div>
          )}

          {/* 分页 */}
          <DataTablePagination
            currentPage={searchParams.page}
            pageSize={searchParams.limit}
            totalCount={totalCount}
            onPageChange={(page, limit) => setSearchParams(prev => ({ ...prev, page, limit }))}
          />
        </CardContent>
      </Card>

      {/* 创建/编辑记录对话框 */}
      <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
        <DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{isCreateForm ? '创建提交记录' : '编辑提交记录'}</DialogTitle>
            <DialogDescription>
              {isCreateForm ? '创建一个新的提交记录' : '编辑现有提交记录信息'}
            </DialogDescription>
          </DialogHeader>

          {isCreateForm ? (
            <Form {...createForm}>
              <form onSubmit={createForm.handleSubmit(handleCreateSubmit)} className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <FormField
                    control={createForm.control}
                    name="classroomNo"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>教室号</FormLabel>
                        <FormControl>
                          <Input placeholder="请输入教室号" {...field} value={field.value || ''} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={createForm.control}
                    name="userId"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>用户ID</FormLabel>
                        <FormControl>
                          <Input placeholder="请输入用户ID" {...field} value={field.value || ''} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />


                  <FormField
                    control={createForm.control}
                    name="score"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>成绩</FormLabel>
                        <FormControl>
                          <Input 
                            type="number" 
                            step="0.01"
                            placeholder="请输入成绩" 
                            {...field} 
                            value={field.value || ''}
                            onChange={(e) => field.onChange(e.target.value ? parseFloat(e.target.value) : null)}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={createForm.control}
                    name="code"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>代码</FormLabel>
                        <FormControl>
                          <Input placeholder="请输入代码" {...field} value={field.value || ''} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={createForm.control}
                    name="status"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>状态</FormLabel>
                        <FormControl>
                          <Input 
                            type="number"
                            placeholder="请输入状态" 
                            {...field} 
                            value={field.value || ''}
                            onChange={(e) => field.onChange(e.target.value ? parseInt(e.target.value) : null)}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={createForm.control}
                    name="holdingStock"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>持股</FormLabel>
                        <FormControl>
                          <Input placeholder="请输入持股信息" {...field} value={field.value || ''} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={createForm.control}
                    name="holdingCash"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>持币</FormLabel>
                        <FormControl>
                          <Input placeholder="请输入持币信息" {...field} value={field.value || ''} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={createForm.control}
                    name="price"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>价格</FormLabel>
                        <FormControl>
                          <Input 
                            type="number" 
                            step="0.01"
                            placeholder="请输入价格" 
                            {...field} 
                            value={field.value || ''}
                            onChange={(e) => field.onChange(e.target.value ? parseFloat(e.target.value) : null)}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={createForm.control}
                    name="profitAmount"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>收益金额</FormLabel>
                        <FormControl>
                          <Input 
                            type="number" 
                            step="0.01"
                            placeholder="请输入收益金额" 
                            {...field} 
                            value={field.value || ''}
                            onChange={(e) => field.onChange(e.target.value ? parseFloat(e.target.value) : null)}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={createForm.control}
                    name="profitPercent"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>收益率(%)</FormLabel>
                        <FormControl>
                          <Input 
                            type="number" 
                            step="0.01"
                            placeholder="请输入收益率" 
                            {...field} 
                            value={field.value || ''}
                            onChange={(e) => field.onChange(e.target.value ? parseFloat(e.target.value) : null)}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={createForm.control}
                    name="totalProfitAmount"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>累计收益金额</FormLabel>
                        <FormControl>
                          <Input 
                            type="number" 
                            step="0.01"
                            placeholder="请输入累计收益金额" 
                            {...field} 
                            value={field.value || ''}
                            onChange={(e) => field.onChange(e.target.value ? parseFloat(e.target.value) : null)}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={createForm.control}
                    name="totalProfitPercent"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>累计收益率(%)</FormLabel>
                        <FormControl>
                          <Input 
                            type="number" 
                            step="0.01"
                            placeholder="请输入累计收益率" 
                            {...field} 
                            value={field.value || ''}
                            onChange={(e) => field.onChange(e.target.value ? parseFloat(e.target.value) : null)}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={createForm.control}
                    name="mark"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>标记</FormLabel>
                        <FormControl>
                          <Input placeholder="请输入标记" {...field} value={field.value || ''} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={createForm.control}
                    name="trainingDate"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>训练日期</FormLabel>
                        <FormControl>
                          <Input 
                            type="datetime-local"
                            placeholder="请选择训练日期" 
                            {...field} 
                            value={field.value ? format(new Date(field.value), "yyyy-MM-dd'T'HH:mm") : ''}
                            onChange={(e) => field.onChange(e.target.value ? new Date(e.target.value) : null)}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>

                <DialogFooter>
                  <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
                    取消
                  </Button>
                  <Button type="submit">创建</Button>
                </DialogFooter>
              </form>
            </Form>
          ) : (
            <Form {...updateForm}>
              <form onSubmit={updateForm.handleSubmit(handleUpdateSubmit)} className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <FormField
                    control={updateForm.control}
                    name="classroomNo"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>教室号</FormLabel>
                        <FormControl>
                          <Input placeholder="请输入教室号" {...field} value={field.value || ''} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={updateForm.control}
                    name="userId"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>用户ID</FormLabel>
                        <FormControl>
                          <Input placeholder="请输入用户ID" {...field} value={field.value || ''} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />


                  <FormField
                    control={updateForm.control}
                    name="score"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>成绩</FormLabel>
                        <FormControl>
                          <Input 
                            type="number" 
                            step="0.01"
                            placeholder="请输入成绩" 
                            {...field} 
                            value={field.value || ''}
                            onChange={(e) => field.onChange(e.target.value ? parseFloat(e.target.value) : null)}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={updateForm.control}
                    name="code"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>代码</FormLabel>
                        <FormControl>
                          <Input placeholder="请输入代码" {...field} value={field.value || ''} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={updateForm.control}
                    name="status"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>状态</FormLabel>
                        <FormControl>
                          <Input 
                            type="number"
                            placeholder="请输入状态" 
                            {...field} 
                            value={field.value || ''}
                            onChange={(e) => field.onChange(e.target.value ? parseInt(e.target.value) : null)}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={updateForm.control}
                    name="holdingStock"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>持股</FormLabel>
                        <FormControl>
                          <Input placeholder="请输入持股信息" {...field} value={field.value || ''} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={updateForm.control}
                    name="holdingCash"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>持币</FormLabel>
                        <FormControl>
                          <Input placeholder="请输入持币信息" {...field} value={field.value || ''} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={updateForm.control}
                    name="price"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>价格</FormLabel>
                        <FormControl>
                          <Input 
                            type="number" 
                            step="0.01"
                            placeholder="请输入价格" 
                            {...field} 
                            value={field.value || ''}
                            onChange={(e) => field.onChange(e.target.value ? parseFloat(e.target.value) : null)}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={updateForm.control}
                    name="profitAmount"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>收益金额</FormLabel>
                        <FormControl>
                          <Input 
                            type="number" 
                            step="0.01"
                            placeholder="请输入收益金额" 
                            {...field} 
                            value={field.value || ''}
                            onChange={(e) => field.onChange(e.target.value ? parseFloat(e.target.value) : null)}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={updateForm.control}
                    name="profitPercent"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>收益率(%)</FormLabel>
                        <FormControl>
                          <Input 
                            type="number" 
                            step="0.01"
                            placeholder="请输入收益率" 
                            {...field} 
                            value={field.value || ''}
                            onChange={(e) => field.onChange(e.target.value ? parseFloat(e.target.value) : null)}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={updateForm.control}
                    name="totalProfitAmount"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>累计收益金额</FormLabel>
                        <FormControl>
                          <Input 
                            type="number" 
                            step="0.01"
                            placeholder="请输入累计收益金额" 
                            {...field} 
                            value={field.value || ''}
                            onChange={(e) => field.onChange(e.target.value ? parseFloat(e.target.value) : null)}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={updateForm.control}
                    name="totalProfitPercent"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>累计收益率(%)</FormLabel>
                        <FormControl>
                          <Input 
                            type="number" 
                            step="0.01"
                            placeholder="请输入累计收益率" 
                            {...field} 
                            value={field.value || ''}
                            onChange={(e) => field.onChange(e.target.value ? parseFloat(e.target.value) : null)}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={updateForm.control}
                    name="mark"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>标记</FormLabel>
                        <FormControl>
                          <Input placeholder="请输入标记" {...field} value={field.value || ''} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={updateForm.control}
                    name="trainingDate"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>训练日期</FormLabel>
                        <FormControl>
                          <Input 
                            type="datetime-local"
                            placeholder="请选择训练日期" 
                            {...field} 
                            value={field.value ? format(new Date(field.value), "yyyy-MM-dd'T'HH:mm") : ''}
                            onChange={(e) => field.onChange(e.target.value ? new Date(e.target.value) : null)}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>

                <DialogFooter>
                  <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
                    取消
                  </Button>
                  <Button type="submit">更新</Button>
                </DialogFooter>
              </form>
            </Form>
          )}
        </DialogContent>
      </Dialog>

      {/* 删除确认对话框 */}
      <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除</AlertDialogTitle>
            <AlertDialogDescription>
              确定要删除这个提交记录吗？此操作无法撤销。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction onClick={handleDelete}>删除</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 对比对话框 */}
      <SubmissionComparisonDialog
        open={compareDialogOpen}
        onOpenChange={setCompareDialogOpen}
        selectedRecords={selectedRecordsData}
      />
    </div>
  );
};

export default SubmissionRecordsPage;