<template>
  <div class="my-message-detail" v-loading="loading">
    <div class="header">
      <el-button @click="handleBack" text>
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
    </div>

    <div v-if="message" class="detail-container">
      <!-- 消息卡片 -->
      <el-card class="message-card" shadow="never">
        <!-- 标题区域 -->
        <div class="message-header">
          <div class="title-area">
            <h1 class="message-title">{{ message.title }}</h1>
            <div class="title-badges">
              <el-tag :type="getMessageTypeTag(message.messageType)">
                {{ getMessageTypeText(message.messageType) }}
              </el-tag>
              <MessagePriorityBadge :priority="message.priority || ''" />
            </div>
          </div>

          <div class="message-meta">
            <div class="meta-item">
              <el-icon><User /></el-icon>
              <span>发送人：{{ message.senderName }}</span>
            </div>
            <div class="meta-item">
              <el-icon><OfficeBuilding /></el-icon>
              <span>部门：{{ message.senderDeptName }}</span>
            </div>
            <div class="meta-item">
              <el-icon><Clock /></el-icon>
              <span>发送时间：{{ formatDateTime(message.actualSendTime) }}</span>
            </div>
            <div v-if="message.isRead" class="meta-item read-status">
              <el-icon><Check /></el-icon>
              <span>已读于：{{ formatDateTime(message.readTime) }}</span>
            </div>
            <div v-else class="meta-item unread-status">
              <el-icon><View /></el-icon>
              <span>未读</span>
            </div>
          </div>
        </div>

        <!-- 消息内容 -->
        <el-divider />
        <div class="message-content">
          <div class="content-body">
            {{ message.content }}
          </div>
        </div>

        <!-- 发送方式 -->
        <el-divider />
        <div class="send-info">
          <div class="info-label">
            <el-icon><Message /></el-icon>
            <span>发送方式：</span>
          </div>
          <div class="send-methods">
            <el-tag
              v-if="message.sendMethod === 'system' || !message.sendMethod"
              type="primary"
              size="small"
            >
              系统消息
            </el-tag>
            <el-tag
              v-if="message.sendMethod === 'email'"
              type="success"
              size="small"
            >
              邮件通知
            </el-tag>
            <el-tag
              v-if="message.sendMethod === 'sms'"
              type="warning"
              size="small"
            >
              短信通知
            </el-tag>
          </div>
        </div>

        <!-- 发送状态 -->
        <div class="send-status">
          <div class="info-label">
            <el-icon><CircleCheck /></el-icon>
            <span>发送状态：</span>
          </div>
          <el-tag
            :type="getSendStatusType(message.sendStatus)"
            size="small"
          >
            {{ getSendStatusText(message.sendStatus) }}
          </el-tag>
          <span v-if="message.failReason" class="fail-reason">
            （{{ message.failReason }}）
          </span>
        </div>

        <!-- 操作按钮 -->
        <el-divider />
        <div class="message-actions">
          <el-button
            v-if="!message.isRead"
            type="primary"
            @click="handleMarkAsRead"
            :loading="marking"
          >
            <el-icon><Check /></el-icon>
            标记为已读
          </el-button>
        </div>
      </el-card>

      <!-- 相关消息推荐（可选功能） -->
      <el-card v-if="relatedMessages.length > 0" class="related-messages" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="header-title">相关消息</span>
          </div>
        </template>
        <div class="related-list">
          <div
            v-for="relMsg in relatedMessages"
            :key="relMsg.messageID"
            class="related-item"
            @click="handleViewRelated(relMsg.messageID)"
          >
            <div class="related-title">
              <span v-if="!relMsg.isRead" class="unread-dot"></span>
              {{ relMsg.title }}
            </div>
            <div class="related-meta">
              <span>{{ formatDateTime(relMsg.actualSendTime) }}</span>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import {
  ArrowLeft,
  User,
  OfficeBuilding,
  Clock,
  Check,
  View,
  Message,
  CircleCheck
} from '@element-plus/icons-vue';
import { messageApi } from '@/apis/message';
import type { MessageUserVO } from '@/types';
import { MessagePriorityBadge } from '@/components/message';

defineOptions({
  name: 'MyMessageDetailView'
});

const router = useRouter();
const route = useRoute();
const messageID = route.params.messageID as string;

const loading = ref(false);
const marking = ref(false);

const message = ref<MessageUserVO | null>(null);
const relatedMessages = ref<MessageUserVO[]>([]);

/** 获取消息类型标签 */
function getMessageTypeTag(type?: string): string {
  const map: Record<string, string> = {
    notice: 'info',
    announcement: 'warning',
    warning: 'danger',
    system: 'success'
  };
  return map[type || ''] || '';
}

/** 获取消息类型文本 */
function getMessageTypeText(type?: string): string {
  const map: Record<string, string> = {
    notice: '通知',
    announcement: '公告',
    warning: '预警',
    system: '系统消息'
  };
  return map[type || ''] || type || '';
}

/** 获取发送状态类型 */
function getSendStatusType(status?: string): string {
  const map: Record<string, string> = {
    pending: 'info',
    success: 'success',
    failed: 'danger'
  };
  return map[status || ''] || '';
}

/** 获取发送状态文本 */
function getSendStatusText(status?: string): string {
  const map: Record<string, string> = {
    pending: '待发送',
    success: '发送成功',
    failed: '发送失败'
  };
  return map[status || ''] || status || '';
}

/** 格式化日期时间 */
function formatDateTime(dateStr?: string): string {
  if (!dateStr) return '-';
  const date = new Date(dateStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
}

/** 加载消息详情 */
async function loadMessageDetail() {
  loading.value = true;
  try {
    const result = await messageApi.getMyMessageDetail(messageID);
    if (result.success) {
      message.value = result.data || null;

      // 如果是未读消息，自动标记为已读
      if (message.value && !message.value.isRead) {
        await autoMarkAsRead();
      }
    } else {
      ElMessage.error(result.message || '加载失败');
    }
  } catch (error) {
    console.error('加载消息详情失败:', error);
    ElMessage.error('加载失败');
  } finally {
    loading.value = false;
  }
}

/** 自动标记为已读 */
async function autoMarkAsRead() {
  try {
    await messageApi.markAsRead(messageID);
    // 不显示成功消息，静默标记
  } catch (error) {
    console.error('自动标记已读失败:', error);
  }
}

/** 手动标记为已读 */
async function handleMarkAsRead() {
  marking.value = true;
  try {
    const result = await messageApi.markAsRead(messageID);
    if (result.success) {
      ElMessage.success('已标记为已读');
      await loadMessageDetail();
    } else {
      ElMessage.error(result.message || '操作失败');
    }
  } catch (error) {
    console.error('标记已读失败:', error);
    ElMessage.error('操作失败');
  } finally {
    marking.value = false;
  }
}

/** 查看相关消息 */
function handleViewRelated(relatedMessageID?: string) {
  if (!relatedMessageID) return;
  router.push(`/user/message/detail/${relatedMessageID}`);
  // 重新加载当前页面
  loadMessageDetail();
}

/** 返回 */
function handleBack() {
  router.back()
}

onMounted(() => {
  loadMessageDetail();
});
</script>

<style lang="scss" scoped>
.my-message-detail {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;

  .header {
    max-width: 900px;
    margin: 0 auto 20px;
  }

  .detail-container {
    max-width: 900px;
    margin: 0 auto;

    .message-card {
      margin-bottom: 20px;

      .message-header {
        .title-area {
          margin-bottom: 20px;

          .message-title {
            margin: 0 0 12px 0;
            font-size: 28px;
            font-weight: 600;
            color: #333;
            line-height: 1.4;
          }

          .title-badges {
            display: flex;
            gap: 8px;
          }
        }

        .message-meta {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
          gap: 12px;
          padding: 16px;
          background-color: #f9f9f9;
          border-radius: 8px;

          .meta-item {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 14px;
            color: #666;

            &.read-status {
              color: #67c23a;
            }

            &.unread-status {
              color: #409eff;
            }

            .el-icon {
              font-size: 16px;
            }
          }
        }
      }

      .message-content {
        .content-body {
          font-size: 16px;
          line-height: 1.8;
          color: #333;
          white-space: pre-wrap;
          word-wrap: break-word;
          min-height: 200px;
          padding: 20px 0;
        }
      }

      .send-info,
      .send-status {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 12px;

        .info-label {
          display: flex;
          align-items: center;
          gap: 6px;
          font-size: 14px;
          color: #666;
          font-weight: 500;

          .el-icon {
            font-size: 16px;
          }
        }

        .send-methods {
          display: flex;
          gap: 8px;
        }

        .fail-reason {
          font-size: 12px;
          color: #f56c6c;
        }
      }

      .message-actions {
        display: flex;
        gap: 12px;
        padding-top: 8px;
      }
    }

    .related-messages {
      .card-header {
        .header-title {
          font-size: 16px;
          font-weight: 600;
          color: #333;
        }
      }

      .related-list {
        .related-item {
          padding: 12px;
          border-bottom: 1px solid #f0f0f0;
          cursor: pointer;
          transition: background-color 0.2s;

          &:last-child {
            border-bottom: none;
          }

          &:hover {
            background-color: #f9f9f9;
          }

          .related-title {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
            color: #333;
            margin-bottom: 6px;

            .unread-dot {
              width: 6px;
              height: 6px;
              background-color: #f56c6c;
              border-radius: 50%;
              flex-shrink: 0;
            }
          }

          .related-meta {
            font-size: 12px;
            color: #999;
          }
        }
      }
    }
  }
}
</style>
