import React, { useState, useEffect, useMemo } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Plus, Edit2, Trash2, Copy, Eye, X, Search, RotateCcw } from 'lucide-react';
import { Button, Space, Table as AntdTable, Modal, message, Input, Form as AntdForm, Select, DatePicker, TimePicker, InputNumber, Switch, Radio, Checkbox, Card, Alert, Cascader, Upload, Tooltip } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { toast } from 'sonner';
import * as FormApi from '../api/bpm/form';
import { DICT_TYPE, getDictLabel } from '../utils/dict';
import { dateFormatter } from '../utils/formatTime';
import { setConfAndFields2, FormCreateData } from '../utils/formCreate';
import { useTranslation } from 'react-i18next';
import FormUploadField from './FormUploadField';
import './IsolationWorkListTable.css';

export default function FormManagement() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const location = useLocation();
  
  // 调试信息
  useEffect(() => {
    console.log('FormManagement 组件已加载');
  }, []);
  
  const [loading, setLoading] = useState(true);
  const [list, setList] = useState<FormApi.FormVO[]>([]);
  const [total, setTotal] = useState(0);
  const [queryParams, setQueryParams] = useState<FormApi.FormPageParams>({
    pageNo: 1,
    pageSize: 10,
    name: '',
  });
  const [searchName, setSearchName] = useState('');
  const [detailForm] = AntdForm.useForm();
  const [formStatusUpdating, setFormStatusUpdating] = useState<Record<number, boolean>>({});
  
  // 详情弹窗
  const [detailVisible, setDetailVisible] = useState(false);
  const [detailData, setDetailData] = useState<FormCreateData>({
    rule: [],
    option: {}
  });
  const defaultFormConfig = {
    name: '',
    labelPosition: 'right',
    formSize: 'middle',
    labelSuffix: '',
    labelWidth: 100,
    layoutColumns: 1 as 1 | 2 | 3,
    hideRequiredMark: false,
    showValidationError: true,
    inlineValidation: false,
    showSubmitButton: false,
    showResetButton: false,
  };

  // 合并表单配置：兼容 option.formConfig 或 option 即 formConfig 两种后端结构
  const getMergedFormConfig = () => ({
    ...defaultFormConfig,
    ...(detailData.option?.formConfig || detailData.option || {}),
  });

  // 渲染字段预览（支持嵌套结构）
  const renderFieldPreview = (field: any, parentSpanStyle?: React.CSSProperties): React.ReactNode => {
    const formConfig = getMergedFormConfig();
    const layoutColumns = formConfig.layoutColumns || 1;
    const spanStyle = parentSpanStyle || (layoutColumns > 1 ? { gridColumn: `span ${Math.min(layoutColumns, field.span || 1)}` } : undefined);
    const wrapperStyle: React.CSSProperties = spanStyle || {};

    // 处理容器类型（card 和 grid）
    if (field.type === 'card') {
      const children = field.children || [];
      // 优先使用 label（字段名称），如果没有则使用 cardTitle，最后使用默认值
      const cardTitle = field.label || field.cardTitle || t('common.cardContainer');
      return (
        <div key={field.id} style={spanStyle} className="mb-4">
          <Card title={cardTitle} className="w-full">
            <div className="space-y-4">
              {children.map((child: any) => renderFieldPreview(child))}
            </div>
          </Card>
        </div>
      );
    }

    if (field.type === 'grid') {
      const gridColumns = field.gridColumns || 2;
      const children = field.children || [];
      return (
        <div key={field.id} style={spanStyle} className="mb-4">
          <div
            style={{
              display: 'grid',
              gridTemplateColumns: `repeat(${gridColumns}, minmax(0, 1fr))`,
              gap: '12px',
              rowGap: '16px',
            }}
          >
            {children.map((child: any) => {
              const childSpanStyle = gridColumns > 1 
                ? { gridColumn: `span ${Math.min(gridColumns, child.span || 1)}` } 
                : undefined;
              return (
                <div key={child.id} style={childSpanStyle}>
                  {renderFieldPreview(child)}
                </div>
              );
            })}
          </div>
        </div>
      );
    }

    // 处理 alert 类型
    if (field.type === 'alert') {
      const themeClass =
        field.alertTheme === 'dark'
          ? 'bg-gray-800 text-white border-gray-700'
          : '';
      return (
        <div key={field.id} className="mb-4" style={spanStyle}>
          <Alert
            message={field.alertTitle || field.label}
            description={field.alertDescription}
            type={field.alertType || 'info'}
            showIcon={field.alertShowIcon !== false}
            closable={field.alertClosable}
            closeText={field.alertCloseText}
            className={`${field.alertCentered ? 'text-center' : ''} ${themeClass}`}
            banner
            style={field.style}
          />
          {field.hint && <div className="text-xs text-gray-400 mt-1">{field.hint}</div>}
        </div>
      );
    }

    // 与表单设计器一致：每字段 labelCol/wrapperCol
    const getItemLayout = (f: any) => {
      const isTop = formConfig.labelPosition === 'top';
      const w = f.labelWidth ?? formConfig.labelWidth ?? 100;
      const effective = (typeof w === 'number' && w > 0) ? w : 100;
      return {
        labelCol: isTop ? undefined : { flex: `${effective}px`, style: { minWidth: `${effective}px`, textAlign: formConfig.labelPosition === 'right' ? 'right' : 'left' } },
        wrapperCol: isTop ? undefined : { flex: 'auto', style: { minWidth: 0 } },
      };
    };
    const itemLayout = getItemLayout(field);

    // 处理普通字段
    switch (field.type) {
      case 'textarea':
        return (
          <div key={field.id} style={wrapperStyle}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || t('common.pleaseInput') }] : []}
              help={field.hint}
              labelCol={itemLayout.labelCol}
              wrapperCol={itemLayout.wrapperCol}
            >
              <Input.TextArea 
                placeholder={typeof field.placeholder === 'string' ? field.placeholder : t('common.pleaseInput')} 
                rows={4}
                allowClear={field.showClear}
                maxLength={field.maxLength}
                readOnly={field.readOnly}
                disabled={field.disabled}
                size={field.size || 'middle'}
              />
            </AntdForm.Item>
          </div>
        );
      case 'password':
        return (
          <div key={field.id} style={wrapperStyle}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || t('common.pleaseInput') }] : []}
              help={field.hint}
              labelCol={itemLayout.labelCol}
              wrapperCol={itemLayout.wrapperCol}
            >
              <Input.Password 
                placeholder={typeof field.placeholder === 'string' ? field.placeholder : t('common.pleaseInput')}
                allowClear={field.showClear}
                maxLength={field.maxLength}
                readOnly={field.readOnly}
                disabled={field.disabled}
                size={field.size || 'middle'}
              /> 
            </AntdForm.Item>
          </div>
        );
      case 'number':
        return (
          <div key={field.id} style={wrapperStyle}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || t('common.pleaseInput') }] : []}
              help={field.hint}
              labelCol={itemLayout.labelCol}
              wrapperCol={itemLayout.wrapperCol}
            >
              <InputNumber 
                style={{ width: '100%' }} 
                placeholder={typeof field.placeholder === 'string' ? field.placeholder : t('common.pleaseInput')}
                max={field.maxLength}
                readOnly={field.readOnly}
                disabled={field.disabled}
                size={field.size || 'middle'}
              />
            </AntdForm.Item>
          </div>
        );
      case 'select':
        return (
          <div key={field.id} style={wrapperStyle}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || t('common.pleaseSelect') }] : []}
              help={field.hint}
              labelCol={itemLayout.labelCol}
              wrapperCol={itemLayout.wrapperCol}
            >
              <Select
                placeholder={typeof field.placeholder === 'string' ? field.placeholder : t('common.pleaseSelect')}
                allowClear={field.showClear}
                disabled={field.disabled}
                size={field.size || 'middle'}
              >
                {(field.options || []).map((opt: any, idx: number) => (
                  <Select.Option key={idx} value={opt.value}>{opt.label}</Select.Option>
                ))}
              </Select>
            </AntdForm.Item>
          </div>
        );
      case 'date':
        return (
          <div key={field.id} style={wrapperStyle}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || t('common.pleaseSelectDate') }] : []}
              help={field.hint}
              labelCol={itemLayout.labelCol}
              wrapperCol={itemLayout.wrapperCol}
            >
              <DatePicker 
                className="w-full" 
                placeholder={typeof field.placeholder === 'string' ? field.placeholder : undefined}
                allowClear={field.showClear}
                disabled={field.disabled}
                size={field.size || 'middle'}
              />
            </AntdForm.Item>
          </div>
        );
      case 'daterange':
        return (
          <div key={field.id} style={wrapperStyle}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || t('common.pleaseSelectDateRange') }] : []}
              help={field.hint}
              labelCol={itemLayout.labelCol}
              wrapperCol={itemLayout.wrapperCol}
            >
              <DatePicker.RangePicker 
                className="w-full" 
                placeholder={Array.isArray(field.placeholder) ? field.placeholder as [string, string] : [t('common.startDate'), t('common.endDate')]}
                allowClear={field.showClear}
                disabled={field.disabled}
                size={field.size || 'middle'}
              />
            </AntdForm.Item>
          </div>
        );
      case 'datetime':
        return (
          <div key={field.id} style={wrapperStyle}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || t('common.pleaseSelectDateTime') }] : []}
              help={field.hint}
              labelCol={itemLayout.labelCol}
              wrapperCol={itemLayout.wrapperCol}
            >
              <DatePicker 
                className="w-full" 
                placeholder={typeof field.placeholder === 'string' ? field.placeholder : undefined}
                allowClear={field.showClear}
                disabled={field.disabled}
                size={field.size || 'middle'}
                showTime={{ format: 'HH:mm:ss' }}
                format="YYYY-MM-DD HH:mm:ss"
              />
            </AntdForm.Item>
          </div>
        );
      case 'timepicker':
        return (
          <div key={field.id} style={wrapperStyle}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || t('common.pleaseSelectTime') }] : []}
              help={field.hint}
              labelCol={itemLayout.labelCol}
              wrapperCol={itemLayout.wrapperCol}
            >
              <TimePicker 
                className="w-full" 
                placeholder={typeof field.placeholder === 'string' ? field.placeholder : undefined}
                allowClear={field.showClear}
                disabled={field.disabled}
                size={field.size || 'middle'}
                format="HH:mm:ss"
              />
            </AntdForm.Item>
          </div>
        );
      case 'switch':
        return (
          <div key={field.id} style={wrapperStyle}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || t('common.pleaseSelect') }] : []}
              help={field.hint}
              valuePropName="checked"
              labelCol={itemLayout.labelCol}
              wrapperCol={itemLayout.wrapperCol}
            >
              <Switch disabled={field.disabled} />
            </AntdForm.Item>
          </div>
        );
      case 'radio':
        return (
          <div key={field.id} style={wrapperStyle}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || t('common.pleaseSelect') }] : []}
              help={field.hint}
              labelCol={itemLayout.labelCol}
              wrapperCol={itemLayout.wrapperCol}
            >
              <Radio.Group disabled={field.disabled}>
                {(field.options || []).map((opt: any, idx: number) => (
                  <Radio key={idx} value={opt.value}>{opt.label}</Radio>
                ))}
              </Radio.Group>
            </AntdForm.Item>
          </div>
        );
      case 'checkbox':
        return (
          <div key={field.id} style={wrapperStyle}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || t('common.pleaseSelect') }] : []}
              help={field.hint}
              labelCol={itemLayout.labelCol}
              wrapperCol={itemLayout.wrapperCol}
            >
              <Checkbox.Group disabled={field.disabled}>
                {(field.options || []).map((opt: any, idx: number) => (
                  <Checkbox key={idx} value={opt.value}>{opt.label}</Checkbox>
                ))}
              </Checkbox.Group>
            </AntdForm.Item>
          </div>
        );
      case 'cascader':
        return (
          <div key={field.id} style={wrapperStyle}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || t('common.pleaseSelect') }] : []}
              help={field.hint}
              labelCol={itemLayout.labelCol}
              wrapperCol={itemLayout.wrapperCol}
            >
              <Cascader
                placeholder={typeof field.placeholder === 'string' ? field.placeholder : t('common.pleaseSelect')}
                options={field.cascaderOptions || []}
                className="w-full"
                allowClear={field.showClear}
                disabled={field.disabled}
                size={field.size || 'middle'}
              />
            </AntdForm.Item>
          </div>
        );
      case 'upload':
        return (
          <div key={field.id} style={wrapperStyle}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || t('common.upload') }] : []}
              help={field.hint}
              labelCol={itemLayout.labelCol}
              wrapperCol={itemLayout.wrapperCol}
            >
              <FormUploadField
                uploadType={field.uploadType}
                maxCount={field.maxCount}
                accept={field.accept}
                disabled={field.disabled}
              />
            </AntdForm.Item>
          </div>
        );
      default:
        return (
          <div key={field.id} style={wrapperStyle}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || t('common.pleaseInput') }] : []}
              help={field.hint}
              labelCol={itemLayout.labelCol}
              wrapperCol={itemLayout.wrapperCol}
            >
              <Input 
                type={field.inputType || 'text'}
                placeholder={typeof field.placeholder === 'string' ? field.placeholder : t('common.pleaseInput')}
                allowClear={field.showClear}
                maxLength={field.maxLength}
                readOnly={field.readOnly}
                disabled={field.disabled}
                size={field.size || 'middle'}
              />
            </AntdForm.Item>
          </div>
        );
    }
  };

  /** 查询列表 */
  const getList = async (params?: FormApi.FormPageParams) => {
    const searchParams = params || queryParams;
    setLoading(true);
    try {
      console.log('FormManagement: 开始获取表单列表', searchParams);
      const data = await FormApi.getFormPage(searchParams);
      console.log('FormManagement: 获取到数据', data);
      setList(data.list || []);
      setTotal(data.total || 0);
    } catch (error: any) {
      console.error('FormManagement: 获取表单列表失败', error);
      toast.error(error.message || t('form.fetchFormListFailed'));
      // 确保即使失败也显示空列表
      setList([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  };

  // 处理表单状态切换
  const handleFormStatusChanged = async (record: FormApi.FormVO, newStatus: number) => {
    if (!record.id) {
      message.error('表单ID不存在');
      return;
    }

    // 设置该记录为更新中状态
    setFormStatusUpdating(prev => ({ ...prev, [record.id!]: true }));

    try {
      await FormApi.updateFormStatus({
        id: record.id,
        status: newStatus,
      });
      
      // 更新本地列表中的状态
      setList(prev => 
        prev.map(item => 
          item.id === record.id ? { ...item, status: newStatus } : item
        )
      );
      
      message.success(newStatus === 0 ? '已开启' : '已关闭');
    } catch (error: any) {
      console.error('更新表单状态失败:', error);
      message.error(error?.message || '更新状态失败');
    } finally {
      // 清除更新中状态
      setFormStatusUpdating(prev => {
        const newState = { ...prev };
        delete newState[record.id!];
        return newState;
      });
    }
  };

  useEffect(() => {
    getList();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [queryParams.pageNo, queryParams.pageSize, queryParams.name]);

  // 监听路径变化，当从表单编辑器返回时自动刷新列表
  useEffect(() => {
    // 当路径包含 /form 时，刷新列表以确保显示最新数据
    if (location.pathname.includes('/form')) {
      getList();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [location.pathname]);

  /** 添加/修改操作 */
  const openForm = (type: string, id?: number) => {
    const query: Record<string, string> = { type };
    if (id !== undefined && (typeof id === 'number' || typeof id === 'string')) {
      query.id = String(id);
    }
    // 记录来源菜单：用于从表单设计器返回时恢复菜单到「隔离作业 > 表单管理」
    sessionStorage.setItem(
      'formDesignerSource',
      JSON.stringify({ menu: 'isolationWork', subMenu: 'formManagement' })
    );
    // 跳转到表单编辑器（这里需要根据实际路由配置）
    navigate(`/bpm/form/editor?${new URLSearchParams(query).toString()}`);
  };

  /** 删除按钮操作 */
  const handleDelete = async (id: number) => {
    Modal.confirm({
      title: t('form.confirmDeleteForm'),
      content: t('form.confirmDeleteFormText'),
      okText: t('common.confirm'),
      cancelText: t('common.cancel'),
      onOk: async () => {
        try {
          await FormApi.deleteForm(id);
          toast.success(t('form.deleteFormSuccess'));
          await getList();
        } catch (error: any) {
          toast.error(error.message || t('form.deleteFormFailed'));
        }
      }
    });
  };

  /** 详情操作 */
  const openDetail = async (rowId: number) => {
    try {
      const data = await FormApi.getForm(rowId);
      setConfAndFields2(setDetailData, data.conf, data.fields);
      setDetailVisible(true);
    } catch (error: any) {
      toast.error(error.message || t('form.fetchFormDetailFailed'));
    }
  };

  // 搜索
  const handleSearch = () => {
    setQueryParams({
      ...queryParams,
      pageNo: 1,
      name: searchName.trim() || undefined,
    });
  };

  // 重置
  const handleReset = () => {
    setSearchName('');
    setQueryParams({
      ...queryParams,
      pageNo: 1,
      name: undefined,
    });
  };

  // 表格列配置
  const columns: ColumnsType<FormApi.FormVO> = [
    {
      title: t('form.formId'),
      dataIndex: 'id',
      width: 90,
      align: 'center',
    },
    {
      title: t('form.formName'),
      dataIndex: 'name',
      width: 220,
      align: 'center',
      render: (name: string, record: FormApi.FormVO) => {
        if (!name || name === '-') return <span>{name || '-'}</span>;
        return (
          <span
            className="text-blue-600 cursor-pointer hover:text-blue-800 hover:underline"
            onClick={(e) => {
              e.stopPropagation();
              openDetail(record.id!);
            }}
          >
            {name}
          </span>
        );
      },
    },
    {
      title: t('form.formStatus'),
      dataIndex: 'status',
      width: 110,
      align: 'center',
      render: (status: number, record: FormApi.FormVO) => {
        const isChecked = Number(status) === 0; // 0 是开启
        const isUpdating = formStatusUpdating[record.id!] || false;
        return (
          <Switch
            checked={isChecked}
            onChange={(checked) => {
              if (!isUpdating) {
                const newStatus = checked ? 0 : 1; // 0 是开启，1 是关闭
                handleFormStatusChanged(record, newStatus);
              }
            }}
            disabled={isUpdating}
            loading={isUpdating}
            style={{
              ...(isChecked ? { 
                backgroundColor: '#52c41a',
              } : {})
            }}
            className={isChecked ? 'ant-switch-checked-green' : ''}
          />
        );
      },
    },
    {
      title: t('form.formRemark'),
      dataIndex: 'remark',
      width: 260,
      align: 'center',
      render: (text: string) => {
        const remarkText = text || '-';
        const maxLength = 20;
        const shouldTruncate = remarkText.length > maxLength;
        const displayText = shouldTruncate ? remarkText.slice(0, maxLength) + '...' : remarkText;
        
        return (
          <Tooltip placement="topLeft" title={remarkText}>
            <span>{displayText}</span>
          </Tooltip>
        );
      },
    },
    {
      title: t('form.formCreateTime'),
      dataIndex: 'createTime',
      width: 180,
      align: 'center',
      render: (text: string) => dateFormatter(text),
    },
    {
      title: t('form.formOperation'),
      width: 260,
      align: 'center',
      fixed: 'right',
      render: (_: any, record: FormApi.FormVO) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<Copy className="w-4 h-4" style={{ color: '#000000' }} />}
            onClick={() => openForm('copy', record.id)}
            style={{ color: '#000000' }}
            className="transition-colors"
            onMouseEnter={(e) => {
              e.currentTarget.style.color = '#1677ff';
              e.currentTarget.style.textDecoration = 'underline';
              e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #1677ff');
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.color = '#000000';
              e.currentTarget.style.textDecoration = 'none';
              e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #000000');
            }}
          >
            {t('form.copy')}
          </Button>
          <Button
            type="link"
            size="small"
            icon={<Edit2 className="w-4 h-4" style={{ color: '#000000' }} />}
            onClick={() => openForm('update', record.id)}
            style={{ color: '#000000' }}
            className="transition-colors"
            onMouseEnter={(e) => {
              e.currentTarget.style.color = '#1677ff';
              e.currentTarget.style.textDecoration = 'underline';
              e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #1677ff');
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.color = '#000000';
              e.currentTarget.style.textDecoration = 'none';
              e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #000000');
            }}
          >
            {t('common.edit')}
          </Button>
          <Button
            type="link"
            size="small"
            icon={<Eye className="w-4 h-4" style={{ color: '#000000' }} />}
            onClick={() => openDetail(record.id!)}
            style={{ color: '#000000' }}
            className="transition-colors"
            onMouseEnter={(e) => {
              e.currentTarget.style.color = '#1677ff';
              e.currentTarget.style.textDecoration = 'underline';
              e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #1677ff');
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.color = '#000000';
              e.currentTarget.style.textDecoration = 'none';
              e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #000000');
            }}
          >
            {t('form.preview')}
          </Button>
          <Button
            type="link"
            size="small"
            icon={<Trash2 className="w-4 h-4" style={{ color: '#000000' }} />}
            onClick={() => handleDelete(record.id!)}
            style={{ color: '#000000' }}
            className="transition-colors"
            onMouseEnter={(e) => {
              e.currentTarget.style.color = '#1677ff';
              e.currentTarget.style.textDecoration = 'underline';
              e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #1677ff');
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.color = '#000000';
              e.currentTarget.style.textDecoration = 'none';
              e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #000000');
            }}
          >
            {t('common.delete')}
          </Button>
        </Space>
      ),
    },
  ];

  // 计算分页数据
  const totalPages = Math.ceil(total / queryParams.pageSize) || 1;

  return (
    <div className="space-y-6">
      {/* 操作栏和表格容器 */}
      <div className="bg-white rounded-2xl border border-gray-200/50 shadow-sm overflow-hidden">
        {/* 查询与操作栏 */}
        <div className="p-4 lg:p-5 border-b border-gray-200/50">
          <div className="flex flex-wrap items-center justify-between gap-3">
            {/* 左侧：搜索条件 + 紧跟其后的 搜索 / 重置 按钮 */}
            <div className="flex flex-wrap items-center gap-3">
              <div className="flex items-center gap-3">
                <span className="text-sm text-gray-700">{t('form.formName')}：</span>
                <Input
                  value={searchName}
                  onChange={(e) => setSearchName(e.target.value)}
                  placeholder={t('form.formNamePlaceholder')}
                  allowClear
                  style={{ width: 240 }}
                />
              </div>
              <Space size="small">
                <Button type="primary" icon={<Search className="w-4 h-4" />} onClick={handleSearch}>
                  {t('common.search')}
                </Button>
                <Button icon={<RotateCcw className="w-4 h-4" />} onClick={handleReset}>
                  {t('common.reset')}
                </Button>
              </Space>
            </div>
            {/* 右侧：新增按钮保持在最右侧 */}
            <div>
              <Button
                type="primary"
                icon={<Plus className="w-4 h-4" />}
                onClick={() => openForm('create')}
              >
                {t('form.addForm')}
              </Button>
            </div>
          </div>
        </div>

        {/* 表格容器 */}
        <div className="isolation-work-list-table overflow-hidden min-w-0">
          <AntdTable
            loading={loading}
            columns={columns}
            dataSource={list}
            rowKey="id"
            pagination={false}
            scroll={{ x: 'max-content' }}
            rowClassName={(_, index) =>
              index !== undefined && index % 2 === 1 ? 'isolation-work-list-row-alt' : ''
            }
          />
        </div>
      </div>

      {/* 分页 */}
      {total > 0 && (
        <div className="bg-white rounded-lg border border-gray-200 px-6 py-4">
          <div className="flex items-center justify-between">
            <div className="text-sm text-gray-600">
              {t('form.totalRecords')} <span className="text-blue-600 font-medium">{total}</span> {t('form.recordsUnit')}
            </div>
            <div className="flex gap-2">
              <Button
                onClick={() => setQueryParams({ ...queryParams, pageNo: queryParams.pageNo - 1 })}
                disabled={queryParams.pageNo <= 1}
              >
                {t('common.prevPage')}
              </Button>
              <span className="px-4 py-2 text-sm text-gray-600 flex items-center">
                {queryParams.pageNo} / {totalPages}
              </span>
              <Button
                onClick={() => setQueryParams({ ...queryParams, pageNo: queryParams.pageNo + 1 })}
                disabled={queryParams.pageNo >= totalPages}
              >
                {t('common.nextPage')}
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* 表单详情的弹窗 */}
      <Modal
        title={t('form.formDetail')}
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={[
          <div key="tip" style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: '12px', width: '100%' }}>
            <span style={{ color: '#ff4d4f', fontSize: '14px' }}>{t('form.formPreviewTip')}</span>
            <Button
              key="submit"
              type="primary"
              onClick={() => {
                // 详情预览提交按钮不执行任何操作，也不关闭弹窗
                return;
              }}
            >
              {t('common.submit')}
            </Button>
          </div>,
        ]}
        width={960}
      >
        <div className="p-2">
          {(() => {
            const formConfig = getMergedFormConfig();
            const layoutColumns = formConfig.layoutColumns || 1;
            const gridStyle = layoutColumns > 1 ? {
              display: 'grid',
              gridTemplateColumns: `repeat(${layoutColumns}, minmax(0, 1fr))`,
              gap: '12px',
              rowGap: '16px',
            } : undefined;

            const isHorizontal = formConfig.labelPosition !== 'top';
            const effectiveLabelWidth = Math.max(0, Number(formConfig.labelWidth) || defaultFormConfig.labelWidth);
            return (
              <>
                <style>{`
                  .form-preview-grid .ant-form-item { margin-bottom: 12px; }
                  .form-preview-grid .ant-form-item-control { min-width: 0; }
                `}</style>
                <AntdForm
                  form={detailForm}
                  layout={formConfig.labelPosition === 'top' ? 'vertical' : 'horizontal'}
                  size={formConfig.formSize === 'default' ? 'middle' : formConfig.formSize}
                  requiredMark={formConfig.hideRequiredMark ? false : undefined}
                  wrapperCol={formConfig.labelPosition === 'top' ? undefined : { flex: 'auto', style: { minWidth: 0 } }}
                >
                  <div 
                    style={gridStyle} 
                    className={layoutColumns === 1 ? 'space-y-4' : 'form-preview-grid'}
                  >
                    {(detailData.rule || []).map((field: any) => renderFieldPreview(field))}
                  </div>
                </AntdForm>
              </>
            );
          })()}
        </div>
      </Modal>
    </div>
  );
}

