<template>
  <el-radio-group :model-value="current" size="small" @change="onChange">
    <el-radio-button value="Platform">管理员</el-radio-button>
    <el-radio-button value="RCSMonitor">运营</el-radio-button>
  </el-radio-group>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import type { Scope } from '@/types/auth'

const auth = useAuthStore()
const router = useRouter()

// 单向受控 + 仅 @change 触发：避免「v-model set 与 @change 各触发一次」导致的
// 双重 switchScope 请求 / 双重导航竞态（旧实现会让一次点击发起两次切换，
// 偶发造成 scope 与 effectivePermissions 不一致 → 配置页 PermissionGuard 误判隐藏）。
const current = computed<Scope>(() => auth.scope ?? 'Platform')

let switching = false
async function onChange(v: string | number | boolean | undefined) {
  if (switching) return
  switching = true
  try {
    await switchAndNavigate(v as Scope)
  } finally {
    switching = false
  }
}

async function switchAndNavigate(scope: Scope) {
  try {
    await auth.switchScope(scope)
    router.push(scope === 'Platform' ? '/admin/map-monitor' : '/monitor/map')
  } catch (err) {
    ElMessage.error((err as Error)?.message ?? `切换到 ${scope} 失败`)
  }
}
</script>
