<!--
  组件名称：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-divider content-position="left">主题前缀配置</el-divider>
        <el-row :gutter="16">
          <el-col :span="12" v-for="dt in DEVICE_TYPES" :key="dt">
            <el-form-item :label="DEVICE_TYPE_LABELS[dt]">
              <el-input v-model="form.topics![dt]" :placeholder="`device/${dt}`" size="small" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-alert
          type="info"
          :closable="false"
          show-icon
          title="各设备类型使用独立的 MQTT 主题前缀，留空默认按 device/{设备类型} 生成"
          style="margin-bottom: 8px"
        />

        <!-- 默认主题参数配置 -->
        <el-divider content-position="left">默认主题参数</el-divider>
        <el-row :gutter="16">
          <el-col :span="6">
            <el-form-item label="公司编号">
              <el-input v-model="form.defaultTopicParams!.company_id" placeholder="如：001" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="会议室名称">
              <el-input v-model="form.defaultTopicParams!.conference_name" placeholder="如：测试会议室1" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="会议室ID">
              <el-input v-model="form.defaultTopicParams!.conference_id" placeholder="如：16" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="会议室编号">
              <div class="room-ids-inline">
                <template v-for="(_room, index) in form.defaultTopicParams!.room_ids" :key="index">
                  <el-input v-model="form.defaultTopicParams!.room_ids![index]" :placeholder="`C${index + 1}`" size="small" style="width: 100px" />
                  <el-button v-if="(form.defaultTopicParams!.room_ids?.length ?? 0) > 1" type="danger" link size="small" @click="removeRoomId(index)" :icon="Delete" />
                </template>
                <el-button size="small" @click="addRoomId" :icon="Plus" circle />
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">门口屏授权码配置</el-divider>
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="授权码前缀">
              <el-input v-model="form.defaultTopicParams!.app_token_prefix" placeholder="如：AND-518" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="起始编号">
              <el-input-number v-model="form.defaultTopicParams!.app_token_start" :min="1" :max="9999" style="width: 100%" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结束编号">
              <el-input-number v-model="form.defaultTopicParams!.app_token_end" :min="1" :max="9999" style="width: 100%" size="small" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">无纸化授权码配置</el-divider>
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="授权码前缀">
              <el-input v-model="form.defaultTopicParams!.paperless_token_prefix" placeholder="如：ANP-518" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="起始编号">
              <el-input-number v-model="form.defaultTopicParams!.paperless_token_start" :min="1" :max="9999" style="width: 100%" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结束编号">
              <el-input-number v-model="form.defaultTopicParams!.paperless_token_end" :min="1" :max="9999" style="width: 100%" size="small" />
            </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, Delete } from '@element-plus/icons-vue'
import {
  listEnvConfigs,
  createEnvConfig,
  updateEnvConfig,
  deleteEnvConfig,
  testEnvConnection,
} from '@/api/deviceSim'
import type { EnvConfig, EnvConfigCreate } from '@/types/device'
import { DEVICE_TYPE_LABELS } from '@/types/device'

/** 支持配置主题前缀的设备类型（按固定顺序展示） */
const DEVICE_TYPES = ['door', 'paperless', 'central', 'client'] as const

/** 由主题前缀自动生成默认多主题映射 */
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: {
    company_id: '',
    room_ids: [''],
    app_token_prefix: '',
    app_token_start: 1,
    app_token_end: 10,
    paperless_token_prefix: '',
    paperless_token_start: 1,
    paperless_token_end: 10,
    conference_id: '',
    conference_name: '',
  },
})

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 ? {
      company_id: row.defaultTopicParams.company_id || '',
      room_ids: row.defaultTopicParams.room_ids?.length ? [...row.defaultTopicParams.room_ids] : [''],
      app_token_prefix: row.defaultTopicParams.app_token_prefix || '',
      app_token_start: row.defaultTopicParams.app_token_start ?? 1,
      app_token_end: row.defaultTopicParams.app_token_end ?? 10,
      paperless_token_prefix: row.defaultTopicParams.paperless_token_prefix || '',
      paperless_token_start: row.defaultTopicParams.paperless_token_start ?? 1,
      paperless_token_end: row.defaultTopicParams.paperless_token_end ?? 10,
      conference_id: row.defaultTopicParams.conference_id || '',
      conference_name: row.defaultTopicParams.conference_name || '',
    } : {
      company_id: '',
      room_ids: [''],
      app_token_prefix: '',
      app_token_start: 1,
      app_token_end: 10,
      paperless_token_prefix: '',
      paperless_token_start: 1,
      paperless_token_end: 10,
      conference_id: '',
      conference_name: '',
    },
  })
  dialogVisible.value = true
}

/** 添加会议室编号 */
function addRoomId() {
  if (!form.defaultTopicParams!.room_ids) {
    form.defaultTopicParams!.room_ids = ['']
  }
  form.defaultTopicParams!.room_ids.push('')
}

/** 删除会议室编号 */
function removeRoomId(index: number) {
  form.defaultTopicParams!.room_ids?.splice(index, 1)
}

/** 保存配置 */
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;
}

.room-ids-inline {
  display: flex;
  align-items: center;
  gap: 6px;
  flex-wrap: wrap;
}
</style>