import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate, useLocation } from 'react-router-dom';
import { Search, RotateCcw, BookOpen, ChevronLeft, ChevronRight, Plus } from 'lucide-react';
import { Checkbox } from './ui/checkbox';
import { Button as AntButton, Modal, Form, Input, Select, TreeSelect, DatePicker, Tooltip, Descriptions, Table as AntdTable, Space } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { Button } from './ui/button';
import { toast } from 'sonner';
import dayjs, { Dayjs } from 'dayjs';
import { in_site, type NotifyMessageVO, type SendNotifyMessageVO } from '../api/notification/in_site';
import { dateFormatter } from '../utils/formatTime';
import { deptApi } from '../api/dept';
import { userApi } from '../api/user';
import { roleApi } from '../api/Role';
import { handleTree } from '../utils/tree';
import { DICT_TYPE, getDictLabel, getDictObj } from '../utils/dict';

interface MessageItem {
  id: number;
  title: string;
  type: string;
  sender: string;
  sendTime: string;
  createTime?: string | number;
  content: string;
  status: 'read' | 'unread';
  readTime?: string | number;
  userId?: number;
  userType?: number;
  templateId?: number;
  templateCode?: string;
  templateParams?: any;
  templateType?: number;
}

export default function InboxMessage() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const location = useLocation();
  const [messageTitle, setMessageTitle] = useState<string>('');
  const [messageStatus, setMessageStatus] = useState<string | undefined>(undefined);
  const [startDate, setStartDate] = useState<Dayjs | null>(null);
  const [endDate, setEndDate] = useState<Dayjs | null>(null);
  const [selectedIds, setSelectedIds] = useState<number[]>([]);
  const [messages, setMessages] = useState<MessageItem[]>([]);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [total, setTotal] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(false);
  const [sendModalVisible, setSendModalVisible] = useState<boolean>(false);
  const [sendLoading, setSendLoading] = useState<boolean>(false);
  const [detailModalVisible, setDetailModalVisible] = useState<boolean>(false);
  const [detailMessage, setDetailMessage] = useState<MessageItem | null>(null);
  const [detailLoading, setDetailLoading] = useState<boolean>(false);
  const [deptList, setDeptList] = useState<any[]>([]);
  const [userList, setUserList] = useState<any[]>([]);
  const [roleList, setRoleList] = useState<any[]>([]);
  const [form] = Form.useForm();
  const pageSize = 10;
  const totalPages = Math.ceil(total / pageSize);
  const isSearchingRef = React.useRef(false);

  // 将API数据转换为组件使用的格式
  const convertMessageData = (data: NotifyMessageVO): MessageItem => {
    // 根据 templateType 获取字典标签
    const typeLabel = data.templateType 
      ? getDictLabel(DICT_TYPE.SYSTEM_NOTIFY_TEMPLATE_TYPE, data.templateType) 
      : t('notificationManagement.notifyMessage');
    
    return {
      id: data.id,
      title: data.title || '',
      type: typeLabel,
      sender: data.templateNickname || t('notificationManagement.system'),
      sendTime: data.createTime || '',
      createTime: data.createTime,
      content: data.templateContent || '',
      status: data.readStatus === true ? 'read' : 'unread',
      readTime: data.readTime,
      userId: data.userId,
      userType: data.userType,
      templateId: data.templateId,
      templateCode: data.templateCode,
      templateParams: data.templateParams,
      templateType: data.templateType
    };
  };

  // 获取消息列表（若调用方传入 searchParams 的某字段，则优先用传入值，包括 undefined 表示清空该条件）
  const fetchMessages = async (searchParams?: {
    title?: string;
    status?: string;
    startDate?: Dayjs | null;
    endDate?: Dayjs | null;
    page?: number;
  }) => {
    setLoading(true);
    try {
      const has = (key: string) => searchParams && key in searchParams;
      const title = has('title') ? searchParams!.title : messageTitle;
      const status = has('status') ? searchParams!.status : messageStatus;
      const start = has('startDate') ? searchParams!.startDate : startDate;
      const end = has('endDate') ? searchParams!.endDate : endDate;
      const page = has('page') ? searchParams!.page : currentPage;

      const params: any = {
        pageNo: page,
        pageSize: pageSize
      };

      // 添加筛选条件（只有当值存在时才添加）
      if (title && title.trim()) {
        params.title = title.trim();
      }
      if (status !== undefined && status !== null && status !== '') {
        // 将字符串转换为 boolean：'true' 表示已读(true)，'false' 表示未读(false)
        params.readStatus = status === 'true' ? true : status === 'false' ? false : undefined;
      }
      if (start) {
        // createTime[0] 格式：YYYY-MM-DD 00:00:00
        params['createTime[0]'] = start.format('YYYY-MM-DD 00:00:00');
      }
      if (end) {
        // createTime[1] 格式：YYYY-MM-DD 23:59:59
        params['createTime[1]'] = end.format('YYYY-MM-DD 23:59:59');
      }

      const response = await in_site.getMyPage(params);
      const messageList = (response.list || []).map(convertMessageData);
      setMessages(messageList);
      setTotal(response.total || 0);
    } catch (error: any) {
      console.error('获取消息列表失败:', error);
      toast.error(error?.response?.data?.message || t('notificationManagement.getMessageListFailed'));
      setMessages([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  };

  // 初始加载和分页变化时重新获取数据
  useEffect(() => {
    // 如果是搜索触发的，不在这里处理
    if (isSearchingRef.current) {
      isSearchingRef.current = false;
      return;
    }
    fetchMessages();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentPage]);

  // 加载部门、用户、角色列表（用于发送消息）
  useEffect(() => {
    const loadData = async () => {
      try {
        // 加载部门列表
        const deptData = await deptApi.getSimpleDeptList();
        const deptTreeData = deptData.map(dept => ({
          id: dept.id!,
          name: dept.name,
          parentId: dept.parentId,
        }));
        const treeData = handleTree(deptTreeData, 'id', 'parentId', 'children');
        setDeptList(treeData);

        // 加载用户列表（简单列表）
        const userResponse = await userApi.getUserPage({ pageNo: 1, pageSize: -1 });
        setUserList(userResponse.list || []);

        // 加载角色列表
        const roleResponse = await roleApi.getRolePage({ pageNo: 1, pageSize: -1 });
        setRoleList(roleResponse.list || []);
      } catch (error) {
        console.error('加载数据失败:', error);
      }
    };
    loadData();
  }, []);

  // 全选/取消全选
  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      setSelectedIds(messages.map(msg => msg.id));
    } else {
      setSelectedIds([]);
    }
  };

  // 单个选择
  const handleSelectItem = (id: number, checked: boolean) => {
    if (checked) {
      setSelectedIds([...selectedIds, id]);
    } else {
      setSelectedIds(selectedIds.filter(selectedId => selectedId !== id));
    }
  };

  // 搜索
  const handleSearch = () => {
    // 标记为搜索触发，避免 useEffect 重复调用
    isSearchingRef.current = true;
    const targetPage = 1;
    // 先更新页码
    setCurrentPage(targetPage);
    // 直接使用当前搜索条件进行搜索
    fetchMessages({
      title: messageTitle,
      status: messageStatus,
      startDate: startDate,
      endDate: endDate,
      page: targetPage
    });
  };

  // 重置：清空筛选条件并立即用空条件重新拉取列表
  const handleReset = async () => {
    // 标记为搜索触发，避免 useEffect 重复调用
    isSearchingRef.current = true;
    // 清空筛选条件
    setMessageTitle('');
    setMessageStatus(undefined);
    setStartDate(null);
    setEndDate(null);
    setSelectedIds([]);
    setCurrentPage(1);
    // 使用空条件重新拉取列表（显式传参，不依赖 state），并等待完成以保证列表刷新
    await fetchMessages({
      title: '',
      status: undefined,
      startDate: null,
      endDate: null,
      page: 1
    });
  };

  // 标记已读
  const handleMarkAsRead = async () => {
    if (selectedIds.length === 0) {
      toast.warning(t('notificationManagement.pleaseSelectMessages'));
      return;
    }
    setLoading(true);
    try {
      await in_site.markAsRead(selectedIds);
      setSelectedIds([]);
      // 重新获取数据
      await fetchMessages();
      toast.success(t('notificationManagement.markReadSuccess'));
      // 触发事件，通知消息通知组件更新未读数量
      window.dispatchEvent(new CustomEvent('messageRead'));
    } catch (error: any) {
      console.error('标记已读失败:', error);
      toast.error(error?.response?.data?.message || t('notificationManagement.markReadFailed'));
    } finally {
      setLoading(false);
    }
  };

  // 全部已读
  const handleMarkAllAsRead = async () => {
    setLoading(true);
    try {
      await in_site.markAllAsRead();
      setSelectedIds([]);
      // 重新获取数据
      await fetchMessages();
      toast.success(t('notificationManagement.markAllReadSuccess'));
      // 触发事件，通知消息通知组件更新未读数量
      window.dispatchEvent(new CustomEvent('messageRead'));
    } catch (error: any) {
      console.error('全部标记已读失败:', error);
      toast.error(error?.response?.data?.message || t('notificationManagement.markAllReadFailed'));
    } finally {
      setLoading(false);
    }
  };

  // 查看详情
  const handleViewDetail = async (id: number) => {
    setDetailLoading(true);
    try {
      // 先查找当前消息是否未读
      const currentMessage = messages.find(msg => msg.id === id);
      const isUnread = currentMessage?.status === 'unread';
      
      // 如果消息未读，先调用 update-read 更新状态
      if (isUnread) {
        try {
          await in_site.markAsRead([id]);
          // 更新列表数据
          await fetchMessages();
          // 触发事件，通知消息通知组件更新未读数量
          window.dispatchEvent(new CustomEvent('messageRead'));
        } catch (error) {
          console.error('标记已读失败:', error);
          toast.error(t('notificationManagement.markReadFailed'));
          setDetailLoading(false);
          return;
        }
      }
      
      // 获取消息详情
      const messageData = await in_site.getMessage(id);
      const messageItem = convertMessageData(messageData);
      
      setDetailMessage(messageItem);
      setDetailModalVisible(true);
    } catch (error: any) {
      console.error('获取消息详情失败:', error);
      toast.error(error?.response?.data?.message || t('notificationManagement.getMessageDetailFailed'));
    } finally {
      setDetailLoading(false);
    }
  };

  // 打开发送消息弹窗
  const handleOpenSendModal = () => {
    setSendModalVisible(true);
    form.resetFields();
    form.setFieldsValue({
      type: '通知消息',
      targetType: 'all', // 默认全体用户
    });
  };

  // 发送消息
  const handleSendMessage = async () => {
    try {
      const values = await form.validateFields();
      setSendLoading(true);

      const sendData: SendNotifyMessageVO = {
        title: values.title,
        content: values.content,
        type: values.type || '通知消息',
      };

      // 根据接收对象类型设置不同的ID列表
      if (values.targetType === 'user') {
        sendData.userIds = values.userIds || [];
      } else if (values.targetType === 'dept') {
        sendData.deptIds = values.deptIds || [];
      } else if (values.targetType === 'role') {
        sendData.roleIds = values.roleIds || [];
      } else {
        // 全体用户，不传ID列表
      }

      await in_site.sendMessage(sendData);
      toast.success(t('notificationManagement.sendMessageSuccess'));
      setSendModalVisible(false);
      form.resetFields();
      // 刷新消息列表
      await fetchMessages();
    } catch (error: any) {
      if (error?.errorFields) {
        // 表单验证错误
        return;
      }
      console.error('发送消息失败:', error);
      toast.error(error?.response?.data?.message || t('notificationManagement.sendMessageFailed'));
    } finally {
      setSendLoading(false);
    }
  };


  // 使用从API获取的消息列表（已根据筛选条件过滤）
  const filteredMessages = messages;

  const isAllSelected = filteredMessages.length > 0 && selectedIds.length === filteredMessages.length;

  // 定义表格列
  const columns: ColumnsType<MessageItem> = [
    {
      title: t('notificationManagement.messageTitle'),
      dataIndex: 'title',
      key: 'title',
      width: '15%',
      render: (text: string) => <span className="text-sm text-gray-900">{text}</span>,
    },
    {
      title: t('notificationManagement.messageType'),
      dataIndex: 'type',
      key: 'type',
      width: '10%',
      render: (type: string, record: MessageItem) => {
        const dictObj = record.templateType 
          ? getDictObj(DICT_TYPE.SYSTEM_NOTIFY_TEMPLATE_TYPE, record.templateType)
          : null;
        
        let bgColor = 'bg-gray-100';
        let textColor = 'text-gray-700';
        
        if (dictObj) {
          switch (dictObj.colorType) {
            case 'blue':
              bgColor = 'bg-blue-100';
              textColor = 'text-blue-700';
              break;
            case 'green':
              bgColor = 'bg-green-100';
              textColor = 'text-green-700';
              break;
            case 'orange':
              bgColor = 'bg-orange-100';
              textColor = 'text-orange-700';
              break;
            default:
              bgColor = 'bg-gray-100';
              textColor = 'text-gray-700';
          }
        }
        
        return (
          <span className={`inline-flex px-3 py-1 rounded-lg text-xs ${bgColor} ${textColor}`}>
            {type}
          </span>
        );
      },
    },
    {
      title: t('notificationManagement.sender'),
      dataIndex: 'sender',
      key: 'sender',
      width: '10%',
      render: (text: string) => <span className="text-sm text-gray-900">{text}</span>,
    },
    {
      title: t('table.createTime'),
      dataIndex: 'createTime',
      key: 'createTime',
      width: '12%',
      render: (createTime: string | number | undefined, record: MessageItem) => {
        const time = createTime || record.sendTime;
        return <span className="text-sm text-gray-900">{time ? dateFormatter(time) : '-'}</span>;
      },
    },
    {
      title: t('notificationManagement.messageContent'),
      dataIndex: 'content',
      key: 'content',
      width: '20%',
      render: (content: string) => {
        const contentText = content || '-';
        const maxLength = 20;
        const shouldTruncate = contentText.length > maxLength;
        const displayText = shouldTruncate ? contentText.slice(0, maxLength) + '...' : contentText;

        const goToMyTask = () => {
          sessionStorage.setItem('navigateToMenu', JSON.stringify({
            menu: 'isolationWork',
            subMenu: 'myTask',
          }));
          if (location.pathname === '/dashboard') {
            window.dispatchEvent(new CustomEvent('switchToMenu', {
              detail: { menu: 'isolationWork', subMenu: 'myTask' },
            }));
          } else {
            navigate('/dashboard');
          }
        };

        return (
          <Tooltip placement="topLeft" title={contentText}>
            <span
              role="button"
              tabIndex={0}
              className="cursor-pointer hover:underline"
              style={{ color: '#1677ff', fontSize: 14 }}
              onClick={(e) => { e.stopPropagation(); goToMyTask(); }}
              onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); goToMyTask(); } }}
            >
              {displayText}
            </span>
          </Tooltip>
        );
      },
    },
    {
      title: t('notificationManagement.messageStatus'),
      dataIndex: 'status',
      key: 'status',
      width: '8%',
      render: (status: 'read' | 'unread') => {
        return status === 'read' ? (
          <span className="inline-flex px-3 py-1 rounded-lg text-xs bg-gray-100 text-gray-700">
            {t('notificationManagement.read')}
          </span>
        ) : (
          <span className="inline-flex px-3 py-1 rounded-lg text-xs bg-red-100 text-red-700">
            {t('notificationManagement.unread')}
          </span>
        );
      },
    },
    {
      title: t('notificationManagement.readTime'),
      dataIndex: 'readTime',
      key: 'readTime',
      width: '12%',
      render: (readTime: string | number | undefined) => {
        return <span className="text-sm text-gray-900">{readTime ? dateFormatter(readTime) : '-'}</span>;
      },
    },
    {
      title: t('common.operation'),
      key: 'action',
      width: '8%',
      align: 'center',
      render: (_: any, record: MessageItem) => {
        return (
          <Button 
            variant="ghost"
            size="sm"
            onClick={() => handleViewDetail(record.id)}
            className="h-8 px-2 transition-colors"
            style={{ color: record.status === 'unread' ? '#f56565' : '#1677ff' }}
            onMouseEnter={(e) => {
              if (record.status === 'unread') {
                e.currentTarget.style.color = '#f56565';
                e.currentTarget.style.textDecoration = 'underline';
                e.currentTarget.style.textDecorationColor = '#f56565';
              } else {
                e.currentTarget.style.color = '#1677ff';
                e.currentTarget.style.textDecoration = 'underline';
              }
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.color = record.status === 'unread' ? '#f56565' : '#1677ff';
              e.currentTarget.style.textDecoration = 'none';
            }}
          >
            <span>{record.status === 'unread' ? t('notificationManagement.readLabel') : t('notificationManagement.detailLabel')}</span>
          </Button>
        );
      },
    },
  ];

  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 gap-3">
            {/* 搜索条件 + 搜索、重置紧跟其后 */}
            <div className="flex flex-wrap items-center gap-3">
              {/* 消息标题 */}
              <div className="flex items-center gap-2">
                <label className="text-sm text-gray-700 whitespace-nowrap">{t('notificationManagement.messageTitle')}：</label>
                <Input
                  placeholder={t('notificationManagement.placeholderMessageTitle')}
                  value={messageTitle}
                  onChange={(e) => setMessageTitle(e.target.value)}
                  onPressEnter={handleSearch}
                  allowClear
                  style={{ width: 200 }}
                />
              </div>

              {/* 消息状态 */}
              <div className="flex items-center gap-2">
                <label className="text-sm text-gray-700 whitespace-nowrap">{t('notificationManagement.messageStatus')}：</label>
                <Select
                  value={messageStatus}
                  onChange={setMessageStatus}
                  placeholder={t('common.pleaseSelect')}
                  style={{ width: 120 }}
                  allowClear
                >
                  <Select.Option value="true">{t('notificationManagement.read')}</Select.Option>
                  <Select.Option value="false">{t('notificationManagement.unread')}</Select.Option>
                </Select>
              </div>

              {/* 发送日期 + 搜索/重置同组 */}
              <div className="flex items-center gap-2">
                <label className="text-sm text-gray-700 whitespace-nowrap">{t('notificationManagement.time')}：</label>
                <DatePicker
                  placeholder={t('common.startDate')}
                  value={startDate}
                  onChange={setStartDate}
                  format="YYYY-MM-DD"
                  style={{ width: 140 }}
                />
                <span className="text-gray-400">-</span>
                <DatePicker
                  placeholder={t('common.endDate')}
                  value={endDate}
                  onChange={setEndDate}
                  format="YYYY-MM-DD"
                  style={{ width: 140 }}
                />
                <Space size="small">
                  <AntButton
                    type="primary"
                    icon={<Search className="w-4 h-4" />}
                    onClick={handleSearch}
                    disabled={loading}
                  >
                    {t('common.search')}
                  </AntButton>
                  <AntButton
                    icon={<RotateCcw className="w-4 h-4" />}
                    onClick={handleReset}
                  >
                    {t('common.reset')}
                  </AntButton>
                </Space>
              </div>
            </div>

            {/* 其他操作按钮保持在最右侧（全部已读） */}
            <Space size="small" className="ml-auto">
              <AntButton
                icon={<BookOpen className="w-4 h-4" />}
                onClick={handleMarkAllAsRead}
                disabled={loading}
              >
                {t('notificationManagement.markAllRead')}
              </AntButton>
            </Space>
          </div>
        </div>

        {/* 表格容器 */}
        <div className="overflow-hidden min-w-0">
          <AntdTable
            loading={loading}
            columns={columns}
            dataSource={filteredMessages}
            rowKey={(record) => record.id}
            pagination={false}
            scroll={{ x: 'max-content' }}
            locale={{
              emptyText: t('common.noData'),
            }}
          />
        </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('common.total')} <span className="text-blue-600 font-medium">{total}</span> {t('common.records')}
            </div>
            <div className="flex gap-2">
              <AntButton
                onClick={() => {
                  const newPage = Math.max(1, currentPage - 1);
                  setCurrentPage(newPage);
                }}
                disabled={currentPage === 1 || loading}
              >
                {t('common.prevPage')}
              </AntButton>
              <span className="px-4 py-2 text-sm text-gray-600 flex items-center">
                {currentPage} / {totalPages || 1}
              </span>
              <AntButton
                onClick={() => {
                  const newPage = Math.min(totalPages, currentPage + 1);
                  setCurrentPage(newPage);
                }}
                disabled={currentPage >= totalPages || loading || totalPages === 0}
              >
                {t('common.nextPage')}
              </AntButton>
            </div>
          </div>
        </div>
      )}

      {/* 发送消息弹窗 */}
      <Modal
        title={t('notificationManagement.sendInbox')}
        open={sendModalVisible}
        onOk={handleSendMessage}
        onCancel={() => {
          setSendModalVisible(false);
          form.resetFields();
        }}
        confirmLoading={sendLoading}
        okText={t('notificationManagement.send')}
        cancelText={t('common.cancel')}
        width={700}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            type: '通知消息',
            targetType: 'all',
          }}
        >
          <Form.Item
            label={t('notificationManagement.messageTitle')}
            name="title"
            rules={[{ required: true, message: t('notificationManagement.messageTitleRequired') }]}
          >
            <Input placeholder={t('notificationManagement.placeholderMessageTitle')} />
          </Form.Item>

          <Form.Item
            label={t('notificationManagement.messageType')}
            name="type"
          >
            <Select placeholder={t('common.pleaseSelect')}>
              <Select.Option value="通知消息">{t('notificationManagement.notifyMessage')}</Select.Option>
              <Select.Option value="告警通知">{t('notificationManagement.alertNotify')}</Select.Option>
              <Select.Option value="培训通知">{t('notificationManagement.trainNotify')}</Select.Option>
              <Select.Option value="审批通知">{t('notificationManagement.approvalNotify')}</Select.Option>
              <Select.Option value="安全提醒">{t('notificationManagement.securityRemind')}</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            label={t('notificationManagement.targetType')}
            name="targetType"
            rules={[{ required: true, message: t('notificationManagement.targetTypeRequired') }]}
          >
            <Select placeholder={t('notificationManagement.targetTypeRequired')}>
              <Select.Option value="all">{t('notificationManagement.allUsers')}</Select.Option>
              <Select.Option value="user">{t('notificationManagement.byUser')}</Select.Option>
              <Select.Option value="dept">{t('notificationManagement.byDept')}</Select.Option>
              <Select.Option value="role">{t('notificationManagement.byRole')}</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => prevValues.targetType !== currentValues.targetType}
          >
            {({ getFieldValue }) => {
              const targetType = getFieldValue('targetType');
              if (targetType === 'user') {
                return (
                  <Form.Item
                    label={t('notificationManagement.selectUser')}
                    name="userIds"
                    rules={[{ required: true, message: t('notificationManagement.userRequired') }]}
                  >
                    <Select
                      mode="multiple"
                      placeholder={t('notificationManagement.userRequired')}
                      showSearch
                      filterOption={(input, option) =>
                        (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                      }
                      options={userList.map(user => ({
                        label: `${user.nickname || user.username} (${user.username})`,
                        value: user.id,
                      }))}
                    />
                  </Form.Item>
                );
              }
              if (targetType === 'dept') {
                return (
                  <Form.Item
                    label={t('notificationManagement.selectDept')}
                    name="deptIds"
                    rules={[{ required: true, message: t('notificationManagement.deptRequired') }]}
                  >
                    <TreeSelect
                      multiple
                      placeholder={t('notificationManagement.deptRequired')}
                      treeData={deptList}
                      fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                    />
                  </Form.Item>
                );
              }
              if (targetType === 'role') {
                return (
                  <Form.Item
                    label={t('notificationManagement.selectRole')}
                    name="roleIds"
                    rules={[{ required: true, message: t('notificationManagement.roleRequired') }]}
                  >
                    <Select
                      mode="multiple"
                      placeholder={t('notificationManagement.roleRequired')}
                      options={roleList.map(role => ({
                        label: role.name,
                        value: role.id,
                      }))}
                    />
                  </Form.Item>
                );
              }
              return null;
            }}
          </Form.Item>

          <Form.Item
            label={t('notificationManagement.messageContent')}
            name="content"
            rules={[{ required: true, message: t('notificationManagement.messageContentRequired') }]}
          >
            <Input.TextArea
              rows={6}
              placeholder={t('notificationManagement.placeholderMessageContent')}
              showCount
              maxLength={1000}
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 消息详情弹窗 */}
      <Modal
        title={t('notificationManagement.inboxDetail')}
        open={detailModalVisible}
        onCancel={() => {
          setDetailModalVisible(false);
          setDetailMessage(null);
        }}
        footer={null}
        width={800}
        confirmLoading={detailLoading}
      >
        {detailLoading ? (
          <div className="py-8 text-center text-gray-500">{t('common.loading')}</div>
        ) : detailMessage ? (
          <Descriptions 
            column={1} 
            bordered
            labelStyle={{ whiteSpace: 'nowrap', width: '120px' }}
          >
            <Descriptions.Item label={t('notificationManagement.sender')}>
              {detailMessage.sender || t('notificationManagement.system')}
            </Descriptions.Item>
            <Descriptions.Item label={t('table.createTime')}>
              {detailMessage.createTime ? dateFormatter(detailMessage.createTime) : (detailMessage.sendTime ? dateFormatter(detailMessage.sendTime) : '-')}
            </Descriptions.Item>
            <Descriptions.Item label={t('notificationManagement.messageType')}>
              {(() => {
                // 根据 templateType 获取字典对象，包含颜色信息
                const dictObj = detailMessage.templateType 
                  ? getDictObj(DICT_TYPE.SYSTEM_NOTIFY_TEMPLATE_TYPE, detailMessage.templateType)
                  : null;
                
                // 根据字典的 colorType 设置不同的颜色
                let bgColor = 'bg-gray-100';
                let textColor = 'text-gray-700';
                let borderColor = 'border-gray-200';
                
                if (dictObj) {
                  switch (dictObj.colorType) {
                    case 'blue':
                      bgColor = 'bg-blue-100';
                      textColor = 'text-blue-700';
                      borderColor = 'border-blue-200';
                      break;
                    case 'green':
                      bgColor = 'bg-green-100';
                      textColor = 'text-green-700';
                      borderColor = 'border-green-200';
                      break;
                    case 'orange':
                      bgColor = 'bg-orange-100';
                      textColor = 'text-orange-700';
                      borderColor = 'border-orange-200';
                      break;
                    default:
                      bgColor = 'bg-gray-100';
                      textColor = 'text-gray-700';
                      borderColor = 'border-gray-200';
                  }
                }
                
                return (
                  <span className={`inline-flex px-3 py-1 rounded-lg text-xs ${bgColor} ${textColor} border ${borderColor}`}>
                    {detailMessage.type || t('notificationManagement.notifyMessage')}
                  </span>
                );
              })()}
            </Descriptions.Item>
            <Descriptions.Item label={t('notificationManagement.isRead')}>
              {detailMessage.status === 'read' ? (
                <span className="inline-flex px-3 py-1 rounded-lg text-xs bg-gray-100 text-gray-700 border border-gray-200">
                  {t('notificationManagement.read')}
                </span>
              ) : (
                <span className="inline-flex px-3 py-1 rounded-lg text-xs bg-red-100 text-red-700 border border-red-200">
                  {t('notificationManagement.unread')}
                </span>
              )}
            </Descriptions.Item>
            {detailMessage.readTime && (
              <Descriptions.Item label={t('notificationManagement.readTime')}>
                {dateFormatter(detailMessage.readTime)}
              </Descriptions.Item>
            )}
            <Descriptions.Item label={t('notificationManagement.content')}>
              <div className="text-sm text-gray-900 bg-gray-50 p-3 rounded-lg border border-gray-200 min-h-[80px] whitespace-pre-wrap">
                {detailMessage.content || '-'}
              </div>
            </Descriptions.Item>
          </Descriptions>
        ) : null}
      </Modal>
    </div>
  );
}

