<template>
  <div class="dtu-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.dtuStatus.online" />
        <span style="margin-left: 8px; font-size: 12px; color: #8c8c8c">
          {{ dataStore.dtuStatus.online ? '在线' : '离线' }}
        </span>
      </div>

      <a-alert
        v-if="topicPreview"
        type="info"
        show-icon
        style="margin-bottom: 16px"
      >
        <template #message>
          <div>主题预览: <code>{{ topicPreview }}</code></div>
        </template>
      </a-alert>

      <a-form layout="vertical">
        <a-divider orientation="left">MQTT主题配置</a-divider>

        <a-form-item
          label="根主题前缀"
          :validate-status="!formData.topic_prefix && showErrors ? 'error' : undefined"
          help="用于在同一Broker上与其他业务系统做命名空间隔离"
        >
          <a-input
            v-model:value="formData.topic_prefix"
            placeholder="例如: 线架系统"
            :status="!formData.topic_prefix && showErrors ? 'error' : undefined"
          >
            <template #prefix>
              <span style="color: #8c8c8c">/</span>
            </template>
          </a-input>
        </a-form-item>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item
              label="客户ID"
              :validate-status="!formData.customer_id && showErrors ? 'error' : undefined"
              help="用于主题隔离，不同客户使用不同ID"
            >
              <a-input
                v-model:value="formData.customer_id"
                placeholder="例如: customer001"
                :status="!formData.customer_id && showErrors ? 'error' : undefined"
              >
                <template #prefix>
                  <span style="color: #8c8c8c">/</span>
                </template>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              label="DTU ID"
              :validate-status="!formData.dtu_id && showErrors ? 'error' : undefined"
              help="DTU设备的唯一标识"
            >
              <a-input
                v-model:value="formData.dtu_id"
                placeholder="例如: dtu001"
                :status="!formData.dtu_id && showErrors ? 'error' : undefined"
              >
                <template #prefix>
                  <span style="color: #8c8c8c">/</span>
                </template>
              </a-input>
            </a-form-item>
          </a-col>
        </a-row>

        <a-divider orientation="left">设备信息</a-divider>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="固件版本">
              <a-input
                v-model:value="formData.firmware_version"
                placeholder="例如: 1.0.0"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="心跳间隔(秒)">
              <a-input-number
                v-model:value="formData.heartbeat_interval"
                :min="10"
                :max="3600"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="DTU功能">
          <div style="display: flex; align-items: center; gap: 12px">
            <a-switch
              v-model:checked="formData.enabled"
              checked-children="开"
              un-checked-children="关"
            />
            <a-tag :color="formData.enabled ? 'green' : 'default'">
              {{ formData.enabled ? '已启用' : '已禁用' }}
            </a-tag>
          </div>
        </a-form-item>

        <a-divider orientation="left">状态信息</a-divider>

        <a-descriptions :column="2" size="small" bordered>
          <a-descriptions-item label="注册状态">
            <a-tag :color="dataStore.dtuStatus.registered ? 'green' : 'default'">
              {{ dataStore.dtuStatus.registered ? '已注册' : '未注册' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="在线状态">
            <a-tag :color="dataStore.dtuStatus.online ? 'green' : 'red'">
              {{ dataStore.dtuStatus.online ? '在线' : '离线' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="最后心跳">
            {{ dataStore.dtuStatus.last_heartbeat || '无' }}
          </a-descriptions-item>
          <a-descriptions-item label="主题前缀">
            {{ dataStore.dtuConfig.topic_prefix || '未配置' }}
          </a-descriptions-item>
          <a-descriptions-item label="主板温度">
            <span :style="{ color: getTempColor(dataStore.dtuStatus.temperature) }">
              {{ dataStore.dtuStatus.temperature !== null && dataStore.dtuStatus.temperature !== undefined
                  ? `${dataStore.dtuStatus.temperature}°C` : '--' }}
            </span>
          </a-descriptions-item>
          <a-descriptions-item label="固件版本">
            {{ dataStore.dtuStatus.firmware_version || dataStore.dtuConfig.firmware_version || '--' }}
          </a-descriptions-item>
          <a-descriptions-item label="CPU 使用率">
            <a-progress
              v-if="dataStore.dtuStatus.cpu_usage !== null && dataStore.dtuStatus.cpu_usage !== undefined"
              :percent="Math.round(dataStore.dtuStatus.cpu_usage)"
              :status="dataStore.dtuStatus.cpu_usage > 80 ? 'exception' : 'normal'"
              style="width: 100%"
            />
            <span v-else>--</span>
          </a-descriptions-item>
          <a-descriptions-item label="内存使用率">
            <a-progress
              v-if="dataStore.dtuStatus.memory_usage !== null && dataStore.dtuStatus.memory_usage !== undefined"
              :percent="Math.round(dataStore.dtuStatus.memory_usage)"
              :status="dataStore.dtuStatus.memory_usage > 80 ? 'exception' : 'normal'"
              style="width: 100%"
            />
            <span v-else>--</span>
          </a-descriptions-item>
        </a-descriptions>

        <div style="display: flex; justify-content: flex-end; margin-top: 16px">
          <a-space wrap>
            <a-button
              type="primary"
              @click="saveConfig"
              :loading="isSaving"
            >
              保存配置
            </a-button>
            <a-button
              @click="registerDTU"
              :loading="isRegistering"
              :disabled="!canRegister"
            >
              手动注册
            </a-button>
            <a-button
              @click="refreshStatus"
              :loading="isRefreshing"
            >
              刷新状态
            </a-button>
          </a-space>
        </div>

        <a-divider orientation="left">广播控制</a-divider>

        <a-alert
          type="info"
          show-icon
          style="margin-bottom: 16px"
        >
          <template #message>
            <div>发送广播消息到所有在线DTU设备</div>
          </template>
        </a-alert>

        <a-space wrap style="margin-bottom: 16px">
          <a-button
            @click="sendDiscoverBroadcast"
            :loading="isBroadcastingDiscover"
            :disabled="!formData.customer_id"
          >
            <template #icon><ScanOutlined /></template>
            发送DTU发现广播
          </a-button>
          <a-button
            @click="sendConfigBroadcast"
            :loading="isBroadcastingConfig"
            :disabled="!formData.customer_id"
          >
            <template #icon><SettingOutlined /></template>
            发送批量配置广播
          </a-button>
        </a-space>

        <a-collapse v-model:activeKey="configCollapseKey">
          <a-collapse-panel key="configPayload" header="配置广播内容">
            <a-form layout="vertical">
              <a-form-item label="主题前缀">
                <a-input v-model:value="broadcastConfig.topic_prefix" placeholder="线架系统" />
              </a-form-item>
              <a-form-item label="MQTT服务器">
                <a-input v-model:value="broadcastConfig.mqtt_broker" placeholder="mqtt://localhost:1883" />
              </a-form-item>
              <a-form-item label="心跳间隔(秒)">
                <a-input-number v-model:value="broadcastConfig.heartbeat_interval" :min="10" :max="3600" style="width: 100%" />
              </a-form-item>
            </a-form>
          </a-collapse-panel>
        </a-collapse>
      </a-form>
    </a-space>
  </div>
</template>

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

const dataStore = useDataStore()

const isSaving = ref(false)
const isRegistering = ref(false)
const isRefreshing = ref(false)
const isBroadcastingDiscover = ref(false)
const isBroadcastingConfig = ref(false)
const showErrors = ref(false)
const configCollapseKey = ref(['configPayload'])

const formData = ref({
  topic_prefix: '线架系统',
  customer_id: '',
  dtu_id: '',
  firmware_version: '1.0.0',
  heartbeat_interval: 30,
  enabled: true
})

const broadcastConfig = ref({
  topic_prefix: '线架系统',
  mqtt_broker: 'mqtt://localhost:1883',
  heartbeat_interval: 30
})

const topicPreview = computed(() => {
  if (formData.value.topic_prefix && formData.value.customer_id && formData.value.dtu_id) {
    return `${formData.value.topic_prefix}/${formData.value.customer_id}/dtu/${formData.value.dtu_id}/register`
  }
  return ''
})

const canRegister = computed(() => {
  return formData.value.topic_prefix && formData.value.customer_id && formData.value.dtu_id
})

const getTempColor = (t) => {
  if (t === null || t === undefined) return '#999'
  if (t >= 70) return '#ff4d4f'
  if (t >= 60) return '#faad14'
  return '#52c41a'
}

watch(() => formData.value.topic_prefix, () => {
  if (formData.value.topic_prefix) {
    showErrors.value = false
  }
})

const saveConfig = async () => {
  if (!formData.value.topic_prefix) {
    showErrors.value = true
    message.error('请输入根主题前缀')
    return
  }

  try {
    isSaving.value = true
    const response = await apiService.dtu.updateConfig(formData.value)

    if (response.data.success) {
      dataStore.setDTUConfig(formData.value)
      message.success('配置保存成功')
    } else {
      message.error(response.data.message || '保存失败')
    }
  } catch (error) {
    console.error('保存DTU配置失败:', error)
    message.error('保存配置失败: ' + (error.response?.data?.message || error.message))
  } finally {
    isSaving.value = false
  }
}

const registerDTU = async () => {
  if (!canRegister.value) {
    showErrors.value = true
    message.error('请完整填写主题配置')
    return
  }

  try {
    isRegistering.value = true
    const response = await apiService.dtu.register()

    if (response.data.success) {
      message.success('注册请求已发送')
      await refreshStatus()
    } else {
      message.error(response.data.message || '注册失败')
    }
  } catch (error) {
    console.error('DTU注册失败:', error)
    message.error('注册失败: ' + (error.response?.data?.message || error.message))
  } finally {
    isRegistering.value = false
  }
}

const refreshStatus = async () => {
  try {
    isRefreshing.value = true

    const [configResponse, statusResponse] = await Promise.all([
      apiService.dtu.getConfig(),
      apiService.dtu.getStatus()
    ])

    if (configResponse.data.success) {
      dataStore.setDTUConfig(configResponse.data.data)
      formData.value = { ...configResponse.data.data }
    }

    if (statusResponse.data.success) {
      dataStore.setDTUStatus(statusResponse.data.data)
    }
  } catch (error) {
    console.error('获取DTU状态失败:', error)
  } finally {
    isRefreshing.value = false
  }
}

const sendDiscoverBroadcast = async () => {
  if (!formData.value.customer_id) {
    message.error('请先配置客户ID')
    return
  }

  try {
    isBroadcastingDiscover.value = true
    const response = await apiService.mqtt.broadcastDiscover(formData.value.customer_id)

    if (response.data.success) {
      message.success('DTU发现广播已发送')
    } else {
      message.error(response.data.message || '发送失败')
    }
  } catch (error) {
    console.error('发送发现广播失败:', error)
    message.error('发送失败: ' + (error.response?.data?.message || error.message))
  } finally {
    isBroadcastingDiscover.value = false
  }
}

const sendConfigBroadcast = async () => {
  if (!formData.value.customer_id) {
    message.error('请先配置客户ID')
    return
  }

  try {
    isBroadcastingConfig.value = true
    const response = await apiService.mqtt.broadcastConfig(formData.value.customer_id, broadcastConfig.value)

    if (response.data.success) {
      message.success('批量配置广播已发送')
    } else {
      message.error(response.data.message || '发送失败')
    }
  } catch (error) {
    console.error('发送配置广播失败:', error)
    message.error('发送失败: ' + (error.response?.data?.message || error.message))
  } finally {
    isBroadcastingConfig.value = false
  }
}

onMounted(() => {
  refreshStatus()
  const timer = setInterval(refreshStatus, 30000)
  onUnmounted(() => clearInterval(timer))
})
</script>

<style scoped>
.dtu-config {
  height: 100%;
  display: flex;
  flex-direction: column;
}

code {
  background-color: #f5f5f5;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: monospace;
  font-size: 12px;
}

:deep(.ant-descriptions-bordered .ant-descriptions-item-label) {
  background-color: #fafafa;
}

:deep(.ant-divider-inner-text) {
  font-weight: 500;
  color: #1890ff;
}
</style>