<template>
  <div v-if="visible" class="modal-overlay" @click="handleClose">
    <div class="modal-container" @click.stop>
      <div class="modal-content">
        <div class="modal-header">
          <h3 class="modal-title">微信绑定</h3>
          <button class="modal-close" @click="handleClose">×</button>
        </div>
        
        <div class="modal-body">
          <!-- 加载状态 -->
          <div v-if="currentStep === 'loading'" class="step-content">
            <div class="loading-container">
              <el-icon class="loading-icon is-loading"><Loading /></el-icon>
              <p class="loading-text">正在生成二维码...</p>
            </div>
          </div>
          
          <!-- 显示二维码 -->
          <div v-else-if="currentStep === 'qrcode'" class="step-content">
            <div class="qr-container">
              <div class="qr-header">
                <el-icon class="wechat-icon"><ChatDotSquare /></el-icon>
                <h4 class="qr-title">请使用微信扫描二维码</h4>
                <p class="wechat-bind-tip">扫码关注公众号即可绑定微信</p>
              </div>
              
              <div class="qr-code-wrapper">
                <img :src="qrCodeUrl" alt="微信二维码" class="qr-code-image" />
              </div>
              
              <!-- 等待扫码提示 -->
              <div v-if="polling" class="polling-status">
                <el-icon class="polling-icon is-loading"><Loading /></el-icon>
                <p class="polling-text">等待扫码中...</p>
              </div>
              
              <div class="qr-instructions">
                <p class="instruction-item">1. 打开微信，点击右上角"+"</p>
                <p class="instruction-item">2. 选择"扫一扫"</p>
                <p class="instruction-item">3. 扫描上方二维码完成绑定</p>
              </div>
              
              <div class="qr-footer">
                <p class="qr-tip">
                  <el-icon class="tip-icon"><InfoFilled /></el-icon>
                  二维码5分钟内有效，请及时扫描
                </p>
                <button class="refresh-btn" @click="refreshQRCode" :disabled="refreshing">
                  <el-icon class="refresh-icon" :class="{ 'is-loading': refreshing }">
                    <Refresh />
                  </el-icon>
                  {{ refreshing ? '刷新中...' : '刷新二维码' }}
                </button>
              </div>
            </div>
          </div>
          
          <!-- 绑定成功 -->
          <div v-else-if="currentStep === 'success'" class="step-content">
            <div class="result-container success">
              <el-icon class="result-icon success-icon"><SuccessFilled /></el-icon>
              <h4 class="result-title">绑定成功</h4>
              <p class="result-message">您的微信账号已成功绑定到当前账户</p>
              <button class="result-btn success-btn" @click="handleSuccess">确定</button>
            </div>
          </div>
          
          <!-- 绑定失败 -->
          <div v-else-if="currentStep === 'error'" class="step-content">
            <div class="result-container error">
              <el-icon class="result-icon error-icon"><CircleCloseFilled /></el-icon>
              <h4 class="result-title">绑定失败</h4>
              <p class="result-message">{{ errorMessage }}</p>
              <div class="result-actions">
                <button class="result-btn secondary-btn" @click="retryBind">重试</button>
                <button class="result-btn primary-btn" @click="handleClose">关闭</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onUnmounted } from 'vue'
import { ElMessage, ElIcon } from 'element-plus'
import { 
  Loading, 
  ChatDotSquare, 
  InfoFilled, 
  Refresh, 
  SuccessFilled, 
  CircleCloseFilled 
} from '@element-plus/icons-vue'
import { getWechatBindQR, checkWechatBindStatus } from '../api/user'

// 定义props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

// 定义emits
const emit = defineEmits(['close', 'success'])

// 状态管理
const currentStep = ref('loading') // loading, qrcode, success, error
const qrCodeUrl = ref('')
const sceneStr = ref('')
const polling = ref(false)
const refreshing = ref(false)
const errorMessage = ref('')

let pollingTimer = null
let qrTimer = null

// 监听弹窗显示状态
watch(() => props.visible, (newVal) => {
  if (newVal) {
    // ✅ 简化逻辑：每次打开都直接请求新二维码
    currentStep.value = 'loading'
    getQRCode()
  } else {
    cleanup()
  }
})

// 获取二维码
const getQRCode = async () => {
  try {
    const response = await getWechatBindQR()
    if (response.code === 200) {
      qrCodeUrl.value = response.data.qrCodeUrl
      sceneStr.value = response.data.sceneStr
      currentStep.value = 'qrcode'
      
      // 开始轮询
      startPolling()
      
      // 设置二维码过期定时器（5分钟）
      startQRTimer()
    } else {
      throw new Error(response.message || '获取二维码失败')
    }
  } catch (error) {
    console.error('获取二维码失败:', error)
    showError(error.message || '获取二维码失败，请稍后重试')
  }
}

// 开始轮询绑定状态
const startPolling = () => {
  if (pollingTimer) {
    clearInterval(pollingTimer)
  }
  
  polling.value = true
  pollingTimer = setInterval(async () => {
    try {
      const response = await checkWechatBindStatus(sceneStr.value)
      
      if (response.code === 200) {
        // 绑定成功
        stopPolling()
        currentStep.value = 'success'
      } else if (response.code === 400) {
        // 绑定失败
        stopPolling()
        showError(response.message || '该微信账号已绑定其他用户')
      }
      // code === 202 时继续轮询
    } catch (error) {
      console.error('检查绑定状态失败:', error)
      // 网络错误时不停止轮询，继续尝试
      if (error.code !== 'NETWORK_ERROR') {
        ElMessage.error('网络连接异常，请检查网络后重试')
      }
    }
  }, 2000) // 每2秒轮询一次
}

// 停止轮询
const stopPolling = () => {
  if (pollingTimer) {
    clearInterval(pollingTimer)
    pollingTimer = null
  }
  polling.value = false
}

// 设置二维码过期定时器
const startQRTimer = () => {
  if (qrTimer) {
    clearTimeout(qrTimer)
  }
  
  qrTimer = setTimeout(() => {
    if (currentStep.value === 'qrcode') {
      showError('二维码已过期，请刷新后重新扫描')
    }
  }, 5 * 60 * 1000) // 5分钟
}

// 刷新二维码
const refreshQRCode = async () => {
  if (refreshing.value) return
  
  refreshing.value = true
  stopPolling()
  
  if (qrTimer) {
    clearTimeout(qrTimer)
    qrTimer = null
  }
  
  try {
    await getQRCode()
    ElMessage.success('二维码已刷新')
  } catch (error) {
    console.error('刷新二维码失败:', error)
    ElMessage.error('刷新失败，请稍后重试')
  } finally {
    refreshing.value = false
  }
}

// 显示错误
const showError = (message) => {
  errorMessage.value = message
  currentStep.value = 'error'
  stopPolling()
  
  if (qrTimer) {
    clearTimeout(qrTimer)
    qrTimer = null
  }
}

// 重试绑定
const retryBind = () => {
  currentStep.value = 'loading'
  getQRCode()
}

// 处理绑定成功
const handleSuccess = () => {
  emit('success')
  handleClose()
}

// 处理关闭
const handleClose = () => {
  emit('close')
  cleanup()
}

// 清理资源
const cleanup = () => {
  stopPolling()
  
  if (qrTimer) {
    clearTimeout(qrTimer)
    qrTimer = null
  }
}

// 组件销毁时清理定时器
onUnmounted(() => {
  cleanup()
})
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 99999;
}

.modal-container {
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

.modal-content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.modal-title {
  font-family: Arial, sans-serif;
  font-weight: 600;
  font-size: 20px;
  line-height: 24px;
  color: #333;
  margin: 0;
}

.modal-close {
  width: 32px;
  height: 32px;
  border: none;
  background: transparent;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.3s;
}

.modal-close:hover {
  background: #f5f5f5;
  color: #666;
}

.modal-body {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

.step-content {
  width: 100%;
  text-align: center;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  padding: 40px 20px;
}

.loading-icon {
  font-size: 32px;
  color: #409eff;
}

.loading-text {
  font-family: Arial, sans-serif;
  font-size: 16px;
  color: #666;
  margin: 0;
}

/* 二维码样式 */
.qr-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

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

.wechat-icon {
  font-size: 32px;
  color: #07c160;
}

.qr-title {
  font-family: Arial, sans-serif;
  font-weight: 600;
  font-size: 18px;
  line-height: 22px;
  color: #333;
  margin: 0;
}

.wechat-bind-tip {
  font-family: Arial, sans-serif;
  font-size: 13px;
  line-height: 16px;
  color: #07c160;
  margin: 0;
  font-weight: 500;
  opacity: 0.9;
}

.qr-code-wrapper {
  position: relative;
  display: inline-block;
  padding: 16px;
  background: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.qr-code-image {
  width: 200px;
  height: 200px;
  display: block;
}

.polling-status {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  margin: 16px 0;
  padding: 12px 20px;
  background: rgba(64, 158, 255, 0.1);
  border: 1px solid rgba(64, 158, 255, 0.2);
  border-radius: 8px;
  max-width: 200px;
}

.polling-icon {
  font-size: 16px;
  color: #409eff;
}

.polling-text {
  font-family: Arial, sans-serif;
  font-size: 14px;
  color: #409eff;
  margin: 0;
  font-weight: 500;
}

.qr-instructions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  text-align: left;
  max-width: 300px;
}

.instruction-item {
  font-family: Arial, sans-serif;
  font-size: 14px;
  line-height: 18px;
  color: #666;
  margin: 0;
  padding: 4px 0;
}

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

.qr-tip {
  display: flex;
  align-items: center;
  gap: 6px;
  font-family: Arial, sans-serif;
  font-size: 13px;
  color: #faad14;
  margin: 0;
}

.tip-icon {
  font-size: 14px;
}

.refresh-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  background: transparent;
  border: 1px solid #409eff;
  border-radius: 4px;
  color: #409eff;
  font-family: Arial, sans-serif;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.refresh-btn:hover:not(:disabled) {
  background: #409eff;
  color: #fff;
}

.refresh-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.refresh-icon {
  font-size: 14px;
}

/* 结果状态样式 */
.result-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  padding: 40px 20px;
}

.result-icon {
  font-size: 48px;
}

.success-icon {
  color: #52c41a;
}

.error-icon {
  color: #ff4d4f;
}

.result-title {
  font-family: Arial, sans-serif;
  font-weight: 600;
  font-size: 20px;
  line-height: 24px;
  color: #333;
  margin: 0;
}

.result-message {
  font-family: Arial, sans-serif;
  font-size: 16px;
  line-height: 20px;
  color: #666;
  text-align: center;
  margin: 0;
  max-width: 300px;
}

.result-actions {
  display: flex;
  gap: 12px;
}

.result-btn {
  padding: 10px 24px;
  border: none;
  border-radius: 4px;
  font-family: Arial, sans-serif;
  font-weight: 500;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  min-width: 80px;
}

.success-btn {
  background: #52c41a;
  color: #fff;
}

.success-btn:hover {
  background: #73d13d;
}

.primary-btn {
  background: #409eff;
  color: #fff;
}

.primary-btn:hover {
  background: #66b1ff;
}

.secondary-btn {
  background: #fff;
  color: #666;
  border: 1px solid #d9d9d9;
}

.secondary-btn:hover {
  color: #409eff;
  border-color: #409eff;
}

/* 响应式设计 */
@media screen and (max-width: 480px) {
  .modal-container {
    width: 95%;
    margin: 20px;
  }
  
  .qr-code-image {
    width: 160px;
    height: 160px;
  }
  
  .qr-instructions {
    max-width: 250px;
  }
  
  .result-actions {
    flex-direction: column;
    width: 100%;
  }
  
  .result-btn {
    width: 100%;
  }
}

/* 动画效果 */
.is-loading {
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
