<template>
  <div class="card">
    <div class="card-header">
      <h2 style="display: flex; align-items: center; margin: 0; color: var(--text-primary);">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="title-icon" style="color: var(--primary-color); margin-right: var(--space-sm); vertical-align: middle;">
          <path d="M21 16V8C21 6.89543 20.1046 6 19 6H5C3.89543 6 3 6.89543 3 8V16C3 17.1046 3.89543 18 5 18H19C20.1046 18 21 17.1046 21 16Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          <path d="M12 12L9 15L12 18L15 15L12 12Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
        <span style="font-weight: bold; font-size: 16px;">MQTT数据显示</span>
      </h2>
      <button class="btn-clear" @click="clearData" style="background-color: var(--error-color); color: white; border: none; padding: 5px 10px; border-radius: var(--radius); cursor: pointer; font-size: 14px; transition: background-color var(--transition-fast);">清空</button>
    </div>
    
    <div class="data-display-container">
      <div class="data-display" ref="mqttDataContainer" v-html="formattedMQTTData"></div>
    </div>
    
    <div class="stats">
      <p>接收消息数: {{ dataStore.mqttData?.length || 0 }}</p>
      <p v-if="lastMessageTime">最后接收时间: {{ formatTime(lastMessageTime) }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick } from 'vue'
import { useDataStore } from '../stores/dataStore'

// 使用数据存储
const dataStore = useDataStore()

// DOM引用
const mqttDataContainer = ref(null)

// 最后接收消息时间
const lastMessageTime = ref(null)

// 格式化MQTT数据为HTML显示
const formattedMQTTData = computed(() => {
  if (!dataStore.mqttData || dataStore.mqttData.length === 0) {
    return '<div class="no-data">暂无数据</div>'
  }
  
  return dataStore.mqttData.map(item => {
    // 适配数据格式，支持字符串或对象格式
    if (typeof item === 'string') {
      return `
        <div class="message-item">
          <span class="timestamp">${formatTime(new Date())}</span>
          <span class="topic">unknown</span>
          <div class="message-content">${formatMessageContent(item)}</div>
        </div>
      `
    } else {
      return `
        <div class="message-item">
          <span class="timestamp">${formatTime(item.timestamp || new Date())}</span>
          <span class="topic">${item.topic || 'unknown'}</span>
          <div class="message-content">${formatMessageContent(item.message || item)}</div>
        </div>
      `
    }
  }).join('')
})

// 监听数据变化，自动滚动到底部
watch(() => dataStore.mqttData?.length || 0, () => {
  if (dataStore.mqttData && dataStore.mqttData.length > 0) {
    const lastItem = dataStore.mqttData[0] // 注意：unshift添加在数组开头
    lastMessageTime.value = typeof lastItem === 'object' && lastItem.timestamp ? lastItem.timestamp : new Date()
  }
  
  nextTick(() => {
    if (mqttDataContainer.value) {
      mqttDataContainer.value.scrollTop = mqttDataContainer.value.scrollHeight
    }
  })
})

// 清空数据
const clearData = () => {
  dataStore.clearData() // 调用现有的clearData方法
  lastMessageTime.value = null
}

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', {
    hour12: false,
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    fractionalSecondDigits: 3
  })
}

// 格式化消息内容（尝试JSON格式化）
const formatMessageContent = (message) => {
  // 首先进行HTML转义
  let escaped = escapeHtml(message)
  
  // 尝试解析为JSON并格式化显示
  try {
    const parsed = JSON.parse(message)
    const formattedJson = JSON.stringify(parsed, null, 2)
    return `<pre class="json-formatted">${escapeHtml(formattedJson)}</pre>`
  } catch (e) {
    // 非JSON格式则直接返回
    return escaped.replace(/\n/g, '<br>')
  }
}

// HTML转义
const escapeHtml = (unsafe) => {
  return unsafe
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;")
    .replace(/\s/g, ' ')
}
</script>

<style scoped>
/* 应用CSS变量和主题样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--space-md);
}

.title-icon {
  color: var(--primary-color);
  margin-right: var(--space-sm);
  vertical-align: middle;
}

h2 {
  display: flex;
  align-items: center;
  margin: 0;
  color: var(--text-primary);
}

.data-display-container {
  height: 300px;
  display: flex;
  flex-direction: column;
  border: 1px solid var(--border-color);
  border-radius: var(--radius);
  background-color: var(--bg-secondary);
  margin-bottom: var(--space-sm);
}

.data-display {
  flex: 1;
  min-height: 0;
  overflow-y: scroll;
  overflow-x: hidden;
  padding: var(--space-sm);
  font-family: var(--font-mono);
  font-size: 14px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-break: break-all;
  color: var(--text-primary);
}

.no-data {
  color: var(--text-placeholder);
  font-style: italic;
  text-align: center;
  padding: var(--space-md);
}

.message-item {
  margin-bottom: var(--space-sm);
  padding: var(--space-sm);
  background-color: var(--bg-primary);
  border-radius: var(--radius);
  border-left: 3px solid var(--primary-color);
  box-shadow: var(--shadow-xs);
  transition: box-shadow var(--transition-fast);
}

.message-item:hover {
  box-shadow: var(--shadow-sm);
}

.timestamp {
  color: var(--text-secondary);
  font-size: 12px;
  margin-right: var(--space-sm);
}

.topic {
  color: var(--primary-color);
  font-weight: bold;
  margin-right: var(--space-sm);
  background-color: var(--primary-light);
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 12px;
}

.message-content {
  margin-top: 8px;
  color: var(--text-primary);
}

.json-formatted {
  background-color: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: var(--radius);
  padding: var(--space-sm);
  margin: 0;
  overflow-x: auto;
  color: var(--text-primary);
  font-family: var(--font-mono);
  font-size: 13px;
}

.stats {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: var(--text-secondary);
}

.btn-clear {
  background-color: var(--error-color);
  color: white;
  border: none;
  padding: 5px 10px;
  border-radius: var(--radius);
  cursor: pointer;
  font-size: 14px;
  transition: background-color var(--transition-fast);
}

.btn-clear:hover {
  background-color: var(--error-hover);
}

/* 自定义滚动条 */
.data-display::-webkit-scrollbar {
  width: 6px;
}

.data-display::-webkit-scrollbar-track {
  background: var(--bg-secondary);
}

.data-display::-webkit-scrollbar-thumb {
  background: var(--border-color);
  border-radius: 3px;
}

.data-display::-webkit-scrollbar-thumb:hover {
  background: var(--text-placeholder);
}

/* JSON格式化样式 */
.json-formatted .json-key {
  color: var(--accent-color);
}

.json-formatted .json-string {
  color: var(--success-color);
}

.json-formatted .json-number {
  color: var(--primary-color);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .data-display-container {
    height: 250px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .stats {
    flex-direction: column;
    gap: 5px;
  }
}
</style>