<!-- =============================================================================
// 企微IT智能服务台 — 应急页身份检测 dispatcher (v0.5.4)
// =============================================================================
// 说明：BC/DR 应急场景的统一入口
// 流程：
//   1. 加载企微 JS-SDK
//   2. 调后端 /api/wecom/jsapi-config 拿签名
//   3. wx.config() + wx.agentConfig() 鉴权
//   4. 拿当前 userid
//   5. 调 /api/wecom/check-role 判断角色
//   6. 坐席 → /itagent/agent-preview,员工 → /h5-preview
// 错误兜底:默认按"员工"处理,跳转 /h5-preview
// ============================================================================= -->

<template>
  <div class="emergency-dispatcher">
    <div class="emergency-dispatcher__panel">
      <div class="logo"></div>
      <h2 class="title">IT 智能服务台</h2>
      <p class="subtitle">{{ statusText }}</p>
      <van-loading v-if="loading" type="spinner" color="#1989fa" size="32" />
      <div v-if="errorMsg" class="error-msg">{{ errorMsg }}</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { showLoadingToast, showFailToast } from 'vant'
import axios from 'axios'

const router = useRouter()

const loading = ref(true)
const errorMsg = ref('')
const statusText = ref('正在检测身份...')

const isMobile = computed(() => window.innerWidth < 500)

/**
 * 加载企微 JS-SDK
 * 注意:企微 JS-SDK 文件名是 jweixin-1.2.0.js(历史遗留,虽然叫 jweixin)
 */
function loadWeworkSDK(): Promise<void> {
  return new Promise((resolve, reject) => {
    // 已经加载过
    if (typeof (window as any).wx !== 'undefined' && (window as any).wx.agentConfig) {
      resolve()
      return
    }
    const script = document.createElement('script')
    script.src = 'https://res.wx.qq.com/wwopen/js/wwLogin-1.2.7.js'
    script.onload = () => {
      // 加载企微 agent SDK
      const agentScript = document.createElement('script')
      agentScript.src = 'https://res.wx.qq.com/open/js/jweixin-1.2.0.js'
      agentScript.onload = () => resolve()
      agentScript.onerror = () => reject(new Error('加载企微 agent SDK 失败'))
      document.head.appendChild(agentScript)
    }
    script.onerror = () => reject(new Error('加载企微 JS-SDK 失败'))
    document.head.appendChild(script)
  })
}

/**
 * 拿后端签名
 */
async function getJsapiConfig(url: string) {
  const resp = await axios.get('/api/wecom/jsapi-config', { params: { url } })
  if (resp.data.code !== 0) {
    throw new Error(`拿签名失败: ${resp.data.message}`)
  }
  return resp.data.data
}

/**
 * wx.config 初始化
 */
function wxConfig(config: any): Promise<void> {
  return new Promise((resolve, reject) => {
    const wx = (window as any).wx
    wx.config({
      beta: true, // 开启内测接口
      debug: false,
      appId: config.corp_id,
      timestamp: config.timestamp,
      nonceStr: config.nonce_str,
      signature: config.signature,
      jsApiList: ['agentConfig'],
    })
    wx.ready(() => resolve())
    wx.error((err: any) => reject(new Error(`wx.config 失败: ${JSON.stringify(err)}`)))
  })
}

/**
 * wx.agentConfig 拿身份
 */
function wxAgentConfig(config: any): Promise<{ userId: string }> {
  return new Promise((resolve, reject) => {
    const wx = (window as any).wx
    wx.agentConfig({
      corpid: config.corp_id,
      agentid: config.agent_id,
      timestamp: config.timestamp,
      nonceStr: config.nonce_str,
      signature: config.signature,
      jsApiList: ['selectExternalContact'],
      success: (res: any) => {
        // 拿当前 userid(实际场景可能要从 selectExternalContact 等接口拿)
        // 这里我们直接通过 URL 参数或后端回查
        // 简化版:从后端 cookie / 之前登录态拿
        const userId = (window as any).wecom_userid || ''
        resolve({ userId })
      },
      fail: (err: any) => reject(new Error(`wx.agentConfig 失败: ${JSON.stringify(err)}`)),
    })
  })
}

/**
 * 调后端检查角色
 */
async function checkRole(userid: string) {
  const resp = await axios.get('/api/wecom/check-role', { params: { userid } })
  if (resp.data.code !== 0) {
    throw new Error(`检查角色失败: ${resp.data.message}`)
  }
  return resp.data.data
}

onMounted(async () => {
  try {
    statusText.value = '正在加载企微 SDK...'
    await loadWeworkSDK()

    statusText.value = '正在获取鉴权签名...'
    const currentUrl = window.location.href.split('#')[0]
    const config = await getJsapiConfig(currentUrl)

    statusText.value = '正在初始化企微...'
    await wxConfig(config)

    statusText.value = '正在获取身份...'
    const { userId } = await wxAgentConfig(config)

    if (!userId) {
      throw new Error('未能获取当前用户 userid')
    }

    statusText.value = '正在检查角色...'
    const roleInfo = await checkRole(userId)
    console.log('[EmergencyDispatcher] 角色检测:', roleInfo)

    // 跳转
    statusText.value = `角色: ${roleInfo.role},正在跳转...`
    if (roleInfo.role === 'agent') {
      window.location.href = '/itagent/agent-preview?userid=' + encodeURIComponent(userId)
    } else {
      router.push({ path: '/h5-preview', query: { userid: userId } })
    }
  } catch (err: any) {
    console.error('[EmergencyDispatcher] 错误:', err)
    errorMsg.value = err.message || '未知错误'
    loading.value = false
    showFailToast({ message: errorMsg.value, duration: 5000 })

    // 兜底:3 秒后跳员工页
    setTimeout(() => {
      router.push({ path: '/h5-preview' })
    }, 3000)
  }
})
</script>

<style scoped>
.emergency-dispatcher {
  position: fixed;
  inset: 0;
  background: linear-gradient(135deg, #f7f8fa 0%, #e7e9ed 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: -apple-system, BlinkMacSystemFont, 'PingFang SC', sans-serif;
}

.emergency-dispatcher__panel {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 48px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
  max-width: 400px;
  width: 90%;
}

.logo {
  width: 64px;
  height: 64px;
  border-radius: 16px;
  background: linear-gradient(135deg, #1989fa 0%, #1c64f2 100%);
  margin-bottom: 24px;
  box-shadow: 0 8px 24px rgba(25, 137, 250, 0.3);
}

.title {
  font-size: 20px;
  font-weight: 600;
  color: #323233;
  margin: 0 0 12px;
}

.subtitle {
  font-size: 14px;
  color: #646566;
  margin: 0 0 24px;
  text-align: center;
}

.error-msg {
  margin-top: 16px;
  padding: 12px;
  background: #fff7e8;
  color: #ff976a;
  font-size: 13px;
  border-radius: 8px;
  text-align: center;
  word-break: break-all;
}
</style>
