<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const auth = useAuthStore()
const loading = ref(true)

onMounted(async () => {
  const code = route.query.code as string
  const state = route.query.state as string // This is wecom_userid

  if (!code) {
    ElMessage.error('缺少授权参数')
    router.push('/login')
    return
  }

  try {
    await auth.bindWecom(code, state || '')
    ElMessage.success('企微绑定成功')
    router.push(auth.isManager ? '/m' : '/')
  } catch (e: any) {
    ElMessage.error('绑定失败: ' + (e.response?.data?.detail || e.message))
    router.push('/login')
  } finally {
    loading.value = false
  }
})
</script>

<template>
  <div class="bind-page">
    <el-card v-loading="loading">
      <template #header>正在完成企微账号绑定...</template>
      <p v-if="loading">请稍候，正在验证您的身份。</p>
    </el-card>
  </div>
</template>

<style scoped>
.bind-page {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: #f5f7fa;
}
</style>
