<template>
  <div class="command-history">
    <div class="command-history__header">
      <span>命令历史</span>
      <a-button type="link" size="small" @click="terminalStore.clearHistory()">
        清空
      </a-button>
    </div>
    <div class="command-history__list">
      <div
        v-for="(record, index) in terminalStore.recentCommands"
        :key="index"
        class="command-history__item"
        @click="$emit('select', record.command)"
      >
        <div class="command-history__item-header">
          <span
            class="command-history__exit-code"
            :class="record.exit_code === 0 ? 'success' : 'error'"
          >
            {{ record.exit_code === 0 ? '✓' : '✗' }}
          </span>
          <span class="command-history__command">{{ record.command }}</span>
        </div>
        <div class="command-history__item-meta">
          <span>{{ formatTime(record.timestamp) }}</span>
          <span v-if="record.duration_ms" class="command-history__duration">
            {{ record.duration_ms }}ms
          </span>
        </div>
      </div>
      <div v-if="terminalStore.recentCommands.length === 0" class="command-history__empty">
        暂无命令历史
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useTerminalStore } from '@/stores/terminal'

const terminalStore = useTerminalStore()

defineEmits<{
  select: [command: string]
}>()

function formatTime(timestamp: number): string {
  try {
    const d = new Date(timestamp * 1000)
    return d.toLocaleTimeString('zh-CN')
  } catch {
    return ''
  }
}
</script>

<style scoped>
.command-history {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #fafafa;
  border-left: 1px solid #f0f0f0;
}

.command-history__header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  font-weight: 600;
  font-size: 14px;
  border-bottom: 1px solid #f0f0f0;
}

.command-history__list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.command-history__item {
  padding: 8px 12px;
  border-radius: 4px;
  cursor: pointer;
  margin-bottom: 4px;
  transition: background 0.2s;
}

.command-history__item:hover {
  background: #e6f4ff;
}

.command-history__item-header {
  display: flex;
  align-items: center;
  gap: 6px;
}

.command-history__exit-code {
  font-size: 12px;
  font-weight: 600;
}

.command-history__exit-code.success {
  color: #52c41a;
}

.command-history__exit-code.error {
  color: #f5222d;
}

.command-history__command {
  font-family: 'Menlo', 'Monaco', monospace;
  font-size: 12px;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.command-history__item-meta {
  display: flex;
  gap: 8px;
  margin-top: 2px;
  font-size: 11px;
  color: #999;
}

.command-history__duration {
  color: #1677ff;
}

.command-history__empty {
  text-align: center;
  padding: 24px;
  color: #999;
  font-size: 13px;
}
</style>
