<template>
  <div class="status-item status-button" @click="show">
    <i-lucide-radio class="status-icon" />
    <span class="status-label">SSE 连接状态:</span>
    <span class="status-value" :class="sseStatusClass">{{ sseStatus }}</span>
  </div>

  <a-modal v-model:open="dialogVisible" :title="modalTitle" :footer="null" width="600px">
    <a-row :gutter="[0, 12]">
      <template v-for="(item, index) in modalItems" :key="index">
        <a-col :span="8" class="modal-label">{{ item.label }}</a-col>
        <a-col :span="16" class="modal-value" 
          :class="item.label === '当前状态' ? sseStatusClass : null">
          {{ item.value }}
        </a-col>
      </template>
    </a-row>
    <div class="sse-controls">
      <a-button type="primary" @click="connect" v-if="!isConnected" 
        :loading="isConnecting" :disabled="isInCooldown">
        {{ isConnecting ? '连接中...' : (isInCooldown ? `冷却中 (${cooldownRemaining}s)` : '连接') }}
      </a-button>
      <a-button danger @click="sseDisconnect" v-else>
        断开连接
      </a-button>
      <a-button @click="handleClearSseLogs" class="clear-btn">
        <i-lucide-trash-2 />
        清空日志
      </a-button>
    </div>

    <div class="sse-logs" ref="logContainer">      
      <div v-for="(log, index) in logs" :key="index" class="log-item" :class="log.type">
        {{ log.message }}
      </div>
      
      <div v-if="logs.length === 0" class="empty-logs">
        <i-lucide-radio class="empty-icon" />
        <span>暂无SSE连接日志</span>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, nextTick, watch } from 'vue';
import { useDialog } from '@/utils/useDialog';
import { useSSE } from '@/utils/useSSE';

// Props
const props = defineProps({
  onL1Event: {
    type: Function,
    default: null
  },
  onL4Event: {
    type: Function,
    default: null
  },
  onMesEvent: {
    type: Function,
    default: null
  },
  onSseMessage: {
    type: Function,
    default: null
  }
});

// useDialog管理弹窗状态
const { visible: dialogVisible, show, hide } = useDialog();

// 冷却时间管理
const isInCooldown = ref(false);
const cooldownRemaining = ref(0);
let cooldownTimer: number | null = null;

// 内部日志管理
const logContainer = ref();

// 使用SSE工具函数
const {
  clientId,
  serverUrl,
  isConnected,
  isConnecting,
  sseStatus,
  sseStatusClass,
  logs,
  connect,
  disconnect,
} = useSSE({
  onMessage: (data) => {
    addSseLog(data);
    // 调用父组件传入的消息处理函数
    if (props.onSseMessage) {
      props.onSseMessage(data);
    }
  },
  onL1Event: (data) => {
    if (props.onL1Event) {
      props.onL1Event(data);
    }
  },
  onL4Event: (data) => {
    if (props.onL4Event) {
      props.onL4Event(data);
    }
  },
  onMesEvent: (data) => {
    if (props.onMesEvent) {
      props.onMesEvent(data);
    }
  },
  onError: (error) => {
    console.log('SSE 连接错误:', error);
    addSseLog('连接错误', 'error');
  },
  onConnect: () => {
    addSseLog('已连接到服务器', 'success');
  }
});

const modalTitle = ref('SSE 连接状态');
const modalItems = ref([
  { label: '当前状态', value: sseStatus },
  { label: '客户端ID', value: clientId || 'hmi-main-client' },
  { label: '服务器地址', value: serverUrl }
]);

// 启动连接冷却时间
const startCooldown = () => {
  isInCooldown.value = true;
  cooldownRemaining.value = 5;
  
  const updateCooldown = () => {
    if (cooldownRemaining.value > 0) {
      cooldownRemaining.value--;
      cooldownTimer = window.setTimeout(updateCooldown, 1000);
    } else {
      isInCooldown.value = false;
      cooldownTimer = null;
    }
  };
  
  updateCooldown();
};

// 包装断开函数，添加冷却逻辑
const sseDisconnect = () => {
  disconnect();
  startCooldown();
};

// 添加 SSE 日志函数
const addSseLog = (message: string, type: 'success' | 'error' | 'log' = 'log') => {
  const timestamp = new Date().toLocaleTimeString('zh-CN', { hour12: false });
  const logEntry = `${timestamp} - ${message}`;
  logs.value.push({ message: logEntry, type });
  
  return logEntry;
};

// 处理清空日志
const handleClearSseLogs = () => {
  logs.value = [];
};

// 监听日志变化，自动滚动
watch(() => logs.value.length, () => {
  if (logContainer.value) {
    const { scrollTop = 0, scrollHeight = 0, clientHeight = 0 } = logContainer.value;
    const isUserAtBottom = scrollTop + clientHeight >= scrollHeight - 10;
    nextTick(() => {
      if (logContainer.value && isUserAtBottom) {
        logContainer.value.scrollTop = logContainer.value.scrollHeight;
      }
    });
  }
});

// 暴露方法和数据
defineExpose({
  show,
  hide,
  logs
});

// 初始化
onMounted(() => {
  connect();
});

// 清理
onBeforeUnmount(() => {
  if (cooldownTimer) {
    clearTimeout(cooldownTimer);
    cooldownTimer = null;
  }
  disconnect();
});
</script>

<style scoped lang="scss">
@use "@/assets/styles/variables" as *;

.status-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 6px;
  transition: all 0.2s ease;
  
  &.status-button {
    cursor: pointer;
    
    &:hover {
      background-color: rgba(255, 255, 255, 0.1);
    }
  }
  
  .status-icon {
    width: 16px;
    height: 16px;
    color: #8395B6;
    
    &.success {
      color: $success-color;
    }
    
    &.error {
      color: $error-color;
    }
    
    &.warning {
      color: $warning-color;
    }
  }
  
  .status-label {
    font-size: 13px;
    color: #8395B6;
    white-space: nowrap;
  }
  
  .status-value {
    font-size: 13px;
    font-weight: 500;
    
    &.success {
      color: $success-color;
    }
    
    &.error {
      color: $error-color;
    }
    
    &.warning {
      color: $warning-color;
    }
  }
}

.modal-label {
  font-size: $text-size;
  font-weight: bold;
}

.sse-controls {
  margin: $spacing-md 0;
  display: flex;
  gap: $spacing-md;
  @include transition-ease;

  .clear-btn {
    display: flex;
    align-items: center;
    gap: 4px;

    svg {
      width: 1rem;
      height: 1rem;
    }
  }
}

.sse-logs {
  flex: 1;
  background-color: #283D63;
  border: 1px solid $border-light;
  border-radius: $border-radius;
  padding: $spacing-md;
  overflow-y: auto;
  font-family: 'Consolas', 'Monaco', monospace;
  position: relative;
  backdrop-filter: blur(10px);
  min-height: 200px;
  max-height: 200px;

  .log-item {
    color: $white;
    font-size: 13px;
    line-height: 1.5;
    margin-bottom: 3px;
    padding: 2px 4px;
    border-radius: 3px;
    word-wrap: break-word;
    white-space: pre-wrap;

    &.success {
      color: $success-color;
    }

    &.error {
      color: $error-color;
    }
  }
  
  .empty-logs {
    @include flex-center;
    flex-direction: column;
    height: calc(200px - 2 * $spacing-md - 2px);
    color: $text-gray;
    opacity: 0.6;
    font-size: 13px;
    
    .empty-icon {
      @include icon-base(32px);
      margin-bottom: $spacing-sm;
      color: $text-gray;
      opacity: 0.5;
    }
  }

  /* 滚动条样式 */
  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: $bg-light;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb {
    background: $primary-color;
    border-radius: 3px;

    &:hover {
      background: $primary-light;
    }
  }
}
</style>
