<template>
  <div class="serial-config">
    <a-space direction="vertical" style="width: 100%">
      <div style="display: flex; align-items: center; justify-content: flex-end; margin-bottom: 16px">
        <StatusIndicator :connected="dataStore.serialConnected" />
      </div>
      
      <a-form layout="vertical">
        <a-form-item label="串口选择">
          <a-select 
            v-model:value="dataStore.serialConfig.port" 
            :disabled="isLoading || dataStore.serialConnected"
            placeholder="请选择串口"
            style="width: 100%"
          >
            <a-select-option v-for="port in dataStore.availablePorts" :key="port" :value="port">
              {{ port }}
            </a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="波特率">
          <a-select 
            v-model:value="dataStore.serialConfig.baudrate"
            :disabled="isLoading || dataStore.serialConnected"
            style="width: 100%"
          >
            <a-select-option :value="9600">9600</a-select-option>
            <a-select-option :value="19200">19200</a-select-option>
            <a-select-option :value="38400">38400</a-select-option>
            <a-select-option :value="57600">57600</a-select-option>
            <a-select-option :value="115200">115200</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-space wrap>
          <a-button 
            v-if="!dataStore.serialConnected" 
            type="primary" 
            @click="connectSerial"
            :disabled="isLoading || !dataStore.serialConfig.port"
            :loading="isLoading && currentAction === 'connect'"
          >
            连接串口
          </a-button>
          <a-button 
            v-else 
            danger 
            @click="disconnectSerial"
            :disabled="isLoading"
            :loading="isLoading && currentAction === 'disconnect'"
          >
            断开串口
          </a-button>
          <a-button 
            @click="refreshSerialPorts"
            :disabled="isLoading"
            :loading="isLoading && currentAction === 'refresh'"
          >
            刷新串口列表
          </a-button>
          <a-button
            @click="discoverTerminals"
            :loading="isDiscovering"
            :disabled="!dataStore.serialConnected"
          >
            发现终端
          </a-button>
        </a-space>
        
        <a-divider orientation="left" style="margin: 16px 0">发送数据</a-divider>
        
        <a-form-item label="发送数据到串口">
          <a-input 
            v-model:value="dataStore.serialSendData" 
            placeholder="输入要发送的数据"
            :disabled="isLoading || !dataStore.serialConnected"
          />
        </a-form-item>
        
        <a-button 
          type="primary"
          @click="sendSerialData"
          :disabled="isLoading || !dataStore.serialConnected || !dataStore.serialSendData.trim()"
          :loading="isLoading && currentAction === 'send'"
        >
          发送
        </a-button>
      </a-form>
      
      <!-- 状态消息 -->
      <a-alert 
        v-if="statusMessage" 
        :type="statusType"
        :message="statusMessage"
        show-icon
        :closable="false"
        style="margin-top: 16px"
      />
    </a-space>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useDataStore } from '../stores/dataStore'
import apiService from '../api/apiService'
import StatusIndicator from './StatusIndicator.vue'
import { message } from 'ant-design-vue'

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

// 加载状态管理
const isLoading = ref(false)
const currentAction = ref('')
const isDiscovering = ref(false)
const statusMessage = ref('')
const statusType = ref('info')

// 显示状态消息
const showStatus = (msg, type = 'info', duration = 3000) => {
  statusMessage.value = msg
  statusType.value = type
  
  // 使用Ant Design消息组件
  switch (type) {
    case 'success':
      message.success(msg, duration / 1000)
      break
    case 'error':
      message.error(msg, duration / 1000)
      break
    case 'warning':
      message.warning(msg, duration / 1000)
      break
    default:
      message.info(msg, duration / 1000)
  }
  
  // 自动清除消息
  if (duration > 0) {
    setTimeout(() => {
      statusMessage.value = ''
    }, duration)
  }
}

// 计算状态图标
const statusIcon = computed(() => {
  switch (statusType.value) {
    case 'success':
      return '✅'
    case 'error':
      return '❌'
    case 'warning':
      return '⚠️'
    default:
      return 'ℹ️'
  }
})

// 刷新串口列表
const refreshSerialPorts = async () => {
  isLoading.value = true
  currentAction.value = 'refresh'
  
  try {
    const response = await apiService.serial.getPorts()
    if (response.data.success) {
      dataStore.setAvailablePorts(response.data.ports)
      showStatus('串口列表刷新成功', 'success')
    } else {
      showStatus('刷新失败: ' + response.data.message, 'error')
    }
  } catch (error) {
    console.error('获取串口列表失败:', error)
    showStatus('获取串口列表失败: ' + (error.response?.data?.message || error.message), 'error')
  } finally {
    isLoading.value = false
    currentAction.value = ''
  }
}

// 发现终端
const discoverTerminals = async () => {
  isDiscovering.value = true
  try {
    const res = await apiService.modbus.broadcastQuery({ timeout: 3 })
    if (res.data.success && res.data.responses) {
      showStatus(`发现 ${res.data.responses.length} 个终端`, 'success')
    } else {
      showStatus(res.data.message || '未发现终端', 'info')
    }
  } catch (e) {
    showStatus('发现终端失败: ' + (e.response?.data?.message || e.message), 'error')
  } finally {
    isDiscovering.value = false
  }
}

// 连接串口
const connectSerial = async () => {
  if (!dataStore.serialConfig.port) {
    showStatus('请选择串口', 'warning')
    return
  }
  
  isLoading.value = true
  currentAction.value = 'connect'
  
  try {
    const response = await apiService.serial.connect(dataStore.serialConfig)
    if (response.data.success) {
      dataStore.setSerialConnected(true)
      showStatus('串口连接成功', 'success')
    } else {
      showStatus(response.data.message, 'error')
    }
  } catch (error) {
    console.error('连接串口失败:', error)
    showStatus('连接串口失败: ' + (error.response?.data?.message || error.message), 'error')
  } finally {
    isLoading.value = false
    currentAction.value = ''
  }
}

// 断开串口
const disconnectSerial = async () => {
  isLoading.value = true
  currentAction.value = 'disconnect'
  
  try {
    const response = await apiService.serial.disconnect()
    if (response.data.success) {
      dataStore.setSerialConnected(false)
      showStatus('串口已断开连接', 'info')
    } else {
      showStatus(response.data.message, 'error')
    }
  } catch (error) {
    console.error('断开串口失败:', error)
    showStatus('断开串口失败: ' + (error.response?.data?.message || error.message), 'error')
  } finally {
    isLoading.value = false
    currentAction.value = ''
  }
}

// 发送数据到串口
const sendSerialData = async () => {
  if (!dataStore.serialSendData.trim()) {
    showStatus('请输入要发送的数据', 'warning')
    return
  }
  
  if (!dataStore.serialConnected) {
    showStatus('请先连接串口', 'warning')
    return
  }
  
  isLoading.value = true
  currentAction.value = 'send'
  const dataToSend = dataStore.serialSendData
  
  try {
    const response = await apiService.serial.sendData(dataToSend)
    if (response.data.success) {
      // 清空输入框
      dataStore.serialSendData = ''
      showStatus(`数据发送成功: ${dataToSend}`, 'success')
    } else {
      showStatus(response.data.message, 'error')
    }
  } catch (error) {
    console.error('发送数据失败:', error)
    showStatus('发送数据失败: ' + (error.response?.data?.message || error.message), 'error')
  } finally {
    isLoading.value = false
    currentAction.value = ''
  }
}

// 组件挂载时初始化
onMounted(() => {
  refreshSerialPorts()
})
</script>

<style scoped>
.serial-config {
  /* 卡片基础样式已在App.vue中定义 */
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--space-md) var(--space-lg);
  border-bottom: 1px solid var(--border-color);
  background-color: var(--bg-primary);
}

.card-title {
  display: flex;
  align-items: center;
  gap: var(--space-sm);
  flex: 1;
}

.icon-serial {
  font-size: 1.5rem;
  transition: transform var(--transition-fast);
}

.serial-config:hover .icon-serial {
  transform: rotate(10deg);
}

.card-title h2 {
  margin: 0;
  font-size: 18px;
  color: var(--text-primary);
  font-weight: 600;
}

.card-content {
  padding: var(--space-lg);
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: var(--space-lg);
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: var(--space-xs);
}

.form-group label {
  display: block;
  font-weight: 500;
  color: var(--text-secondary);
  font-size: 14px;
}

.form-group select,
.form-group input {
  width: 100%;
  padding: var(--space-sm) var(--space-md);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-lg);
  background-color: var(--bg-surface);
  color: var(--text-primary);
  font-size: 15px;
  transition: all var(--transition-fast);
}

.form-group select:focus,
.form-group input:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.2);
  background-color: var(--bg-primary);
}

.form-group select.input-disabled,
.form-group input.input-disabled {
  opacity: 0.6;
  cursor: not-allowed;
  background-color: var(--bg-tertiary);
}

.button-group {
  display: flex;
  gap: var(--space-sm);
  flex-wrap: wrap;
}

.btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: var(--space-sm) var(--space-md);
  border: none;
  border-radius: var(--radius-lg);
  font-size: 15px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  min-width: 120px;
  gap: var(--space-xs);
  position: relative;
  overflow: hidden;
}

.btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.btn:active:not(:disabled) {
  transform: translateY(0);
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.btn-primary {
  background-color: var(--primary-color);
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background-color: var(--primary-hover);
}

.btn-danger {
  background-color: var(--error-color);
  color: white;
}

.btn-danger:hover:not(:disabled) {
  background-color: var(--error-hover);
}

.btn-secondary {
  background-color: var(--bg-surface);
  color: var(--text-secondary);
  border: 1px solid var(--border-color);
}

.btn-secondary:hover:not(:disabled) {
  background-color: var(--bg-hover);
  border-color: var(--primary-color);
  color: var(--primary-color);
}

/* 加载动画 */
.btn-loading {
  position: relative;
}

.loading-spinner {
  display: inline-block;
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: white;
  animation: spin 1s ease-in-out infinite;
}

.btn-secondary .loading-spinner {
  border-color: rgba(0, 0, 0, 0.1);
  border-top-color: var(--text-primary);
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.form-section {
  margin-top: var(--space-md);
  padding-top: var(--space-md);
  border-top: 1px solid var(--border-color);
}

.form-section h3 {
  margin-top: 0;
  margin-bottom: var(--space-md);
  font-size: 16px;
  color: var(--text-secondary);
  font-weight: 500;
}

/* 状态消息 */
.status-message {
  display: flex;
  align-items: center;
  gap: var(--space-sm);
  margin-top: var(--space-md);
  padding: var(--space-sm) var(--space-md);
  border-radius: var(--radius-lg);
  font-size: 14px;
  transition: opacity var(--transition-fast), transform var(--transition-fast);
  opacity: 0;
  transform: translateY(-10px);
  animation: slideIn var(--transition-fast) ease forwards;
}

@keyframes slideIn {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.status-message.info {
  background-color: rgba(59, 130, 246, 0.1);
  color: var(--primary-color);
  border-left: 4px solid var(--primary-color);
}

.status-message.success {
  background-color: rgba(16, 185, 129, 0.1);
  color: var(--success-color);
  border-left: 4px solid var(--success-color);
}

.status-message.error {
  background-color: rgba(239, 68, 68, 0.1);
  color: var(--error-color);
  border-left: 4px solid var(--error-color);
}

.status-message.warning {
  background-color: rgba(245, 158, 11, 0.1);
  color: #f59e0b;
  border-left: 4px solid #f59e0b;
}

.status-icon {
  font-size: 1.1rem;
}

.status-text {
  flex: 1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .button-group {
    flex-direction: column;
  }
  
  .btn {
    width: 100%;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--space-sm);
  }
  
  .card-content {
    padding: var(--space-md);
    gap: var(--space-md);
  }
}

/* 聚焦状态改进 */
.form-group select:focus-visible,
.form-group input:focus-visible {
  outline: 2px solid transparent;
  outline-offset: 2px;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.3);
}
</style>