<!--
  组件名称：DeviceList.vue
  组件描述：模拟设备列表公共组件，支持启停、手动上报、状态展示

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

<template>
  <div class="device-list">
    <!-- 筛选栏 -->
    <div class="filter-bar">
      <el-select v-model="filterEnvConfigId" placeholder="选择环境" clearable style="width: 200px" @change="loadDevices">
        <el-option v-for="env in envConfigs" :key="env.id" :label="env.name" :value="env.id" />
      </el-select>
      <el-select v-model="filterStatus" placeholder="状态" clearable style="width: 120px" @change="loadDevices">
        <el-option label="运行中" value="running" />
        <el-option label="已停止" value="stopped" />
        <el-option label="异常" value="error" />
      </el-select>
      <div style="flex: 1" />
      <el-button type="primary" @click="openCreateDialog">
        <el-icon><Plus /></el-icon>新增设备
      </el-button>
    </div>

    <!-- 设备列表 -->
    <el-table :data="devices" v-loading="loading" stripe style="width: 100%">
      <el-table-column prop="deviceName" label="设备名称" min-width="140" />
      <el-table-column prop="deviceId" label="设备 ID" min-width="160" />
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 'running' ? 'success' : row.status === 'error' ? 'danger' : 'info'" size="small">
            {{ row.status === 'running' ? '运行中' : row.status === 'error' ? '异常' : '已停止' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="totalReports" label="上报次数" width="90" align="center" />
      <el-table-column label="最后上报" width="170">
        <template #default="{ row }">
          {{ row.lastReportedAt ? formatTime(row.lastReportedAt) : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" fixed="right">
        <template #default="{ row }">
          <el-button
            :type="row.status === 'running' ? 'warning' : 'success'"
            size="small"
            :loading="operatingId === row.id"
            @click="toggleDevice(row)"
          >
            {{ row.status === 'running' ? '停止' : '启动' }}
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            :disabled="row.status !== 'running'"
            @click="openManualReport(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>

    <!-- 分页 -->
    <div class="pagination-wrapper" v-if="total > limit">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="limit"
        :total="total"
        layout="prev, pager, next, total"
        @change="loadDevices"
      />
    </div>

    <!-- 新增设备弹窗 -->
    <el-dialog v-model="createDialogVisible" title="新增模拟设备" width="500px">
      <el-form ref="createFormRef" :model="createForm" :rules="createRules" label-width="100px" label-position="top">
        <el-form-item label="关联环境" prop="envConfigId">
          <el-select v-model="createForm.envConfigId" placeholder="选择环境配置" style="width: 100%">
            <el-option v-for="env in envConfigs" :key="env.id" :label="env.name" :value="env.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="createForm.deviceName" :placeholder="`如：${deviceTypeLabel}设备1`" />
        </el-form-item>
        <el-form-item label="设备 ID" prop="deviceId">
          <el-input v-model="createForm.deviceId" :placeholder="`如：${deviceType}_001`" />
        </el-form-item>
        <el-form-item label="自动重连">
          <el-switch v-model="createForm.autoReconnect" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="creating" @click="handleCreate">创建</el-button>
      </template>
    </el-dialog>

    <!-- 手动上报弹窗 -->
    <el-dialog v-model="reportDialogVisible" title="手动上报" width="500px">
      <el-form ref="reportFormRef" :model="reportForm" label-width="100px" label-position="top">
        <el-form-item label="上报主题" prop="topic">
          <el-input v-model="reportForm.topic" placeholder="如：event、status、heartbeat" />
        </el-form-item>
        <el-form-item label="上报内容" prop="payload">
          <el-input
            v-model="reportForm.payloadStr"
            type="textarea"
            :rows="6"
            placeholder='如：{"status": "online", "battery": 85}'
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="reportDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="reporting" @click="handleManualReport">发送</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  listSimulators,
  createSimulator,
  deleteSimulator,
  startSimulator,
  stopSimulator,
  manualReport,
  listEnvConfigs,
} from '@/api/deviceSim'
import type { Simulator, SimulatorCreate, EnvConfig, DeviceType } from '@/types/device'
import { DEVICE_TYPE_LABELS } from '@/types/device'

const props = defineProps<{
  deviceType: DeviceType
}>()

const emit = defineEmits<{
  (e: 'device-changed'): void
}>()

const deviceTypeLabel = computed(() => DEVICE_TYPE_LABELS[props.deviceType])

// 设备列表
const loading = ref(false)
const devices = ref<Simulator[]>([])
const total = ref(0)
const currentPage = ref(1)
const limit = 20
const operatingId = ref('')

// 筛选
const envConfigs = ref<EnvConfig[]>([])
const filterEnvConfigId = ref('')
const filterStatus = ref('')

// 新增弹窗
const createDialogVisible = ref(false)
const creating = ref(false)
const createFormRef = ref()
const createForm = ref<SimulatorCreate>({
  envConfigId: '',
  deviceType: props.deviceType,
  deviceName: '',
  deviceId: '',
  autoReconnect: true,
})
const createRules = {
  envConfigId: [{ required: true, message: '请选择环境配置', trigger: 'change' }],
  deviceName: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
  deviceId: [{ required: true, message: '请输入设备 ID', trigger: 'blur' }],
}

// 手动上报弹窗
const reportDialogVisible = ref(false)
const reporting = ref(false)
const reportFormRef = ref()
const reportForm = ref({ topic: '', payloadStr: '{}', deviceId: '' })

/** 加载设备列表 */
async function loadDevices() {
  loading.value = true
  try {
    const params: any = {
      skip: (currentPage.value - 1) * limit,
      limit,
      deviceType: props.deviceType,
    }
    if (filterEnvConfigId.value) params.envConfigId = filterEnvConfigId.value
    if (filterStatus.value) params.status = filterStatus.value

    const res = await listSimulators(params)
    devices.value = res.items
    total.value = res.total
  } catch (e: any) {
    ElMessage.error('加载设备列表失败: ' + (e.message || ''))
  } finally {
    loading.value = false
  }
}

/** 加载环境配置列表 */
async function loadEnvConfigs() {
  try {
    const res = await listEnvConfigs({ limit: 100 })
    envConfigs.value = res.items
  } catch (_) { /* ignore */ }
}

/** 打开新增弹窗 */
function openCreateDialog() {
  createForm.value = {
    envConfigId: filterEnvConfigId.value || '',
    deviceType: props.deviceType,
    deviceName: '',
    deviceId: '',
    autoReconnect: true,
  }
  createDialogVisible.value = true
}

/** 创建设备 */
async function handleCreate() {
  const valid = await createFormRef.value?.validate().catch(() => false)
  if (!valid) return

  creating.value = true
  try {
    await createSimulator(createForm.value)
    ElMessage.success('模拟设备已创建')
    createDialogVisible.value = false
    await loadDevices()
    emit('device-changed')
  } catch (e: any) {
    ElMessage.error('创建失败: ' + (e.message || ''))
  } finally {
    creating.value = false
  }
}

/** 切换设备启停 */
async function toggleDevice(row: Simulator) {
  operatingId.value = row.id
  try {
    if (row.status === 'running') {
      await stopSimulator(row.id)
      ElMessage.success('设备已停止')
    } else {
      await startSimulator(row.id)
      ElMessage.success('设备已启动')
    }
    await loadDevices()
    emit('device-changed')
  } catch (e: any) {
    ElMessage.error('操作失败: ' + (e.message || ''))
  } finally {
    operatingId.value = ''
  }
}

/** 删除设备 */
async function handleDelete(row: Simulator) {
  try {
    await deleteSimulator(row.id)
    ElMessage.success('设备已删除')
    await loadDevices()
    emit('device-changed')
  } catch (e: any) {
    ElMessage.error('删除失败: ' + (e.message || ''))
  }
}

/** 打开手动上报弹窗 */
function openManualReport(row: Simulator) {
  reportForm.value = { topic: 'status', payloadStr: '{}', deviceId: row.id }
  reportDialogVisible.value = true
}

/** 手动上报 */
async function handleManualReport() {
  let payload: any = {}
  try {
    payload = JSON.parse(reportForm.value.payloadStr)
  } catch (_) {
    ElMessage.warning('JSON 格式错误')
    return
  }

  reporting.value = true
  try {
    await manualReport(reportForm.value.deviceId, {
      topic: reportForm.value.topic,
      payload,
    })
    ElMessage.success('上报成功')
    reportDialogVisible.value = false
    await loadDevices()
  } catch (e: any) {
    ElMessage.error('上报失败: ' + (e.message || ''))
  } finally {
    reporting.value = false
  }
}

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

onMounted(() => {
  loadEnvConfigs()
  loadDevices()
})
</script>

<style scoped>
.device-list {
  width: 100%;
}

.filter-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}
</style>