<!--
  组件名称：EnvConfig.vue
  组件描述：环境配置管理页面 - MQTT Broker 连接配置 CRUD，支持多主题配置

  @author czj
  @date 2026-07-29
-->

<template>
  <div class="env-config-page">
    <div class="page-header">
      <h2>环境配置</h2>
      <el-button type="primary" @click="openCreateDialog">
        <el-icon><Plus /></el-icon>新增配置
      </el-button>
    </div>

    <!-- 配置列表 -->
    <el-card shadow="never">
      <el-table :data="configs" v-loading="loading" stripe style="width: 100%">
        <el-table-column prop="name" label="配置名称" min-width="140" />
        <el-table-column prop="brokerHost" label="Broker 地址" min-width="150" />
        <el-table-column prop="brokerPort" label="端口" width="80" />
        <el-table-column label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="statusType(row.status)" size="small">
              {{ statusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="主题配置" min-width="220">
          <template #default="{ row }">
            <div class="topic-tags">
              <el-tag
                v-for="(prefix, type) in normalizeTopics(row)"
                :key="type"
                size="small"
                type="info"
                class="topic-tag"
              >
                {{ deviceTypeLabel(type as string) }}: {{ prefix }}
              </el-tag>
              <span v-if="!hasTopics(row)" class="topic-empty">{{ row.topicPrefix || 'device' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="最后连接" width="170">
          <template #default="{ row }">
            {{ row.lastConnectedAt ? formatTime(row.lastConnectedAt) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="testConnection(row)">测试</el-button>
            <el-button link type="primary" size="small" @click="openEditDialog(row)">编辑</el-button>
            <el-popconfirm title="确定删除此配置？" @confirm="handleDelete(row)">
              <template #reference>
                <el-button link type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑环境配置' : '新增环境配置'" width="640px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" label-position="top">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="配置名称" prop="name">
              <el-input v-model="form.name" placeholder="如：测试环境" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="主题基础前缀" prop="topicPrefix">
              <el-input v-model="form.topicPrefix" placeholder="如：device" @input="onBasePrefixChange" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="14">
            <el-form-item label="Broker 地址" prop="brokerHost">
              <el-input v-model="form.brokerHost" placeholder="如：192.168.1.100" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="端口" prop="brokerPort">
              <el-input-number v-model="form.brokerPort" :min="1" :max="65535" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名">
              <el-input v-model="form.username" placeholder="MQTT 用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码">
              <el-input v-model="form.password" type="password" show-password placeholder="MQTT 密码" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 多主题配置 -->
        <el-divider content-position="left">主题配置（按设备类型）</el-divider>
        <div class="topics-editor">
          <div class="topic-item" v-for="dt in deviceTypes" :key="dt">
            <span class="topic-label">{{ deviceTypeLabel(dt) }}</span>
            <el-input
              v-model="topicValues[dt]"
              :placeholder="`${form.topicPrefix || 'device'}/${dt}`"
              size="default"
              class="topic-input"
            >
              <template #append>/{{ dt }}</template>
            </el-input>
          </div>
          <el-tag type="info" size="small" effect="plain" class="topic-tip">
            修改基础前缀可批量重置各设备主题；也可单独自定义每个设备类型的主题路径
          </el-tag>
        </div>

        <el-row :gutter="20" style="margin-top: 12px">
          <el-col :span="12">
            <el-form-item label="客户端 ID 前缀">
              <el-input v-model="form.clientIdPrefix" placeholder="如：sim" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="TLS 加密">
              <el-switch v-model="form.useTls" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  listEnvConfigs,
  createEnvConfig,
  updateEnvConfig,
  deleteEnvConfig,
  testEnvConnection,
} from '@/api/deviceSim'
import type { EnvConfig, EnvConfigCreate } from '@/types/device'

// 支持的设备类型
const deviceTypes = ['door', 'paperless', 'central', 'client'] as const
const deviceTypeLabels: Record<string, string> = {
  door: '门口屏',
  paperless: '无纸化',
  central: '中控设备',
  client: '集控客户端',
}

/** 设备类型中文名 */
function deviceTypeLabel(type: string): string {
  return deviceTypeLabels[type] || type
}

const loading = ref(false)
const configs = ref<EnvConfig[]>([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const saving = ref(false)
const editId = ref('')
const formRef = ref()

/** 根据基础前缀生成默认多主题映射 */
function buildDefaultTopics(prefix?: string | null): Record<string, string> {
  const p = prefix || 'device'
  const result: Record<string, string> = {}
  for (const dt of deviceTypes) {
    result[dt] = `${p}/${dt}`
  }
  return result
}

const defaultForm = (): EnvConfigCreate => ({
  name: '',
  brokerHost: '',
  brokerPort: 1883,
  username: '',
  password: '',
  topicPrefix: 'device',
  topics: buildDefaultTopics('device'),
  useTls: false,
  clientIdPrefix: 'sim',
})

const form = reactive<EnvConfigCreate>(defaultForm())

// 主题编辑对象（保证非空，用于模板双向绑定）
const topicValues = reactive<Record<string, string>>(buildDefaultTopics('device'))

const rules = {
  name: [{ required: true, message: '请输入配置名称', trigger: 'blur' }],
  brokerHost: [{ required: true, message: '请输入 Broker 地址', trigger: 'blur' }],
  brokerPort: [{ required: true, message: '请输入端口号', trigger: 'blur' }],
  topicPrefix: [{ required: true, message: '请输入主题基础前缀', trigger: 'blur' }],
}

/** 基础前缀变更时，批量重置各设备主题（仅当用户未自定义时） */
function onBasePrefixChange() {
  const fresh = buildDefaultTopics(form.topicPrefix)
  Object.keys(topicValues).forEach((k) => delete topicValues[k])
  Object.assign(topicValues, fresh)
}

/** 规范化主题配置：兼容旧数据（topics 为空时从 topicPrefix 生成） */
function normalizeTopics(row: EnvConfig): Record<string, string> {
  if (row.topics && Object.keys(row.topics).length > 0) {
    return row.topics
  }
  return buildDefaultTopics(row.topicPrefix || 'device')
}

/** 是否已有多主题配置 */
function hasTopics(row: EnvConfig): boolean {
  return !!(row.topics && Object.keys(row.topics).length > 0)
}

/** 加载配置列表 */
async function loadConfigs() {
  loading.value = true
  try {
    const res = await listEnvConfigs({ limit: 100 })
    configs.value = res.items
  } catch (e: any) {
    ElMessage.error('加载环境配置失败: ' + (e.message || ''))
  } finally {
    loading.value = false
  }
}

/** 打开新增弹窗 */
function openCreateDialog() {
  isEdit.value = false
  editId.value = ''
  Object.assign(form, defaultForm())
  Object.keys(topicValues).forEach((k) => delete topicValues[k])
  Object.assign(topicValues, buildDefaultTopics('device'))
  dialogVisible.value = true
}

/** 打开编辑弹窗 */
function openEditDialog(row: EnvConfig) {
  isEdit.value = true
  editId.value = row.id
  const topics = normalizeTopics(row)
  Object.assign(form, {
    name: row.name,
    brokerHost: row.brokerHost,
    brokerPort: row.brokerPort,
    username: row.username,
    password: '',
    topicPrefix: row.topicPrefix,
    topics,
    useTls: row.useTls,
    clientIdPrefix: row.clientIdPrefix,
  })
  Object.keys(topicValues).forEach((k) => delete topicValues[k])
  Object.assign(topicValues, topics)
  dialogVisible.value = true
}

/** 保存配置 */
async function handleSave() {
  const valid = await formRef.value?.validate().catch(() => false)
  if (!valid) return

  // 将主题编辑对象回写到 form
  form.topics = { ...topicValues }

  saving.value = true
  try {
    if (isEdit.value) {
      await updateEnvConfig(editId.value, form)
      ElMessage.success('环境配置已更新')
    } else {
      await createEnvConfig(form)
      ElMessage.success('环境配置已创建')
    }
    dialogVisible.value = false
    await loadConfigs()
  } catch (e: any) {
    ElMessage.error('保存失败: ' + (e.message || ''))
  } finally {
    saving.value = false
  }
}

/** 删除配置 */
async function handleDelete(row: EnvConfig) {
  try {
    await deleteEnvConfig(row.id)
    ElMessage.success('环境配置已删除')
    await loadConfigs()
  } catch (e: any) {
    ElMessage.error('删除失败: ' + (e.message || ''))
  }
}

/** 测试连接 */
async function testConnection(row: EnvConfig) {
  try {
    const res = await testEnvConnection(row.id)
    if (res.success) {
      ElMessage.success(`连接成功 (${res.latencyMs}ms)`)
    } else {
      ElMessage.warning('连接失败: ' + res.message)
    }
  } catch (e: any) {
    ElMessage.error('测试连接失败: ' + (e.message || ''))
  }
}

/** 状态标签类型 */
function statusType(status: string) {
  const map: Record<string, string> = { connected: 'success', disconnected: 'info', error: 'danger' }
  return map[status] || 'info'
}

/** 状态标签文字 */
function statusLabel(status: string) {
  const map: Record<string, string> = { connected: '已连接', disconnected: '未连接', error: '连接失败' }
  return map[status] || status
}

/** 格式化时间 */
function formatTime(t: string) {
  return t?.replace('T', ' ').substring(0, 19) || '-'
}

onMounted(() => {
  loadConfigs()
})
</script>

<style scoped>
.env-config-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.page-header h2 {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.topic-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.topic-tag {
  margin: 0;
}

.topic-empty {
  color: #909399;
  font-size: 13px;
}

.topics-editor {
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 12px;
  background: #fafafa;
  border-radius: 6px;
  border: 1px solid #ebeef5;
}

.topic-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.topic-label {
  width: 80px;
  flex-shrink: 0;
  font-size: 13px;
  color: #606266;
}

.topic-input {
  flex: 1;
}

.topic-tip {
  margin-top: 4px;
  align-self: flex-start;
}
</style>
