<!--
  组件名称：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="最后连接" 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="750px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" label-position="top">
        <el-form-item label="配置名称" prop="name">
          <el-input v-model="form.name" placeholder="如：测试环境" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="14">
            <el-form-item label="Broker 地址" prop="brokerHost">
              <el-input v-model="form.brokerHost" placeholder="如：192.168.5.44" />
            </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-row :gutter="20">
          <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'

/** 由主题前缀自动生成默认多主题映射 */
function defaultTopics(): Record<string, string> {
  return {
    door: 'device/door',
    paperless: 'device/paperless',
    central: 'device/central',
    client: 'device/client',
  }
}

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()

const defaultForm = (): EnvConfigCreate => ({
  name: '',
  brokerHost: '',
  brokerPort: 1883,
  username: 'mqtt@cmdb',
  password: 'mqtt@webpassw0RD',
  useTls: false,
  clientIdPrefix: 'sim',
  topics: defaultTopics(),
  defaultTopicParams: {},
})

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

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

/** 加载配置列表 */
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())
  dialogVisible.value = true
}

/** 打开编辑弹窗 */
function openEditDialog(row: EnvConfig) {
  isEdit.value = true
  editId.value = row.id
  Object.assign(form, {
    name: row.name,
    brokerHost: row.brokerHost,
    brokerPort: row.brokerPort,
    username: row.username,
    password: '',
    useTls: row.useTls,
    clientIdPrefix: row.clientIdPrefix,
    topics: row.topics ? { ...row.topics } : defaultTopics(),
    defaultTopicParams: row.defaultTopicParams ? { ...row.defaultTopicParams } : {},
  })
  dialogVisible.value = true
}

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

  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;
}
</style>