<template>
  <div class="card">
    <div class="card-header" style="display: flex; justify-content: space-between; align-items: center;">
      <h2 style="display: flex; align-items: center;">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="title-icon">
          <path d="M15 5H9C7.89543 5 7 5.89543 7 7V17C7 18.1046 7.89543 19 9 19H15C16.1046 19 17 18.1046 17 17V7C17 5.89543 16.1046 5 15 5Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          <path d="M9 13H17" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          <path d="M9 9H17" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
        串口数据显示
      </h2>
      <button class="btn-clear" @click="clearData">清空</button>
    </div>
    
    <div class="data-display-container">
      <div class="data-display" ref="serialDataContainer" v-html="formattedSerialData"></div>
    </div>
    
    <div class="stats">
      <p>接收消息数: {{ dataStore.serialData.length }}</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 serialDataContainer = ref(null)

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

// 格式化串口数据为HTML显示
const formattedSerialData = computed(() => {
  if (!dataStore.serialData || dataStore.serialData.length === 0) {
    return '<div class="no-data">暂无数据</div>'
  }
  
  return dataStore.serialData.map(item => {
    // 适配数据格式，支持字符串或对象格式
    if (typeof item === 'string') {
      return `
        <div class="message-item">
          <span class="timestamp">${formatTime(new Date())}</span>
          <span class="direction">接收</span>
          <div class="message-content">${escapeHtml(item)}</div>
        </div>
      `
    } else {
      const dir = item.direction === 'in' ? '接收' : item.direction === 'out' ? '发送' : ''
      const text = item.data || item.message || JSON.stringify(item)
      const formatted = text.length > 20 ? text.replace(/(.{2})/g, '$1 ').trim().toUpperCase() : text
      const dirHtml = dir ? ` : <span class="direction">${dir}</span>` : ''
      return `<div class="message-item"><span class="timestamp">${formatTime(item.timestamp || new Date())}</span>${dirHtml} : <span class="msg-data">${escapeHtml(formatted)}</span></div>`
    }
  }).join('')
})

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

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

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

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

h2 {
  display: flex;
  align-items: center;
}

.data-display-container {
  height: 280px;
  display: flex;
  flex-direction: column;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #f5f5f5;
  margin-bottom: 10px;
}

.data-display {
  flex: 1;
  min-height: 0;
  overflow-y: scroll;
  overflow-x: hidden;
  padding: 10px;
  font-family: 'Courier New', Courier, monospace;
  font-size: 14px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-break: break-all;
}

.no-data {
  color: #888;
  font-style: italic;
  text-align: center;
  padding: 20px;
}

.message-item {
  margin-bottom: 10px;
  padding: 8px;
  background-color: #fff;
  border-radius: 4px;
  border-left: 3px solid #4CAF50;
}

.timestamp {
  color: #666;
  font-size: 12px;
  margin-right: 10px;
}

.direction {
  color: #4CAF50;
  font-weight: bold;
  margin-right: 10px;
}

.message-content {
  margin-top: 5px;
  color: #333;
}

.msg-data {
  margin-left: 8px;
  color: #1a1a1a;
  font-weight: 500;
  word-break: break-all;
}

.stats {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
}

.btn-clear {
  background-color: #f44336;
  color: white;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

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

/* 应用CSS变量和主题样式 */
.data-display-container {
  background-color: var(--bg-secondary);
  border: 1px solid var(--border-color);
}

.data-display {
  font-family: var(--font-mono);
  color: var(--text-primary);
}

.no-data {
  color: var(--text-placeholder);
}

.message-item {
  background-color: var(--bg-primary);
  border-left-color: var(--success-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);
}

.direction {
  color: var(--success-color);
}

.message-content {
  color: var(--text-primary);
}

.stats {
  color: var(--text-secondary);
}

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

/* 滚动条样式 */
.data-display::-webkit-scrollbar {
  width: 8px;
}

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

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

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

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