<template>
  <div class="forward-config">
    <a-space direction="vertical" style="width: '100%'">
      <div style="display: 'flex'; align-items: 'center'; margin-bottom: '16px'">
        <a-space align="center">
          <a-icon type="redo" style="color: '#52c41a'" />
          <span style="font-weight: 'bold'; font-size: '16px'">转发配置</span>
        </a-space>
      </div>
      
      <a-form layout="vertical">
        <div class="checkbox-group">
          <a-checkbox 
            v-model:checked="forwardStore.serialToMQTT"
            @change="applyConfig"
            style="margin-bottom: '8px'"
          >
            串口数据转发到MQTT
          </a-checkbox>
          
          <a-checkbox 
            v-model:checked="forwardStore.mqttToSerial"
            @change="applyConfig"
            style="margin-bottom: '8px'"
          >
            MQTT数据转发到串口
          </a-checkbox>
        </div>
        
        <a-form-item 
          label="MQTT发布主题（用于串口转发）" 
          :validate-status="!publishTopic && showErrors ? 'error' : undefined"
        >
          <a-input 
            v-model:value="publishTopic" 
            placeholder="例如: serial_gateway/out"
            :status="!publishTopic && showErrors ? 'error' : undefined"
          />
        </a-form-item>
        
        <div style="display: 'flex'; justify-content: 'flex-end'">
          <a-button 
            type="primary" 
            @click="applyConfig"
            :disabled="isApplying"
            :loading="isApplying"
          >
            应用配置
          </a-button>
        </div>
        
        <a-alert 
          v-if="statusMessage" 
          :message="statusMessage" 
          :type="statusType"
          show-icon
          style="margin-top: '16px'"
        />
      </a-form>
    </a-space>
  </div>
</template>

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

// 使用转发配置存储
const forwardStore = useForwardStore()

// MQTT发布主题
const publishTopic = ref('serial_gateway/out')

// 状态管理
const statusMessage = ref('')
const statusType = ref('info')
const isApplying = ref(false)
const showErrors = ref(false)

// 应用配置
const applyConfig = async () => {
  // 验证发布主题
  if (forwardStore.serialToMQTT && !publishTopic.value.trim()) {
    showErrors.value = true
    showStatus('请输入MQTT发布主题', 'error')
    return
  }
  showErrors.value = false
  
  try {
    isApplying.value = true
    const response = await apiService.forward.setConfig({
      serial_to_mqtt: forwardStore.serialToMQTT,
      mqtt_to_serial: forwardStore.mqttToSerial,
      publish_topic: publishTopic.value
    })
    
    if (response.data.success) {
      showStatus('配置应用成功', 'success')
      setTimeout(() => {
        statusMessage.value = ''
      }, 3000)
    } else {
      showStatus('配置应用失败: ' + response.data.message, 'error')
    }
  } catch (error) {
    console.error('应用配置失败:', error)
    showStatus('配置应用失败: ' + (error.response?.data?.message || error.message), 'error')
  } finally {
    isApplying.value = false
  }
}

// 加载当前配置
const loadCurrentConfig = async () => {
  try {
    const response = await apiService.forward.getStatus()
    if (response.data && response.data.success) {
      // 更新转发配置
      forwardStore.updateFromAPIResponse(response.data)
      // 更新发布主题
      if (response.data.publish_topic) {
        publishTopic.value = response.data.publish_topic
      }
    } else if (response.data) {
      // 更新转发配置
      forwardStore.updateFromAPIResponse(response.data)
      // 更新发布主题
      if (response.data.publish_topic) {
        publishTopic.value = response.data.publish_topic
      }
    }
  } catch (error) {
    console.error('加载配置失败:', error)
  }
}

// 显示状态消息
const showStatus = (msg, type = 'info') => {
  statusMessage.value = msg
  statusType.value = type
  
  // 使用Ant Design消息组件显示临时通知
  switch (type) {
    case 'success':
      message.success(msg)
      break
    case 'error':
      message.error(msg)
      break
    case 'warning':
      message.warning(msg)
      break
    default:
      message.info(msg)
  }
}

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

// 组件挂载时加载配置
onMounted(() => {
  loadCurrentConfig()
})
</script>

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

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

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

.icon-forward {
  font-size: 1.5rem;
  transition: transform 0.3s ease;
}

.forward-config:hover .icon-forward {
  transform: rotate(180deg);
  transition-duration: 1s;
}

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

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

.checkbox-group {
  margin-bottom: var(--spacing-lg);
  padding: var(--spacing-md);
  background-color: var(--background-secondary);
  border-radius: var(--border-radius);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.checkbox-item {
  margin-bottom: var(--spacing-sm);
}

.checkbox-item:last-child {
  margin-bottom: 0;
}

.checkbox-container {
  display: flex;
  align-items: center;
  position: relative;
  cursor: pointer;
  font-size: var(--font-size-base);
  color: var(--text-primary);
  user-select: none;
  transition: color 0.2s ease;
}

.checkbox-container:hover {
  color: var(--primary-color);
  font-weight: 500;
}

.checkbox-container input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
  height: 0;
  width: 0;
}

.checkbox-custom {
  position: relative;
  height: 20px;
  width: 20px;
  margin-right: var(--spacing-sm);
  background-color: var(--input-background);
  border: 2px solid var(--border-color);
  border-radius: var(--border-radius);
  transition: all 0.2s ease;
}

.checkbox-container:hover input ~ .checkbox-custom {
  border-color: var(--primary-color);
}

.checkbox-container input:checked ~ .checkbox-custom {
  background-color: var(--primary-color);
  border-color: var(--primary-color);
}

.checkbox-custom:after {
  content: "";
  position: absolute;
  display: none;
}

.checkbox-container input:checked ~ .checkbox-custom:after {
  display: block;
}

.checkbox-container .checkbox-custom:after {
  left: 6px;
  top: 3px;
  width: 5px;
  height: 10px;
  border: solid white;
  border-width: 0 3px 3px 0;
  transform: rotate(45deg);
}

.checkbox-label {
  font-weight: 400;
}

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

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

.form-group input {
  width: 100%;
  padding: var(--spacing-sm) var(--spacing-md);
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  background-color: var(--input-background);
  color: var(--text-primary);
  font-size: var(--font-size-base);
  transition: all 0.2s ease;
}

.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(--card-background);
}

.form-group input.input-error {
  border-color: var(--error-color);
}

.button-group {
  display: flex;
  gap: var(--spacing-sm);
  margin-top: var(--spacing-lg);
  flex-wrap: wrap;
}

.button-group.justify-end {
  justify-content: flex-end;
}

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

.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);
}

.status-message {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  margin-top: var(--spacing-md);
  padding: var(--spacing-sm) var(--spacing-md);
  border-radius: var(--border-radius);
  font-size: var(--font-size-sm);
  transition: all 0.3s ease;
  opacity: 0;
  transform: translateY(-10px);
  animation: slideIn 0.3s ease forwards;
}

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

.status-message.info {
  background-color: var(--info-background);
  color: var(--info-color);
  border-left: 4px solid var(--info-color);
}

.status-message.success {
  background-color: var(--success-background);
  color: var(--success-color);
  border-left: 4px solid var(--success-color);
}

.status-message.error {
  background-color: var(--error-background);
  color: var(--error-color);
  border-left: 4px solid var(--error-color);
}

.status-message.warning {
  background-color: var(--warning-background);
  color: var(--warning-color);
  border-left: 4px solid var(--warning-color);
}

.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(--spacing-sm);
  }
  
  .card-content {
    padding: var(--spacing-md);
    gap: var(--spacing-md);
  }
  
  .checkbox-custom {
    height: 18px;
    width: 18px;
  }
}

/* 聚焦状态改进 */
.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>