<template>
  <div>
    <!-- 顶部栏 -->
    <div class="mb-16" style="display:flex;justify-content:space-between;align-items:center">
      <div style="display:flex;align-items:center;gap:12px">
        <el-button :icon="ArrowLeft" @click="goBack">返回</el-button>
        <span style="font-size:16px;font-weight:600">{{ status?.name ?? '加载中...' }}</span>
        <el-tag v-if="status" :type="status.isRunning ? 'success' : 'danger'" size="small">
          {{ status.isRunning ? '运行中' : '已停止' }}
        </el-tag>
      </div>
      <div>
        <el-button
          v-if="status && !status.isRunning"
          type="success"
          @click="handleStartStop('start')"
        >启动</el-button>
        <el-popconfirm
          v-if="status && status.isRunning"
          title="确定停止数据模拟？"
          @confirm="handleStartStop('stop')"
        >
          <template #reference>
            <el-button type="danger">停止</el-button>
          </template>
        </el-popconfirm>
        <el-button :icon="Refresh" circle @click="loadStatus" style="margin-left:8px" />
      </div>
    </div>

    <div v-if="!status" v-loading="true" style="height:200px"></div>

    <template v-else>
      <!-- 统计卡片 -->
      <el-row :gutter="16" class="mb-16">
        <el-col :span="6">
          <el-card shadow="hover" body-style="padding:16px">
            <div style="color:#909399;font-size:13px;margin-bottom:4px">设备总数</div>
            <div style="font-size:24px;font-weight:700;color:#303133">{{ status.totalDevices }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" body-style="padding:16px">
            <div style="color:#909399;font-size:13px;margin-bottom:4px">在线设备</div>
            <div style="font-size:24px;font-weight:700;color:#67c23a">{{ status.onlineDevices }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" body-style="padding:16px">
            <div style="color:#909399;font-size:13px;margin-bottom:4px">总零件数</div>
            <div style="font-size:24px;font-weight:700;color:#409eff">{{ stats?.totalParts ?? '-' }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" body-style="padding:16px">
            <div style="color:#909399;font-size:13px;margin-bottom:4px">请求次数</div>
            <div style="font-size:24px;font-weight:700;color:#e6a23c">{{ status.requestCount }}</div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 设备状态表格 -->
      <div class="mb-16">
        <h3 style="margin:0 0 12px;font-size:15px">设备状态</h3>
        <el-table :data="status.devices" border stripe style="width:100%" max-height="400">
          <el-table-column prop="deviceCode" label="编码" width="130" />
          <el-table-column prop="desc" label="描述" min-width="100" />
          <el-table-column prop="scenario" label="场景" width="90" align="center" />
          <el-table-column prop="programName" label="程序" width="90" align="center" />
          <el-table-column prop="partCount" label="零件" width="70" align="center" />
          <el-table-column label="状态" width="70" align="center">
            <template #default="{ row }">
              <el-tag :type="row.isOnline ? 'success' : 'danger'" size="small">
                {{ row.isOnline ? '在线' : '离线' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template #default="{ row }">
              <el-button link size="small" @click="handleEvent(row.deviceCode, 'change_program')">换程序</el-button>
              <el-button link size="small" @click="handleEvent(row.deviceCode, 'reset_parts')">清零</el-button>
              <el-button link size="small" @click="handleEvent(row.deviceCode, 'pause')">暂停</el-button>
              <el-button link size="small" @click="handleEvent(row.deviceCode, 'resume')">恢复</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 设置面板 -->
      <el-collapse class="mb-16">
        <el-collapse-item title="模拟设置" name="settings">
          <el-row :gutter="24">
            <el-col :span="8">
              <div style="margin-bottom:8px;font-size:13px;color:#606266">数据频率（秒）</div>
              <el-slider v-model="intervalValue" :min="1" :max="60" show-input @change="handleIntervalChange" />
            </el-col>
            <el-col :span="8">
              <div style="margin-bottom:8px;font-size:13px;color:#606266">场景模式</div>
              <el-radio-group :model-value="status.scenarioMode" @change="handleModeChange">
                <el-radio-button value="auto">自动</el-radio-button>
                <el-radio-button value="manual">手动</el-radio-button>
              </el-radio-group>
            </el-col>
            <el-col :span="8">
              <div style="margin-bottom:8px;font-size:13px;color:#606266">网络模拟</div>
              <el-select :model-value="status.networkError" @change="handleNetworkChange" style="width:100%">
                <el-option label="正常" value="normal" />
                <el-option label="HTTP 500" value="http500" />
                <el-option label="超时" value="timeout" />
                <el-option label="空数据" value="empty" />
                <el-option label="畸形JSON" value="malformed" />
                <el-option label="拒绝连接" value="refuse" />
              </el-select>
            </el-col>
          </el-row>
        </el-collapse-item>
      </el-collapse>

      <!-- 请求日志 -->
      <div>
        <h3 style="margin:0 0 12px;font-size:15px">最近请求日志</h3>
        <el-table :data="logs" border stripe style="width:100%" max-height="300">
          <el-table-column prop="index" label="#" width="50" align="center" />
          <el-table-column prop="timestamp" label="时间" width="100" />
          <el-table-column prop="deviceCount" label="设备数" width="70" align="center" />
          <el-table-column prop="keyData" label="关键数据" min-width="200" show-overflow-tooltip />
          <el-table-column prop="duration" label="耗时(ms)" width="80" align="center" />
          <el-table-column type="expand">
            <template #default="{ row }">
              <pre style="padding:12px;font-size:12px;max-height:300px;overflow:auto;white-space:pre-wrap">{{ row.fullJson }}</pre>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Refresh } from '@element-plus/icons-vue'
import {
  fetchAddressStatus, startAddressSimulation, stopAddressSimulation,
  triggerDeviceEvent, setAddressInterval, setNetworkError, setScenarioMode,
  fetchAddressLogs, fetchAddressStats
} from '@/api/simulator'
import type { AddressStatus, AddressStats, SimulatorLog } from '@/api/simulator'
import { useMockMode } from '@/composables/useMockMode'

const route = useRoute()
const router = useRouter()
const { isMock } = useMockMode()

const port = Number(route.params.port)
const status = ref<AddressStatus | null>(null)
const stats = ref<AddressStats | null>(null)
const logs = ref<SimulatorLog[]>([])
const intervalValue = ref(10)
let pollTimer: ReturnType<typeof setInterval> | null = null

/** 加载地址状态 */
async function loadStatus() {
  try {
    const res = await fetchAddressStatus(port)
    status.value = res.data ?? null
    if (status.value) {
      intervalValue.value = status.value.dataChangeInterval
    }
  } catch {
    ElMessage.error('获取地址状态失败')
  }
}

/** 加载统计 */
async function loadStats() {
  try {
    const res = await fetchAddressStats(port)
    stats.value = res.data ?? null
  } catch { /* 静默 */ }
}

/** 加载日志 */
async function loadLogs() {
  try {
    const res = await fetchAddressLogs(port)
    logs.value = res.data ?? []
  } catch { /* 静默 */ }
}

/** 返回总览 */
function goBack() {
  const base = isMock.value ? '/mock' : ''
  router.push(`${base}/simulator`)
}

/** 启动/停止 */
async function handleStartStop(action: string) {
  try {
    if (action === 'start') {
      await startAddressSimulation(port)
      ElMessage.success('已启动')
    } else {
      await stopAddressSimulation(port)
      ElMessage.success('已停止')
    }
    await loadStatus()
  } catch (e: any) {
    ElMessage.error(e?.message ?? '操作失败')
  }
}

/** 触发事件 */
async function handleEvent(deviceId: string, eventType: string) {
  try {
    await triggerDeviceEvent(port, { deviceId, eventType })
    ElMessage.success('事件已触发')
    await loadStatus()
  } catch (e: any) {
    ElMessage.error(e?.message ?? '触发失败')
  }
}

/** 修改频率 */
async function handleIntervalChange(val: number) {
  try {
    await setAddressInterval(port, { value: val })
    ElMessage.success('频率已修改')
  } catch (e: any) {
    ElMessage.error(e?.message ?? '修改失败')
  }
}

/** 修改模式 */
async function handleModeChange(mode: string) {
  try {
    await setScenarioMode(port, { mode })
    ElMessage.success('模式已切换')
    await loadStatus()
  } catch (e: any) {
    ElMessage.error(e?.message ?? '切换失败')
  }
}

/** 修改网络模拟 */
async function handleNetworkChange(type: string) {
  try {
    await setNetworkError(port, { type })
    ElMessage.success('网络模拟已设置')
    await loadStatus()
  } catch (e: any) {
    ElMessage.error(e?.message ?? '设置失败')
  }
}

function startPolling() {
  stopPolling()
  pollTimer = setInterval(() => {
    if (document.visibilityState === 'visible') {
      loadStatus()
      loadStats()
    }
  }, 5000)
}

function stopPolling() {
  if (pollTimer) {
    clearInterval(pollTimer)
    pollTimer = null
  }
}

onMounted(async () => {
  await loadStatus()
  await loadStats()
  await loadLogs()
  startPolling()
})

onUnmounted(() => {
  stopPolling()
})
</script>
