import React, { useState, useEffect } from 'react';
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 [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) 
      : '通知消息';
    
    return {
      id: data.id,
      title: data.title || '',
      type: typeLabel,
      sender: data.templateNickname || '系统',
      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
    };
  };

  // 获取消息列表
  const fetchMessages = async (searchParams?: {
    title?: string;
    status?: string;
    startDate?: Dayjs | null;
    endDate?: Dayjs | null;
    page?: number;
  }) => {
    setLoading(true);
    try {
      // 使用传入的参数或当前状态
      const title = searchParams?.title !== undefined ? searchParams.title : messageTitle;
      const status = searchParams?.status !== undefined ? searchParams.status : messageStatus;
      const start = searchParams?.startDate !== undefined ? searchParams.startDate : startDate;
      const end = searchParams?.endDate !== undefined ? searchParams.endDate : endDate;
      const page = searchParams?.page !== undefined ? 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 || '获取消息列表失败');
      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 = () => {
    // 标记为搜索触发，避免 useEffect 重复调用
    isSearchingRef.current = true;
    // 先清空搜索条件和表格数据
    setMessageTitle('');
    setMessageStatus(undefined);
    setStartDate(null);
    setEndDate(null);
    setSelectedIds([]);
    setCurrentPage(1);
    // 先清空表格数据，确保界面立即更新
    setMessages([]);
    setTotal(0);
    // 重置后重新获取数据（使用空条件，确保传入所有参数）
    fetchMessages({
      title: '',
      status: undefined,
      startDate: null,
      endDate: null,
      page: 1
    });
  };

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

  // 全部已读
  const handleMarkAllAsRead = async () => {
    setLoading(true);
    try {
      await in_site.markAllAsRead();
      setSelectedIds([]);
      // 重新获取数据
      await fetchMessages();
      toast.success('全部标记已读成功');
      // 触发事件，通知消息通知组件更新未读数量
      window.dispatchEvent(new CustomEvent('messageRead'));
    } catch (error: any) {
      console.error('全部标记已读失败:', error);
      toast.error(error?.response?.data?.message || '全部标记已读失败');
    } 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('标记已读失败');
          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 || '获取消息详情失败');
    } 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('发送成功');
      setSendModalVisible(false);
      form.resetFields();
      // 刷新消息列表
      await fetchMessages();
    } catch (error: any) {
      if (error?.errorFields) {
        // 表单验证错误
        return;
      }
      console.error('发送消息失败:', error);
      toast.error(error?.response?.data?.message || '发送消息失败');
    } finally {
      setSendLoading(false);
    }
  };


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

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

  // 定义表格列
  const columns: ColumnsType<MessageItem> = [
    {
      title: '消息标题',
      dataIndex: 'title',
      key: 'title',
      width: '15%',
      render: (text: string) => <span className="text-sm text-gray-900">{text}</span>,
    },
    {
      title: '消息类型',
      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: '发送人',
      dataIndex: 'sender',
      key: 'sender',
      width: '10%',
      render: (text: string) => <span className="text-sm text-gray-900">{text}</span>,
    },
    {
      title: '创建时间',
      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: '消息内容',
      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;
        
        return (
          <Tooltip placement="topLeft" title={contentText}>
            <span className="text-sm text-gray-900">{displayText}</span>
          </Tooltip>
        );
      },
    },
    {
      title: '消息状态',
      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">
            已读
          </span>
        ) : (
          <span className="inline-flex px-3 py-1 rounded-lg text-xs bg-red-100 text-red-700">
            未读
          </span>
        );
      },
    },
    {
      title: '阅读时间',
      dataIndex: 'readTime',
      key: 'readTime',
      width: '12%',
      render: (readTime: string | number | undefined) => {
        return <span className="text-sm text-gray-900">{readTime ? dateFormatter(readTime) : '-'}</span>;
      },
    },
    {
      title: '操作',
      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' ? '阅读' : '详情'}</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 justify-between 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">消息标题：</label>
                <Input
                  placeholder="请输入消息标题"
                  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">消息状态：</label>
                <Select
                  value={messageStatus}
                  onChange={setMessageStatus}
                  placeholder="请选择"
                  style={{ width: 120 }}
                  allowClear
                >
                  <Select.Option value="true">已读</Select.Option>
                  <Select.Option value="false">未读</Select.Option>
                </Select>
              </div>

              {/* 发送日期 */}
              <div className="flex items-center gap-2">
                <label className="text-sm text-gray-700 whitespace-nowrap">时间：</label>
                <DatePicker
                  placeholder="开始日期"
                  value={startDate}
                  onChange={setStartDate}
                  format="YYYY-MM-DD"
                  style={{ width: 140 }}
                />
                <span className="text-gray-400">-</span>
                <DatePicker
                  placeholder="结束日期"
                  value={endDate}
                  onChange={setEndDate}
                  format="YYYY-MM-DD"
                  style={{ width: 140 }}
                />
              </div>
            </div>

            <Space size="small">
              <AntButton
                type="primary"
                icon={<Search className="w-4 h-4" />}
                onClick={handleSearch}
                disabled={loading}
              >
                搜索
              </AntButton>
              <AntButton
                icon={<RotateCcw className="w-4 h-4" />}
                onClick={handleReset}
              >
                重置
              </AntButton>
              <AntButton
                icon={<BookOpen className="w-4 h-4" />}
                onClick={handleMarkAllAsRead}
                disabled={loading}
              >
                全部已读
              </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: '暂无数据',
            }}
          />
        </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">
              共 <span className="text-blue-600 font-medium">{total}</span> 条记录
            </div>
            <div className="flex gap-2">
              <AntButton
                onClick={() => {
                  const newPage = Math.max(1, currentPage - 1);
                  setCurrentPage(newPage);
                }}
                disabled={currentPage === 1 || loading}
              >
                上一页
              </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}
              >
                下一页
              </AntButton>
            </div>
          </div>
        </div>
      )}

      {/* 发送消息弹窗 */}
      <Modal
        title="发送站内信"
        open={sendModalVisible}
        onOk={handleSendMessage}
        onCancel={() => {
          setSendModalVisible(false);
          form.resetFields();
        }}
        confirmLoading={sendLoading}
        okText="发送"
        cancelText="取消"
        width={700}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            type: '通知消息',
            targetType: 'all',
          }}
        >
          <Form.Item
            label="消息标题"
            name="title"
            rules={[{ required: true, message: '请输入消息标题' }]}
          >
            <Input placeholder="请输入消息标题" />
          </Form.Item>

          <Form.Item
            label="消息类型"
            name="type"
          >
            <Select placeholder="请选择消息类型">
              <Select.Option value="通知消息">通知消息</Select.Option>
              <Select.Option value="告警通知">告警通知</Select.Option>
              <Select.Option value="培训通知">培训通知</Select.Option>
              <Select.Option value="审批通知">审批通知</Select.Option>
              <Select.Option value="安全提醒">安全提醒</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            label="接收对象"
            name="targetType"
            rules={[{ required: true, message: '请选择接收对象' }]}
          >
            <Select placeholder="请选择接收对象">
              <Select.Option value="all">全体用户</Select.Option>
              <Select.Option value="user">指定用户</Select.Option>
              <Select.Option value="dept">按部门</Select.Option>
              <Select.Option value="role">按角色</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="选择用户"
                    name="userIds"
                    rules={[{ required: true, message: '请选择用户' }]}
                  >
                    <Select
                      mode="multiple"
                      placeholder="请选择用户"
                      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="选择部门"
                    name="deptIds"
                    rules={[{ required: true, message: '请选择部门' }]}
                  >
                    <TreeSelect
                      multiple
                      placeholder="请选择部门"
                      treeData={deptList}
                      fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                    />
                  </Form.Item>
                );
              }
              if (targetType === 'role') {
                return (
                  <Form.Item
                    label="选择角色"
                    name="roleIds"
                    rules={[{ required: true, message: '请选择角色' }]}
                  >
                    <Select
                      mode="multiple"
                      placeholder="请选择角色"
                      options={roleList.map(role => ({
                        label: role.name,
                        value: role.id,
                      }))}
                    />
                  </Form.Item>
                );
              }
              return null;
            }}
          </Form.Item>

          <Form.Item
            label="消息内容"
            name="content"
            rules={[{ required: true, message: '请输入消息内容' }]}
          >
            <Input.TextArea
              rows={6}
              placeholder="请输入消息内容"
              showCount
              maxLength={1000}
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 消息详情弹窗 */}
      <Modal
        title="消息详情"
        open={detailModalVisible}
        onCancel={() => {
          setDetailModalVisible(false);
          setDetailMessage(null);
        }}
        footer={null}
        width={800}
        confirmLoading={detailLoading}
      >
        {detailLoading ? (
          <div className="py-8 text-center text-gray-500">加载中...</div>
        ) : detailMessage ? (
          <Descriptions 
            column={1} 
            bordered
            labelStyle={{ whiteSpace: 'nowrap', width: '120px' }}
          >
            <Descriptions.Item label="发送人">
              {detailMessage.sender || '系统'}
            </Descriptions.Item>
            <Descriptions.Item label="创建时间">
              {detailMessage.createTime ? dateFormatter(detailMessage.createTime) : (detailMessage.sendTime ? dateFormatter(detailMessage.sendTime) : '-')}
            </Descriptions.Item>
            <Descriptions.Item label="消息类型">
              {(() => {
                // 根据 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 || '通知消息'}
                  </span>
                );
              })()}
            </Descriptions.Item>
            <Descriptions.Item label="是否已读">
              {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">
                  已读
                </span>
              ) : (
                <span className="inline-flex px-3 py-1 rounded-lg text-xs bg-red-100 text-red-700 border border-red-200">
                  未读
                </span>
              )}
            </Descriptions.Item>
            {detailMessage.readTime && (
              <Descriptions.Item label="阅读时间">
                {dateFormatter(detailMessage.readTime)}
              </Descriptions.Item>
            )}
            <Descriptions.Item label="内容">
              <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>
  );
}

