<template>
  <div class="mqtt-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.mqttConnected" />
      </div>
      
      <a-form layout="vertical">
        <a-form-item 
          label="服务器地址" 
          :validate-status="!dataStore.mqttConfig.broker && showErrors ? 'error' : undefined"
        >
          <a-input 
            v-model:value="dataStore.mqttConfig.broker" 
            placeholder="例如: 127.0.0.1"
            :disabled="dataStore.mqttConnected"
            :status="!dataStore.mqttConfig.broker && showErrors ? 'error' : undefined"
          />
        </a-form-item>
        
        <a-form-item 
          label="端口" 
          :validate-status="!dataStore.mqttConfig.port && showErrors ? 'error' : undefined"
        >
          <a-input-number 
            v-model:value="dataStore.mqttConfig.port" 
            :min="1" 
            :max="65535"
            :disabled="dataStore.mqttConnected"
            placeholder="默认为 1883"
            :status="!dataStore.mqttConfig.port && showErrors ? 'error' : undefined"
          />
        </a-form-item>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="用户名">
              <a-input 
                v-model:value="dataStore.mqttConfig.username" 
                :disabled="dataStore.mqttConnected"
                placeholder="可选"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="密码">
              <a-input-password 
                v-model:value="dataStore.mqttConfig.password" 
                :disabled="dataStore.mqttConnected"
                placeholder="可选"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="客户端ID">
          <a-input 
            v-model:value="dataStore.mqttConfig.clientId" 
            :disabled="dataStore.mqttConnected"
            placeholder="可选，自动生成"
          />
        </a-form-item>
        
        <a-form-item 
          label="订阅主题 (多个主题用逗号分隔)" 
          :validate-status="!dataStore.mqttConfig.topics && showErrors ? 'error' : undefined"
        >
          <a-input 
            v-model:value="dataStore.mqttConfig.topics" 
            :disabled="dataStore.mqttConnected"
            placeholder="例如: serial_gateway/in,test/data"
            :status="!dataStore.mqttConfig.topics && showErrors ? 'error' : undefined"
          />
        </a-form-item>
        
        <a-space wrap>
          <a-button 
            v-if="!dataStore.mqttConnected" 
            type="primary" 
            @click="connectMQTT" 
            :disabled="isConnecting"
            :loading="isConnecting"
          >
            连接MQTT
          </a-button>
          <a-button 
            v-else 
            danger 
            @click="disconnectMQTT" 
            :disabled="isDisconnecting"
            :loading="isDisconnecting"
          >
            断开MQTT
          </a-button>
          <a-button 
            v-if="dataStore.mqttConnected" 
            @click="subscribeTopics" 
            :disabled="isSubscribing"
            :loading="isSubscribing"
          >
            重新订阅
          </a-button>
        </a-space>
        
        <a-divider orientation="left" style="margin: 16px 0">消息发布</a-divider>
        
        <a-form-item 
          label="发布主题" 
          :validate-status="!dataStore.mqttPublishTopic && showErrors ? 'error' : undefined"
        >
          <a-input 
            v-model:value="dataStore.mqttPublishTopic" 
            placeholder="例如: serial_gateway/out"
            :status="!dataStore.mqttPublishTopic && showErrors ? 'error' : undefined"
          />
        </a-form-item>
        
        <a-form-item 
          label="发送数据" 
          :validate-status="!dataStore.mqttSendData.trim() && showErrors ? 'error' : undefined"
        >
          <a-input-textarea 
            v-model:value="dataStore.mqttSendData" 
            placeholder="输入要发送的数据" 
            :rows="3"
            :status="!dataStore.mqttSendData.trim() && showErrors ? 'error' : undefined"
          />
        </a-form-item>
        
        <div style="display: flex; justify-content: flex-end;">
          <a-button 
            type="primary" 
            @click="publishMQTTData" 
            :disabled="isPublishing"
            :loading="isPublishing"
            danger
          >
            发布
          </a-button>
        </div>
      </a-form>
    </a-space>
  </div>
</template>

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

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

// 状态管理
const isConnecting = ref(false)
const isDisconnecting = ref(false)
const isSubscribing = ref(false)
const isPublishing = ref(false)
const showErrors = ref(false)

// 连接MQTT
const connectMQTT = async () => {
  // 验证必填字段
  if (!dataStore.mqttConfig.broker) {
    showErrors.value = true
    showNotification('请输入MQTT服务器地址', 'error')
    return
  }
  showErrors.value = false
  
  // 处理主题列表，添加空值检查
  let topics = []
  if (dataStore.mqttConfig.topics) {
    topics = dataStore.mqttConfig.topics.split(',').map(t => t.trim()).filter(t => t)
  }
  if (topics.length === 0) {
    topics = ['serial_gateway/in']
  }
  
  try {
    isConnecting.value = true
    const response = await apiService.mqtt.connect({
      ...dataStore.mqttConfig,
      topics: topics
    })
    
    if (response.data.success) {
      dataStore.setMQTTConnected(true)
      showNotification(response.data.message, 'success')
      
      // 更新转发配置
      await updateForwardConfig()
    } else {
      showNotification(response.data.message, 'error')
    }
  } catch (error) {
    console.error('连接MQTT失败:', error)
    showNotification('连接MQTT失败: ' + (error.response?.data?.message || error.message), 'error')
  } finally {
    isConnecting.value = false
  }
}

// 断开MQTT
const disconnectMQTT = async () => {
  try {
    isDisconnecting.value = true
    const response = await apiService.mqtt.disconnect()
    if (response.data.success) {
      dataStore.setMQTTConnected(false)
      showNotification(response.data.message, 'success')
    }
  } catch (error) {
    console.error('断开MQTT失败:', error)
    showNotification('断开MQTT失败: ' + (error.response?.data?.message || error.message), 'error')
  } finally {
    isDisconnecting.value = false
  }
}

// 重新订阅主题
const subscribeTopics = async () => {
  if (!dataStore.mqttConnected) {
    showNotification('请先连接MQTT', 'error')
    return
  }
  
  // 添加空值检查
  let topics = []
  if (dataStore.mqttConfig.topics) {
    topics = dataStore.mqttConfig.topics.split(',').map(t => t.trim()).filter(t => t)
  }
  if (topics.length === 0) {
    showNotification('请输入要订阅的主题', 'error')
    return
  }
  
  try {
    isSubscribing.value = true
    const response = await apiService.mqtt.subscribe(topics)
    if (response.data.success) {
      showNotification(response.data.message, 'success')
    } else {
      showNotification(response.data.message, 'error')
    }
  } catch (error) {
    console.error('订阅主题失败:', error)
    showNotification('订阅主题失败: ' + (error.response?.data?.message || error.message), 'error')
  } finally {
    isSubscribing.value = false
  }
}

// 发布MQTT消息
const publishMQTTData = async () => {
  // 验证输入
  if (!dataStore.mqttPublishTopic || !dataStore.mqttSendData.trim()) {
    showErrors.value = true
    showNotification('请输入主题和消息内容', 'error')
    return
  }
  showErrors.value = false
  
  try {
    isPublishing.value = true
    const response = await apiService.mqtt.publish(dataStore.mqttPublishTopic, dataStore.mqttSendData)
    if (response.data.success) {
      // 清空输入框
      dataStore.mqttSendData = ''
      showNotification('消息发布成功', 'success')
    } else {
      showNotification(response.data.message, 'error')
    }
  } catch (error) {
    console.error('发布消息失败:', error)
    showNotification('发布消息失败: ' + (error.response?.data?.message || error.message), 'error')
  } finally {
    isPublishing.value = false
  }
}

// 更新转发配置
const updateForwardConfig = async () => {
  try {
    await apiService.forward.setConfig({
      serial_to_mqtt: forwardStore.serialToMQTT,
      mqtt_to_serial: forwardStore.mqttToSerial,
      publish_topic: dataStore.mqttPublishTopic
    })
  } catch (error) {
    console.error('更新转发配置失败:', error)
  }
}

// 更新MQTT状态
const updateMQTTStatus = async () => {
  try {
    const response = await apiService.mqtt.getStatus()
    dataStore.setMQTTConnected(response.data.connected)
  } catch (error) {
    console.error('获取MQTT状态失败:', error)
    // 请求失败时，确保状态为未连接
    dataStore.setMQTTConnected(false)
  }
}

// 显示通知
const showNotification = (msg, type = 'info') => {
  // 使用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)
  }
}

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

<style scoped>
.mqtt-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-mqtt {
  font-size: 1.5rem;
  transition: transform var(--transition-fast);
}

.mqtt-config:hover .icon-mqtt {
  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);
}

.card-divider {
  height: 1px;
  background-color: var(--border-color);
  margin: 0;
}

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

.form-row {
  display: flex;
  gap: var(--space-md);
  margin-bottom: var(--space-md);
  align-items: flex-end;
}

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

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

.form-group input,
.form-group textarea {
  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 input:focus,
.form-group textarea: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 input.input-error,
.form-group textarea.input-error {
  border-color: var(--error-color);
}

.form-group textarea {
  resize: vertical;
  min-height: 80px;
  font-family: inherit;
}

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

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

.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-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-success {
  background-color: var(--success-color);
  color: white;
}

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

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

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

/* 加载动画 */
.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);
  }
}

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

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