<template>
  <div>
    <!-- 顶部操作栏 -->
    <div class="mb-16" style="display:flex;justify-content:space-between;align-items:center">
      <div style="display:flex;align-items:center;gap:8px">
        <span
          :style="{
            display: 'inline-block', width: '10px', height: '10px', borderRadius: '50%',
            backgroundColor: connected ? '#67c23a' : '#f56c6c'
          }"
        ></span>
        <span style="font-size:14px;color:#606266">{{ connected ? '模拟器已连接' : '模拟器未连接' }}</span>
        <el-button size="small" :icon="Refresh" circle @click="loadAll" />
      </div>
      <div>
        <el-button type="success" :disabled="!connected" @click="handleStartAll">全部启动</el-button>
        <el-button type="danger" :disabled="!connected" @click="handleStopAll">全部停止</el-button>
        <el-button :disabled="!connected" @click="handleReload">刷新配置</el-button>
      </div>
    </div>

    <!-- 未连接提示 -->
    <el-empty v-if="!connected" description="模拟器未启动，请在服务器上运行 CncSimulator.exe" />

    <!-- 地址列表 -->
    <el-table
      v-else
      :data="addresses"
      border
      stripe
      v-loading="loading"
      style="width:100%"
    >
      <el-table-column prop="name" label="名称" min-width="140">
        <template #default="{ row }">
          <el-link
            v-if="row.isRunning && row.runningPort > 0"
            type="primary"
            @click="goDetail(row.runningPort)"
          >{{ row.name }}</el-link>
          <span v-else>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="url" label="URL" min-width="200" show-overflow-tooltip />
      <el-table-column prop="machineCount" label="机床数" align="center" width="80" />
      <el-table-column label="状态" align="center" width="100">
        <template #default="{ row }">
          <el-tag :type="row.isRunning ? 'success' : 'info'" size="small">
            {{ row.isRunning ? '运行中' : '未启动' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="端口" align="center" width="80">
        <template #default="{ row }">{{ row.isRunning ? row.runningPort : '-' }}</template>
      </el-table-column>
      <el-table-column label="操作" width="160" align="center">
        <template #default="{ row }">
          <div style="white-space:nowrap">
            <el-button
              v-if="row.isRunning"
              link type="primary"
              @click="goDetail(row.runningPort)"
            >详情</el-button>
            <el-button
              v-if="!row.isRunning"
              link type="success"
              @click="handleStart(row)"
            >启动</el-button>
            <el-popconfirm
              v-if="row.isRunning"
              title="确定停止该地址的模拟？"
              @confirm="handleStop(row)"
            >
              <template #reference>
                <el-button link type="danger">停止</el-button>
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 启动弹窗：选择机床 -->
    <el-dialog v-model="startDialogVisible" title="选择模拟机床" width="500px" destroy-on-close>
      <el-checkbox-group v-model="selectedDevices">
        <el-checkbox
          v-for="m in startTarget?.machines ?? []"
          :key="m.deviceCode"
          :label="m.deviceCode"
          :value="m.deviceCode"
        >{{ m.name }} ({{ m.deviceCode }})</el-checkbox>
      </el-checkbox-group>
      <p style="margin-top:12px;color:#909399;font-size:13px">
        不选择则模拟该地址下全部机床（{{ startTarget?.machineCount }} 台）
      </p>
      <template #footer>
        <el-button @click="startDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="startLoading" @click="confirmStart">确认启动</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { pingSimulator, fetchSimulatorAddresses, startSimulator, stopSimulator, startAllSimulators, stopAllSimulators, reloadSimulator } from '@/api/simulator'
import type { SimulatorAddress } from '@/api/simulator'
import { useMockMode } from '@/composables/useMockMode'

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

const loading = ref(false)
const connected = ref(false)
const addresses = ref<SimulatorAddress[]>([])

// 启动弹窗
const startDialogVisible = ref(false)
const startLoading = ref(false)
const startTarget = ref<SimulatorAddress | null>(null)
const selectedDevices = ref<string[]>([])

// 轮询定时器
let pollTimer: ReturnType<typeof setInterval> | null = null

/** 检测连接状态并加载数据 */
async function loadAll() {
  loading.value = true
  try {
    const pingRes = await pingSimulator()
    connected.value = pingRes.data?.running ?? false
    if (connected.value) {
      const addrRes = await fetchSimulatorAddresses()
      addresses.value = addrRes.data ?? []
    } else {
      addresses.value = []
    }
  } catch {
    connected.value = false
    addresses.value = []
  } finally {
    loading.value = false
  }
}

/** 跳转到详情页 */
function goDetail(port: number) {
  const base = isMock.value ? '/mock' : ''
  router.push(`${base}/simulator/${port}`)
}

/** 打开启动弹窗 */
function handleStart(row: SimulatorAddress) {
  startTarget.value = row
  selectedDevices.value = []
  startDialogVisible.value = true
}

/** 确认启动 */
async function confirmStart() {
  if (!startTarget.value) return
  startLoading.value = true
  try {
    const payload: { dbAddressId: number; deviceCodes?: string[] } = {
      dbAddressId: startTarget.value.dbId
    }
    if (selectedDevices.value.length > 0) {
      payload.deviceCodes = selectedDevices.value
    }
    await startSimulator(payload)
    ElMessage.success('启动成功')
    startDialogVisible.value = false
    await loadAll()
  } catch (e: any) {
    ElMessage.error(e?.message ?? '启动失败')
  } finally {
    startLoading.value = false
  }
}

/** 停止 */
async function handleStop(row: SimulatorAddress) {
  try {
    await stopSimulator({ dbAddressId: row.dbId })
    ElMessage.success('已停止')
    await loadAll()
  } catch (e: any) {
    ElMessage.error(e?.message ?? '停止失败')
  }
}

/** 全部启动 */
async function handleStartAll() {
  try {
    await startAllSimulators()
    ElMessage.success('全部启动成功')
    await loadAll()
  } catch (e: any) {
    ElMessage.error(e?.message ?? '操作失败')
  }
}

/** 全部停止 */
async function handleStopAll() {
  try {
    await stopAllSimulators()
    ElMessage.success('全部停止')
    await loadAll()
  } catch (e: any) {
    ElMessage.error(e?.message ?? '操作失败')
  }
}

/** 刷新配置 */
async function handleReload() {
  try {
    await reloadSimulator()
    ElMessage.success('配置已刷新')
    await loadAll()
  } catch (e: any) {
    ElMessage.error(e?.message ?? '刷新失败')
  }
}

// 页面可见性控制轮询
function startPolling() {
  stopPolling()
  pollTimer = setInterval(() => {
    if (document.visibilityState === 'visible') {
      loadAll()
    }
  }, 5000)
}

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

onMounted(() => {
  loadAll()
  startPolling()
})

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