import React, { useState, useEffect, useRef } from 'react';
import { Search, Plus, RefreshCw, Edit2, Trash2, Database, Eye } from 'lucide-react';
import { dictTypeApi, DictTypeVO, PageParam } from '../api/DictType';
import { dictDataApi, DictDataVO, PageParam as DictDataPageParam } from '../api/DictData';
import { toast } from 'sonner';
import { formatDateTimeFull } from '../utils/formatTime';
import { getIntDictOptions, DICT_TYPE, getDictLabel, setDictOptions, DictDataType } from '../utils/dict';
import { Modal, Tag, Space, Table, Button, Input, Tooltip } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Button as UIButton } from './ui/button';
import { Table as UITable, TableBody, TableCell, TableHead, TableHeader, TableRow } from './ui/table';
import DictTypeForm, { DictTypeFormRef } from './DictTypeForm';
import DictDataForm, { DictDataFormRef } from './DictDataForm';
import type { ColumnsType } from 'antd/es/table';
import PermissionWrapper from './PermissionWrapper';
import { hasPermission } from '../utils/permission';
import { useTranslation } from 'react-i18next';
import './IsolationWorkListTable.css';

const { Search: AntSearch } = Input;
const AntButton = Button;

export default function DictTypeManagement() {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(true);
  const [list, setList] = useState<DictTypeVO[]>([]);
  const [total, setTotal] = useState(0);
  const [queryParams, setQueryParams] = useState<PageParam>({
    pageNo: 1,
    pageSize: 20,
    name: undefined,
    type: undefined,
  });
  
  // 弹框相关状态
  const [modalVisible, setModalVisible] = useState(false);
  const [currentDictType, setCurrentDictType] = useState<DictTypeVO | null>(null);
  const [dictDataList, setDictDataList] = useState<DictDataVO[]>([]);
  const [dictDataTotal, setDictDataTotal] = useState(0);
  const [dictDataLoading, setDictDataLoading] = useState(false);
  const [dictDataSearchTerm, setDictDataSearchTerm] = useState('');
  const [dictDataPageParams, setDictDataPageParams] = useState<DictDataPageParam>({
    pageNo: 1,
    pageSize: 10,
  });
  
  const formRef = useRef<DictTypeFormRef>(null);
  const dictDataFormRef = useRef<DictDataFormRef>(null);

  // 获取字典类型列表
  const getList = async (params?: PageParam) => {
    const currentParams = params || queryParams;
    setLoading(true);
    try {
      console.log('DictTypeManagement: 开始获取字典类型列表', currentParams);
      const response = await dictTypeApi.getDictTypePage(currentParams);
      console.log('DictTypeManagement: API 响应', response);
      
      // 处理响应数据 - 兼容不同的响应格式
      let data;
      if (response && typeof response === 'object') {
        // 如果响应有 data 属性，使用 data；否则直接使用 response
        data = (response as any).data !== undefined ? (response as any).data : response;
      } else {
        data = response;
      }
      
      // 确保 data 是对象
      if (!data || typeof data !== 'object') {
        console.warn('DictTypeManagement: 响应数据格式异常', data);
        setList([]);
        setTotal(0);
        return;
      }
      
      const typeList = data.list || [];
      setList(typeList);
      setTotal(data.total || 0);
      console.log('DictTypeManagement: 设置列表数据', typeList, '总数', data.total);
    } catch (error: any) {
      console.error('DictTypeManagement: 获取字典类型列表失败', error);
      console.error('错误详情:', {
        message: error?.message,
        response: error?.response,
        status: error?.response?.status,
        data: error?.response?.data,
      });
      setList([]);
      setTotal(0);
      const errorMessage = error?.response?.data?.message || 
                          error?.message || 
                          '获取字典类型列表失败，请检查网络连接或联系管理员';
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  // 打开查看全部弹框
  const openDictDataModal = async (dictType: DictTypeVO) => {
    setCurrentDictType(dictType);
    setModalVisible(true);
    setDictDataSearchTerm('');
    setDictDataPageParams({ pageNo: 1, pageSize: 10 });
    await loadDictDataFull(dictType.type, { pageNo: 1, pageSize: 10 });
  };

  // 加载完整的字典数据列表（弹框内使用）
  const loadDictDataFull = async (dictType: string, params?: DictDataPageParam) => {
    setDictDataLoading(true);
    try {
      const searchParams: DictDataPageParam = {
        ...params,
        dictType,
        label: dictDataSearchTerm || undefined,
      };
      console.log('DictTypeManagement: 开始获取字典数据', searchParams);
      const response = await dictDataApi.getDictDataPage(searchParams);
      console.log('DictTypeManagement: 字典数据 API 响应', response);
      
      // 处理响应数据 - 兼容不同的响应格式
      let data;
      if (response && typeof response === 'object') {
        data = (response as any).data !== undefined ? (response as any).data : response;
      } else {
        data = response;
      }
      
      if (!data || typeof data !== 'object') {
        console.warn('DictTypeManagement: 字典数据响应格式异常', data);
        setDictDataList([]);
        setDictDataTotal(0);
        return;
      }
      
      setDictDataList(data?.list || []);
      setDictDataTotal(data?.total || 0);
      console.log('DictTypeManagement: 设置字典数据列表', data?.list, '总数', data?.total);
    } catch (error: any) {
      console.error('DictTypeManagement: 获取字典数据失败', error);
      console.error('错误详情:', {
        message: error?.message,
        response: error?.response,
        status: error?.response?.status,
        data: error?.response?.data,
      });
      setDictDataList([]);
      setDictDataTotal(0);
      const errorMessage = error?.response?.data?.message || 
                          error?.message || 
                          '获取字典数据失败，请检查网络连接或联系管理员';
      toast.error(errorMessage);
    } finally {
      setDictDataLoading(false);
    }
  };

  // 搜索字典数据
  const handleDictDataSearch = () => {
    if (currentDictType) {
      setDictDataPageParams(prev => ({ ...prev, pageNo: 1 }));
      loadDictDataFull(currentDictType.type, { ...dictDataPageParams, pageNo: 1 });
    }
  };

  // 分页变化
  const handleDictDataPageChange = (page: number, pageSize: number) => {
    setDictDataPageParams({ pageNo: page, pageSize });
    if (currentDictType) {
      loadDictDataFull(currentDictType.type, { pageNo: page, pageSize });
    }
  };

  // 加载字典管理的状态选项（从接口获取，0=开启，1=关闭）
  const [statusOptions, setStatusOptions] = useState<Array<{ label: string; value: number }>>([]);
  
  useEffect(() => {
    const loadDictStatusOptions = async () => {
      try {
        // 从接口获取 common_status 字典数据
        const response = await dictDataApi.getDictDataPage({
          pageNo: 1,
          pageSize: -1,
          dictType: 'common_status',
        });
        
        const data = (response as any)?.data || response;
        const dictList = data?.list || [];
        
        if (Array.isArray(dictList) && dictList.length > 0) {
          // 使用接口返回的字典数据
          const options = dictList.map((item: any) => ({
            label: item.label,
            value: typeof item.value === 'string' ? parseInt(item.value, 10) : Number(item.value),
          }));
          setStatusOptions(options);
          console.log('DictTypeManagement: 从接口获取状态选项', options);
        } else {
          // 如果接口没有数据，使用字典管理的默认定义：0=开启，1=关闭
          setStatusOptions([
            { label: '开启', value: 0 },
            { label: '关闭', value: 1 },
          ]);
        }
      } catch (error) {
        console.error('加载状态选项失败:', error);
        // 使用字典管理的默认定义：0=开启，1=关闭
        setStatusOptions([
          { label: '开启', value: 0 },
          { label: '关闭', value: 1 },
        ]);
      }
    };

    loadDictStatusOptions();
  }, []);

  // 组件挂载和分页参数变化时获取数据
  useEffect(() => {
    getList();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [queryParams.pageNo, queryParams.pageSize]);

  // 搜索
  const handleQuery = () => {
    const newParams = { ...queryParams, pageNo: 1 };
    setQueryParams(newParams);
    getList(newParams);
  };

  // 重置搜索
  const resetQuery = () => {
    const resetParams: PageParam = {
      pageNo: 1,
      pageSize: 20,
      name: undefined,
      type: undefined,
    };
    // 先设置状态，确保搜索框能同步更新
    setQueryParams(resetParams);
    // 使用重置后的参数立即获取列表
    getList(resetParams);
  };

  // 打开表单
  const openForm = (type: string, id?: number) => {
    if (formRef.current) {
      formRef.current.open(type, id);
    }
  };

  // 删除字典类型
  const handleDelete = async (id: number, name: string) => {
    Modal.confirm({
      title: t('common.confirmDelete'),
      icon: <ExclamationCircleOutlined />,
      content: (
        <div>
          <p>{t('common.confirmDeleteText')} <strong>"{name}"</strong>?</p>
          <p style={{ color: '#ff4d4f', marginTop: '8px' }}>{t('common.confirmDeleteWarning')}</p>
        </div>
      ),
      okText: t('common.confirmDelete'),
      okType: 'danger',
      cancelText: t('common.cancel'),
      onOk: async () => {
        try {
          await dictTypeApi.deleteDictType(id);
          toast.success(t('common.deleteSuccess'));
          await getList();
        } catch (error: any) {
          toast.error(error.message || t('common.deleteFailed'));
        }
      },
    });
  };

  // 打开字典数据表单
  const openDictDataForm = (type: string, id?: number) => {
    if (dictDataFormRef.current && currentDictType) {
      dictDataFormRef.current.open(type, id, currentDictType.type);
    }
  };

  // 删除字典数据
  const handleDeleteDictData = async (id: number, label: string) => {
    Modal.confirm({
      title: t('common.confirmDelete'),
      icon: <ExclamationCircleOutlined />,
      content: (
        <div>
          <p>{t('common.confirmDeleteText')} <strong>"{label}"</strong>?</p>
          <p style={{ color: '#ff4d4f', marginTop: '8px' }}>{t('common.confirmDeleteWarning')}</p>
        </div>
      ),
      okText: t('common.confirmDeleteButton'),
      okType: 'danger',
      cancelText: t('common.cancel'),
      onOk: async () => {
        try {
          await dictDataApi.deleteDictData(id);
          toast.success(t('common.deleteSuccess'));
          if (currentDictType) {
            await loadDictDataFull(currentDictType.type, dictDataPageParams);
          }
        } catch (error: any) {
          toast.error(error.message || t('common.deleteFailed'));
        }
      },
    });
  };

  // 获取状态标签 - 从接口获取的字典数据中查找
  const getStatusLabel = (status: number | string | undefined) => {
    const statusNum = typeof status === 'string' ? parseInt(status, 10) : Number(status);
    // 从接口获取的状态选项中查找
    const statusOption = statusOptions.find(opt => opt.value === statusNum);
    if (statusOption) {
      return statusOption.label;
    }
    // 如果找不到，使用字典管理的默认定义：0=开启，1=关闭
    return statusNum === 0 ? '开启' : '关闭';
  };

  // 获取状态样式 - 字典管理接口：0=开启（绿色），1=关闭（灰色）
  const getStatusStyle = (status: number | string | undefined) => {
    const statusNum = typeof status === 'string' ? parseInt(status, 10) : Number(status);
    // 字典管理接口定义：0=开启（绿色），1=关闭（灰色）
    return statusNum === 0
      ? 'bg-green-100 text-green-700'
      : 'bg-gray-100 text-gray-700';
  };

  // 获取颜色类型标签
  const getColorTypeTag = (colorType: string) => {
    if (!colorType) return null;
    const colorMap: Record<string, string> = {
      'success': 'green',
      'info': 'blue',
      'warning': 'orange',
      'danger': 'red',
      'primary': 'blue',
      'default': 'default',
    };
    return <Tag color={colorMap[colorType] || 'default'}>{colorType}</Tag>;
  };

  // 字典数据表格列定义
  const dictDataColumns: ColumnsType<DictDataVO> = [
    {
      title: t('table.dictCode'),
      dataIndex: 'id',
      key: 'id',
      align: 'center',
      width: 100,
    },
    {
      title: t('table.dictLabel'),
      dataIndex: 'label',
      key: 'label',
      align: 'center',
      width: 120,
      ellipsis: true,
    },
    {
      title: t('table.dictValue'),
      dataIndex: 'value',
      key: 'value',
      align: 'center',
      width: 120,
      ellipsis: true,
    },
    {
      title: t('table.dictSort'),
      dataIndex: 'sort',
      key: 'sort',
      align: 'center',
      width: 100,
    },
    {
      title: t('table.status'),
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      width: 100,
      render: (status: number) => (
        <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getStatusStyle(status)}`}>
          {getStatusLabel(status)}
        </span>
      ),
    },
    {
      title: t('table.colorType'),
      dataIndex: 'colorType',
      key: 'colorType',
      align: 'center',
      width: 100,
      render: (colorType: string) => getColorTypeTag(colorType),
    },
    {
      title: t('table.remark'),
      dataIndex: 'remark',
      key: 'remark',
      align: 'center',
      width: 150,
      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('table.operation'),
      key: 'action',
      align: 'center',
      width: 150,
      fixed: 'right',
      render: (_: any, record: DictDataVO) => (
        <div className="flex items-center gap-2 justify-center">
          <PermissionWrapper permission="system:dict:update">
            <UIButton
              variant="ghost"
              size="sm"
              onClick={() => openDictDataForm('update', record.id)}
              className="h-8 px-2 transition-colors hover:!text-[#1677ff] hover:!underline"
              style={{ color: '#000000' }}
              onMouseEnter={(e) => {
                const target = e.currentTarget as HTMLElement;
                target.style.setProperty('color', '#1677ff', 'important');
                target.style.setProperty('text-decoration', 'underline', 'important');
                const svg = target.querySelector('svg');
                if (svg) {
                  svg.style.setProperty('color', '#1677ff', 'important');
                }
                const span = target.querySelector('span');
                if (span) {
                  span.style.setProperty('color', '#1677ff', 'important');
                }
              }}
              onMouseLeave={(e) => {
                const target = e.currentTarget as HTMLElement;
                target.style.setProperty('color', '#000000', 'important');
                target.style.setProperty('text-decoration', 'none', 'important');
                const svg = target.querySelector('svg');
                if (svg) {
                  svg.style.setProperty('color', '#000000', 'important');
                }
                const span = target.querySelector('span');
                if (span) {
                  span.style.setProperty('color', '#000000', 'important');
                }
              }}
            >
              <Edit2 className="w-4 h-4" style={{ color: '#000000' }} />
              <span className="ml-1">{t('common.edit')}</span>
            </UIButton>
          </PermissionWrapper>
          <PermissionWrapper permission="system:dict:delete">
            <UIButton
              variant="ghost"
              size="sm"
              onClick={() => handleDeleteDictData(record.id!, record.label)}
              className="h-8 px-2 transition-colors hover:!text-[#1677ff] hover:!underline"
              style={{ color: '#000000' }}
              onMouseEnter={(e) => {
                const target = e.currentTarget as HTMLElement;
                target.style.setProperty('color', '#1677ff', 'important');
                target.style.setProperty('text-decoration', 'underline', 'important');
                const svg = target.querySelector('svg');
                if (svg) {
                  svg.style.setProperty('color', '#1677ff', 'important');
                }
                const span = target.querySelector('span');
                if (span) {
                  span.style.setProperty('color', '#1677ff', 'important');
                }
              }}
              onMouseLeave={(e) => {
                const target = e.currentTarget as HTMLElement;
                target.style.setProperty('color', '#000000', 'important');
                target.style.setProperty('text-decoration', 'none', 'important');
                const svg = target.querySelector('svg');
                if (svg) {
                  svg.style.setProperty('color', '#000000', 'important');
                }
                const span = target.querySelector('span');
                if (span) {
                  span.style.setProperty('color', '#000000', 'important');
                }
              }}
            >
              <Trash2 className="w-4 h-4" style={{ color: '#000000' }} />
              <span className="ml-1">{t('common.delete')}</span>
            </UIButton>
          </PermissionWrapper>
        </div>
      ),
    },
  ];

  return (
    <div className="space-y-4">
      {/* 搜索栏 */}
      <div className="bg-white rounded-xl border border-gray-200/50 shadow-sm p-4 lg:p-5">
        <div className="flex items-center justify-between gap-3 lg:gap-4 flex-wrap min-w-0">
          {/* 搜索条件 + 搜索、重置紧跟其后 */}
          <div className="flex items-center gap-2 lg:gap-3 flex-wrap min-w-0">
            <div className="flex items-center gap-2 lg:gap-3 w-[200px] min-w-[100px] flex-shrink">
              <label className="text-sm font-medium text-gray-700 whitespace-nowrap flex-shrink-0">{t('form.dictName')}：</label>
              <Input
                value={queryParams.name || ''}
                onChange={(e) => setQueryParams(prev => ({ ...prev, name: e.target.value }))}
                onPressEnter={handleQuery}
                placeholder={t('form.dictNamePlaceholder')}
                className="min-w-0 w-full"
                allowClear
              />
            </div>
            <div className="flex items-center gap-2 lg:gap-3 w-[200px] min-w-[100px] flex-shrink">
              <label className="text-sm font-medium text-gray-700 whitespace-nowrap flex-shrink-0">{t('form.dictType')}：</label>
              <Input
                value={queryParams.type || ''}
                onChange={(e) => setQueryParams(prev => ({ ...prev, type: e.target.value }))}
                onPressEnter={handleQuery}
                placeholder={t('form.dictTypePlaceholder')}
                className="min-w-0 w-full"
                allowClear
              />
            </div>
            <Space className="flex-shrink-0" size="small">
              <PermissionWrapper permission="system:dict:query">
                <Button
                  type="primary"
                  icon={<Search className="w-4 h-4" />}
                  onClick={handleQuery}
                >
                  {t('common.search')}
                </Button>
              </PermissionWrapper>
              
              <PermissionWrapper permission="system:dict:query">
                <Button
                  icon={<RefreshCw className="w-4 h-4" />}
                  onClick={resetQuery}
                >
                  {t('common.reset')}
                </Button>
              </PermissionWrapper>
            </Space>
          </div>

          {/* 新增等按钮组保持在最右侧 */}
          <Space className="flex-shrink-0" size="small">
            <PermissionWrapper permission="system:dict:create">
              <Button
                type="primary"
                icon={<Plus className="w-4 h-4" />}
                onClick={() => openForm('create')}
              >
                {t('common.addNew')}
              </Button>
            </PermissionWrapper>
          </Space>
        </div>
      </div>

      {/* 表格列表 */}
      <div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
        <div className="system-mgmt-shadcn-table">
        <UITable>
          <TableHeader>
            <TableRow>
              <TableHead className="w-[100px] text-center">{t('table.dictId')}</TableHead>
              <TableHead className="w-[150px]">{t('table.dictName')}</TableHead>
              <TableHead className="w-[200px]">{t('table.dictType')}</TableHead>
              <TableHead className="w-[100px] text-center">{t('table.status')}</TableHead>
              <TableHead>{t('table.remark')}</TableHead>
              <TableHead className="w-[180px] text-center">{t('table.createTime')}</TableHead>
              <TableHead className="w-[280px] text-center">{t('table.operation')}</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading ? (
              <TableRow>
                <TableCell colSpan={7} className="text-center py-8 text-gray-500">
                  加载中...
                </TableCell>
              </TableRow>
            ) : list.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="text-center py-8 text-gray-500">
                  暂无数据
                </TableCell>
              </TableRow>
            ) : (
              list.map((row, index) => (
                <TableRow
                  key={row.id}
                  className={index % 2 === 1 ? 'system-mgmt-row-alt hover:bg-gray-50' : 'hover:bg-gray-50'}
                >
                  <TableCell className="text-center">{row.id}</TableCell>
                  <TableCell className="font-medium">{row.name}</TableCell>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <Database className="w-4 h-4 text-blue-500" />
                      <span className="font-mono text-sm">{row.type}</span>
                    </div>
                  </TableCell>
                  <TableCell className="text-center">
                    <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getStatusStyle(row.status)}`}>
                      {getStatusLabel(row.status)}
                    </span>
                  </TableCell>
                  <TableCell className="text-sm text-gray-600">
                    {(() => {
                      const text = row.remark || '-';
                      const maxLength = 20;
                      const shouldTruncate = text.length > maxLength;
                      const displayText = shouldTruncate ? text.slice(0, maxLength) + '...' : text;
                      
                      return (
                        <Tooltip placement="topLeft" title={text}>
                          <span>{displayText}</span>
                        </Tooltip>
                      );
                    })()}
                  </TableCell>
                  <TableCell className="text-center text-sm text-gray-600">
                    {formatDateTimeFull(row.createTime)}
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center gap-2 justify-center">
                      <PermissionWrapper permission="system:dict:update">
                        <UIButton
                          variant="ghost"
                          size="sm"
                          onClick={() => openForm('update', row.id)}
                          className="h-8 px-2"
                        >
                          <Edit2 className="w-4 h-4" />
                          <span className="ml-1">{t('common.edit')}</span>
                        </UIButton>
                      </PermissionWrapper>
                      <PermissionWrapper permission="system:dict:query">
                        <UIButton
                          variant="ghost"
                          size="sm"
                          onClick={() => openDictDataModal(row)}
                          className="h-8 px-2"
                        >
                          <Eye className="w-4 h-4" />
                          <span className="ml-1">{t('table.data')}</span>
                        </UIButton>
                      </PermissionWrapper>
                      <PermissionWrapper permission="system:dict:delete">
                        <UIButton
                          variant="ghost"
                          size="sm"
                          onClick={() => handleDelete(row.id!, row.name)}
                          className="h-8 px-2 text-red-600 hover:text-red-700"
                        >
                          <Trash2 className="w-4 h-4" />
                          <span className="ml-1">{t('common.delete')}</span>
                        </UIButton>
                      </PermissionWrapper>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </UITable>
        </div>
      </div>

      {/* 分页 */}
      {!loading && list.length > 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('common.total')} <span className="text-blue-600 font-medium">{total}</span> {t('common.records')}
            </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} / {Math.ceil(total / queryParams.pageSize!) || 1}
              </span>
              <Button
                onClick={() => setQueryParams({ ...queryParams, pageNo: queryParams.pageNo! + 1 })}
                disabled={queryParams.pageNo! >= Math.ceil(total / queryParams.pageSize!)}
              >
                {t('common.nextPage')}
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* 字典数据查看全部弹框 */}
      <Modal
        title={
          <div className="flex items-center gap-2">
            <Database className="w-5 h-5 text-blue-500" />
            <span>{t('form.dictData')} - {currentDictType?.name}</span>
            <Tag className="ml-2">{currentDictType?.type}</Tag>
          </div>
        }
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={1400}
        destroyOnClose
      >
        <div className="space-y-4">
          {/* 工具栏 */}
          <div className="flex items-center justify-between gap-4">
            <AntSearch
              placeholder={t('common.search')}
              value={dictDataSearchTerm}
              onChange={(e) => setDictDataSearchTerm(e.target.value)}
              onSearch={handleDictDataSearch}
              style={{ width: 300 }}
              enterButton
            />
            <PermissionWrapper permission="system:dict:create">
              <UIButton
                onClick={() => openDictDataForm('create')}
                className="flex items-center gap-2"
              >
                <Plus className="w-4 h-4" />
                {t('form.addDictItem')}
              </UIButton>
            </PermissionWrapper>
          </div>

          {/* 表格 */}
          <div className="isolation-work-list-table">
            <Table
              columns={dictDataColumns}
              dataSource={dictDataList}
              rowKey="id"
              loading={dictDataLoading}
              pagination={false}
              size="small"
              scroll={{ x: 1400 }}
              rowClassName={(_, index) =>
                index !== undefined && index % 2 === 1 ? 'isolation-work-list-row-alt' : ''
              }
            />
          </div>

          {/* 分页 */}
          {!dictDataLoading && dictDataTotal > 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('common.total')} <span className="text-blue-600 font-medium">{dictDataTotal}</span> {t('common.records')}
                </div>
                <div className="flex gap-2">
                  <Button
                    onClick={() => handleDictDataPageChange(dictDataPageParams.pageNo! - 1, dictDataPageParams.pageSize!)}
                    disabled={dictDataPageParams.pageNo! <= 1}
                  >
                    {t('common.prevPage')}
                  </Button>
                  <span className="px-4 py-2 text-sm text-gray-600 flex items-center">
                    {dictDataPageParams.pageNo} / {Math.ceil(dictDataTotal / dictDataPageParams.pageSize!) || 1}
                  </span>
                  <Button
                    onClick={() => handleDictDataPageChange(dictDataPageParams.pageNo! + 1, dictDataPageParams.pageSize!)}
                    disabled={dictDataPageParams.pageNo! >= Math.ceil(dictDataTotal / dictDataPageParams.pageSize!)}
                  >
                    {t('common.nextPage')}
                  </Button>
                </div>
              </div>
            </div>
          )}
        </div>
      </Modal>

      {/* 表单弹窗 */}
      <DictTypeForm ref={formRef} onSuccess={getList} />
      <DictDataForm 
        ref={dictDataFormRef} 
        onSuccess={async () => {
          if (currentDictType) {
            await loadDictDataFull(currentDictType.type, dictDataPageParams);
          }
        }} 
      />
    </div>
  );
}
