<template>
  <div class="wx-callback">
    <el-card class="callback-card">
      <template #header>
        <div class="card-header">
          <el-icon><Loading /></el-icon>
          <span>正在处理微信登录...</span>
        </div>
      </template>
      
      <div v-if="loading" class="loading-content">
        <el-icon class="loading-icon"><Loading /></el-icon>
        <p>请稍候，正在获取授权信息</p>
      </div>
      
      <el-alert
        v-else-if="errorMsg"
        :title="errorMsg"
        type="error"
        show-icon
        :closable="false"
      />
      
      <el-alert
        v-else
        title="授权成功，正在跳转"
        type="success"
        show-icon
        :closable="false"
      />
    </el-card>

    <!-- 绑定账户弹窗 -->
    <el-dialog
      v-model="showBind"
      title="完善信息并绑定账户"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <el-form 
        ref="bindFormRef"
        :model="bindForm" 
        :rules="bindFormRules"
        label-width="80px" 
        label-position="left"
      >
        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="bindForm.name"
            placeholder="请输入姓名"
            clearable
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="手机号" prop="mobile">
          <el-input
            v-model="bindForm.mobile"
            placeholder="请输入手机号"
            clearable
            maxlength="11"
          />
        </el-form-item>
        
        <el-form-item label="编号" prop="sn">
          <el-input
            v-model="bindForm.sn"
            placeholder="请输入编号"
            clearable
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="bindForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
            clearable
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="onCancelBind">取消</el-button>
          <el-button type="primary" @click="onBind" :loading="bindLoading">
            确认绑定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getWechatUserInfo, bindWechatAccount } from '../api'
import { saveLoginData } from '../utils/auth'

const router = useRouter()
const route = useRoute()
const loading = ref(true)
const errorMsg = ref('')
const showBind = ref(false)
const bindLoading = ref(false)
const bindForm = ref({ name: '', mobile: '', sn: '', password: '' })
const bindFormRef = ref()
let cachedState = ''
const userInfo = ref({})

// 表单校验规则
const bindFormRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  sn: [
    { required: true, message: '请输入编号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

function parseQuery(){
  // 优先从路由 query 获取
  const { code, state } = route.query || {}
  if (code && state) return { code, state }
  // 兜底从 location 解析
  const usp = new URLSearchParams(window.location.search)
  return { code: usp.get('code'), state: usp.get('state') }
}

onMounted(async () => {
  try{
    const { code, state } = parseQuery()
    cachedState = state || ''
    if(!code){
      ElMessage.error('未获取到微信授权code')
      loading.value = false
      return
    }
    const res = await getWechatUserInfo({ code, state })
    // 假设后端返回 token 与跳转页
    const data = res?.data || res
    userInfo.value = data
    if(data?.is_bind){
      // 使用工具函数保存登录数据
      saveLoginData(userInfo.value)
      router.replace('/dashboard')
      return
    }else{
      showBind.value = true
    }
  }catch(e){
    ElMessage.error(e?.response?.data?.message || '授权失败，请重试')
  }finally{
    loading.value = false
  }
})

function onCancelBind(){
  showBind.value = false
  router.replace('/login')
}

async function onBind(){
  // 表单校验
  if (!bindFormRef.value) return
  
  try {
    await bindFormRef.value.validate()
  } catch (error) {
    ElMessage.warning('请检查表单信息')
    return
  }
  
  bindLoading.value = true
  try{
    const payload = { ...bindForm.value, ...userInfo.value }
    const res = await bindWechatAccount(payload)
    const data = res?.data || res
    ElMessage.success(data.message || '绑定成功')
    if (data) {
      showBind.value = false
      // 使用工具函数保存登录数据
      saveLoginData(data)
      router.replace('/dashboard')
    }
  }catch(e){
    ElMessage.error(e?.response?.data?.message || '绑定失败，请重试')
  }finally{
    bindLoading.value = false
  }
}
</script>

<style scoped>
.wx-callback {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f6f9;
}

.callback-card {
  width: 400px;
  text-align: center;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.loading-icon {
  font-size: 24px;
  animation: rotate 2s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 表单样式优化 */
.el-form-item {
  margin-bottom: 18px;
}

.el-form-item__label {
  font-weight: 500;
  color: #333;
}

.el-input {
  width: 100%;
}

.el-input__wrapper {
  border-radius: 6px;
}

/* 字符计数样式 */
.el-input__count {
  color: #999;
  font-size: 12px;
}
</style>

