<template>
  <div style="padding: 40px; text-align: center; font-family: Arial, sans-serif;">
    <div v-if="loading" style="margin-top: 100px;">
      <i class="el-icon-loading" style="font-size: 48px; color: #409EFF;"></i>
      <p style="margin-top: 20px; font-size: 16px; color: #666;">正在处理授权...</p>
    </div>
    
    <div v-else-if="success" style="margin-top: 100px;">
      <i class="el-icon-success" style="font-size: 64px; color: #67C23A;"></i>
      <h2 style="margin-top: 20px; color: #67C23A;">授权成功！</h2>
      <div style="margin-top: 30px; padding: 20px; background: #f5f7fa; border-radius: 8px; max-width: 600px; margin-left: auto; margin-right: auto;">
        <p style="margin-bottom: 15px; font-size: 14px; color: #666;">请复制以下访问令牌：</p>
        <el-input
          :value="accessToken"
          readonly
          style="margin-bottom: 15px;"
        >
          <template slot="append">
            <el-button @click="copyToken" icon="el-icon-document-copy">复制</el-button>
          </template>
        </el-input>
        <p style="font-size: 12px; color: #999; margin-top: 10px;">
          访问令牌有效期：{{ expiresIn }} 秒
        </p>
      </div>
      <div style="margin-top: 30px;">
        <el-button type="primary" @click="closeWindow">关闭窗口</el-button>
      </div>
    </div>
    
    <div v-else style="margin-top: 100px;">
      <i class="el-icon-error" style="font-size: 64px; color: #F56C6C;"></i>
      <h2 style="margin-top: 20px; color: #F56C6C;">授权失败</h2>
      <p style="margin-top: 20px; color: #666;">{{ errorMessage }}</p>
      <div style="margin-top: 30px;">
        <el-button type="primary" @click="closeWindow">关闭窗口</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getTencentDocAccessToken } from '@/api/jarvis/tendoc'

export default {
  name: 'TencentDocCallback',
  data() {
    return {
      loading: true,
      success: false,
      accessToken: '',
      refreshToken: '',
      expiresIn: 0,
      errorMessage: ''
    }
  },
  created() {
    this.handleCallback()
  },
  methods: {
    async handleCallback() {
      // 从URL参数中获取code和state
      const urlParams = new URLSearchParams(window.location.search)
      const code = urlParams.get('code')
      const state = urlParams.get('state')
      const error = urlParams.get('error')
      const errorDescription = urlParams.get('error_description')
      
      // 处理授权错误
      if (error) {
        this.loading = false
        this.errorMessage = errorDescription || error || '授权失败'
        return
      }
      
      // 验证授权码
      if (!code) {
        this.loading = false
        this.errorMessage = '未收到授权码，请重新授权'
        return
      }
      
      try {
        // 调用后端接口获取访问令牌
        const res = await getTencentDocAccessToken(code)
        
        if (res.code === 200 && res.data) {
          const data = res.data
          this.accessToken = data.access_token || data.accessToken || ''
          this.refreshToken = data.refresh_token || data.refreshToken || ''
          this.expiresIn = data.expires_in || data.expiresIn || 0
          
          // 保存到localStorage，供主窗口使用
          if (this.accessToken) {
            localStorage.setItem('tendoc_access_token', this.accessToken)
            if (this.refreshToken) {
              localStorage.setItem('tendoc_refresh_token', this.refreshToken)
            }
            
            // 通知父窗口（如果是从弹窗打开的）
            if (window.opener) {
              window.opener.postMessage({
                type: 'tendoc_auth_success',
                access_token: this.accessToken,
                refresh_token: this.refreshToken,
                expires_in: this.expiresIn
              }, '*')
            }
          }
          
          this.success = true
        } else {
          this.errorMessage = res.msg || '获取访问令牌失败'
        }
      } catch (e) {
        console.error('获取访问令牌失败', e)
        this.errorMessage = e.message || '获取访问令牌失败，请稍后重试'
      } finally {
        this.loading = false
      }
    },
    
    copyToken() {
      if (this.accessToken) {
        if (navigator.clipboard) {
          navigator.clipboard.writeText(this.accessToken).then(() => {
            this.$message.success('访问令牌已复制到剪贴板')
          }).catch(() => {
            this.fallbackCopy(this.accessToken)
          })
        } else {
          this.fallbackCopy(this.accessToken)
        }
      }
    },
    
    fallbackCopy(text) {
      const textArea = document.createElement('textarea')
      textArea.value = text
      textArea.style.position = 'fixed'
      textArea.style.left = '-999999px'
      textArea.style.top = '-999999px'
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()
      try {
        document.execCommand('copy')
        this.$message.success('访问令牌已复制到剪贴板')
      } catch (err) {
        this.$message.error('复制失败，请手动复制')
      }
      document.body.removeChild(textArea)
    },
    
    closeWindow() {
      if (window.opener) {
        window.close()
      } else {
        // 如果不是弹窗，跳转到订单列表页面
        this.$router.push('/system/jdorder/orderList')
      }
    }
  }
}
</script>

<style scoped>
</style>

