<template>
  <div class="payment-modal-overlay" v-if="visible" @click="handleOverlayClick">
    <div class="payment-modal-container" @click.stop>
      <!-- 头部 -->
      <div class="modal-header">
        <h2 class="modal-title">{{ packageName }}会员</h2>
        <button class="close-btn" @click="handleClose">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M18 6L6 18M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </button>
      </div>

      <!-- 支付方式选择 -->
      <div class="payment-methods">
         <div class="payment-method active">
           <div class="method-icon">
             <svg width="24" height="24" viewBox="0 0 1228 1024" fill="none" xmlns="http://www.w3.org/2000/svg">
               <path d="M530.8928 703.1296a41.472 41.472 0 0 1-35.7376-19.8144l-2.7136-5.5808L278.272 394.752a18.7392 18.7392 0 0 1-2.048-8.1408 19.968 19.968 0 0 1 20.48-19.3536c4.608 0 8.8576 1.4336 12.288 3.84l234.3936 139.9296a64.4096 64.4096 0 0 0 54.528 5.9392L1116.2624 204.8C1004.9536 80.896 821.76 0 614.4 0 275.0464 0 0 216.576 0 483.6352c0 145.7152 82.7392 276.8896 212.2752 365.5168a38.1952 38.1952 0 0 1 17.2032 31.488 44.4928 44.4928 0 0 1-2.1504 12.3904l-27.6992 97.4848c-1.3312 4.608-3.328 9.3696-3.328 14.1312 0 10.752 9.216 19.3536 20.48 19.3536 4.4032 0 8.0384-1.536 11.776-3.584l134.5536-73.3184c10.1376-5.5296 20.7872-8.96 32.6144-8.96 6.2976 0 12.288 0.9216 18.0736 2.5088 62.72 17.0496 130.4576 26.5728 200.5504 26.5728C953.7024 967.168 1228.8 750.592 1228.8 483.6352c0-80.9472-25.4464-157.1328-70.0416-224.1024l-604.9792 436.992-4.4544 2.4064a42.1376 42.1376 0 0 1-18.432 4.1984z" fill="#15BA11"/>
             </svg>
           </div>
           <span>微信扫码支付</span>
         </div>
      </div>

      <!-- 金额显示 -->
      <div class="amount-section">
        <span class="amount-label">金额</span>
        <span class="amount-value">￥{{ amount }}</span>
      </div>

      <!-- 二维码区域 -->
      <div class="qr-section">
        <div class="qr-container">
          <div class="agreement-text">
            支付前请阅读
            <a href="/doc/支付协议.html" target="_blank" class="agreement-link">《1818AI付费服务协议》</a>
          </div>
          
          <!-- 二维码显示区域 -->
          <div class="qr-code-area" v-if="qrCodeUrl">
            <div class="qr-code-wrapper">
              <img :src="qrCodeUrl" alt="微信支付二维码" class="qr-code-image" />
            </div>
            <div class="qr-tips">
              <p>请使用微信扫描二维码完成支付</p>
              <p class="qr-tips-small">二维码有效期为15分钟</p>
            </div>
          </div>

          <!-- 加载状态 -->
          <div class="qr-loading" v-else-if="loading">
            <div class="loading-spinner"></div>
            <p>正在生成支付二维码...</p>
          </div>

           <!-- 错误状态 -->
           <div class="qr-error" v-else-if="error">
             <div class="error-icon">⚠️</div>
             <p>{{ error }}</p>
             <button class="retry-btn" @click="handleRetry">重试</button>
           </div>
        </div>
      </div>

      <!-- 底部协议 -->
      <div class="modal-footer">
        <a href="/doc/支付协议.html" target="_blank" class="footer-agreement">《1818AI付费服务协议》</a>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { queryPaymentStatus } from '../api/user'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  packageName: {
    type: String,
    default: '标准版'
  },
  amount: {
    type: Number,
    required: true
  },
  paymentParams: {
    type: String,
    default: ''
  },
  orderNo: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['close', 'payment-success', 'payment-failed'])

const loading = ref(false)
const error = ref('')
const qrCodeUrl = ref('')
const paymentStatus = ref('pending') // pending, paid, failed, expired
let pollingTimer = null
let timeoutTimer = null

// 生成二维码
const generateQRCode = async (codeUrl) => {
  try {
    loading.value = true
    error.value = ''
    
    // 使用qrcode.js生成二维码
    const QRCode = await import('qrcode')
    const qrDataURL = await QRCode.toDataURL(codeUrl, {
      width: 200,
      margin: 2,
      color: {
        dark: '#000000',
        light: '#FFFFFF'
      }
    })
    
    qrCodeUrl.value = qrDataURL
    loading.value = false
    
    // 开始轮询支付状态
    startPaymentStatusPolling()
  } catch (err) {
    console.error('生成二维码失败:', err)
    error.value = '生成二维码失败，请重试'
    loading.value = false
  }
}

// 轮询支付状态
const startPaymentStatusPolling = () => {
  if (!props.orderNo) {
    console.error('订单号为空，无法轮询支付状态')
    return
  }

  // 清除之前的定时器
  stopPolling()

  console.log('开始轮询支付状态，订单号:', props.orderNo)

  pollingTimer = setInterval(async () => {
    try {
      // 调用 /user/pay/orderQuery 接口
      const response = await queryPaymentStatus({ orderNo: props.orderNo })
      
      console.log('支付状态查询结果:', response)
      
      if (response.code === 200) {
        // 处理不同的响应格式
        let status
        if (typeof response.data === 'string') {
          // 如果data直接是字符串状态
          status = response.data
        } else if (response.data?.trade_state) {
          // 如果data是对象，包含trade_state字段
          status = response.data.trade_state
        } else if (response.data?.status) {
          // 如果data是对象，包含status字段
          status = response.data.status
        } else {
          status = response.data
        }
        
        console.log('解析出的支付状态:', status)
        
        // 微信支付状态：SUCCESS-支付成功, REFUND-转入退款, NOTPAY-未支付, CLOSED-已关闭, 
        // REVOKED-已撤销（仅付款码支付会返回）, USERPAYING-用户支付中（仅付款码支付会返回）, PAYERROR-支付失败(仅付款码支付会返回)
        if (status === 'SUCCESS' || status === 'PAID') {
          // 支付成功
          console.log('支付成功，准备关闭弹窗并更新用户信息')
          paymentStatus.value = 'paid'
          stopPolling()
          ElMessage.success('支付成功！')
          emit('payment-success', response.data)
        } else if (status === 'CLOSED' || status === 'PAYERROR' || status === 'FAILED' || status === 'CANCELLED') {
          // 支付失败、已关闭或取消
          paymentStatus.value = 'failed'
          stopPolling()
          error.value = '支付失败或已关闭，请重试'
          ElMessage.error('支付失败')
          emit('payment-failed', response.data)
        } else if (status === 'REFUND' || status === 'REVOKED') {
          // 已退款或已撤销
          paymentStatus.value = 'failed'
          stopPolling()
          error.value = '订单已退款或撤销'
          ElMessage.warning('订单已退款或撤销')
          emit('payment-failed', response.data)
        }
        // 如果是 NOTPAY 或 USERPAYING 状态，继续轮询
      }
    } catch (err) {
      console.error('检查支付状态失败:', err)
      // 网络错误时不停止轮询，继续尝试
    }
  }, 3000) // 每3秒检查一次

  // 15分钟后停止轮询
  timeoutTimer = setTimeout(() => {
    stopPolling()
    if (paymentStatus.value === 'pending') {
      paymentStatus.value = 'expired'
      error.value = '支付超时，请重新发起支付'
      ElMessage.warning('支付超时，请重新发起支付')
    }
  }, 15 * 60 * 1000)
}

// 停止轮询
const stopPolling = () => {
  if (pollingTimer) {
    clearInterval(pollingTimer)
    pollingTimer = null
  }
  if (timeoutTimer) {
    clearTimeout(timeoutTimer)
    timeoutTimer = null
  }
}


// 重试
const handleRetry = () => {
  if (props.paymentParams) {
    try {
      const params = JSON.parse(props.paymentParams)
      if (params.code_url) {
        generateQRCode(params.code_url)
      }
    } catch (err) {
      error.value = '支付参数错误'
    }
  }
}

// 关闭弹窗
const handleClose = () => {
  stopPolling()
  emit('close')
}

// 点击遮罩关闭
const handleOverlayClick = () => {
  handleClose()
}

// 监听支付参数变化
watch(() => props.paymentParams, (newParams) => {
  if (newParams && props.visible) {
    try {
      const params = JSON.parse(newParams)
      if (params.code_url) {
        generateQRCode(params.code_url)
      }
    } catch (err) {
      error.value = '支付参数格式错误'
    }
  }
}, { immediate: true })

// 监听弹窗显示状态
watch(() => props.visible, (newVisible) => {
  if (newVisible && props.paymentParams) {
    try {
      const params = JSON.parse(props.paymentParams)
      if (params.code_url) {
        generateQRCode(params.code_url)
      }
    } catch (err) {
      error.value = '支付参数格式错误'
    }
  } else if (!newVisible) {
    // 重置状态并停止轮询
    stopPolling()
    qrCodeUrl.value = ''
    error.value = ''
    paymentStatus.value = 'pending'
    loading.value = false
  }
})

// 组件卸载时清理定时器
onUnmounted(() => {
  stopPolling()
})
</script>

<style scoped>
.payment-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.6);
  backdrop-filter: blur(10px);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
}

.payment-modal-container {
  width: 655px;
  height: 792px;
  box-sizing: border-box;
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 12px;
  backdrop-filter: blur(74.0999984741211px);
  background: rgba(198, 208, 219, 0.2);
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 32px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.modal-title {
  color: rgba(255, 255, 255, 1);
  font-family: PingFang SC;
  font-size: 24px;
  font-weight: 400;
  line-height: 30px;
  letter-spacing: 0%;
  margin: 0;
}

.close-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
  border-radius: 8px;
  transition: all 0.2s ease;
}

.close-btn:hover {
  background: rgba(0, 0, 0, 0.1);
  color: #333;
}

.payment-methods {
  padding: 24px 32px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
}

.payment-method {
  width: 238px;
  height: 56px;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  gap: 10px;
  padding: 0;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.1);
  color: rgba(255, 255, 255, 0.6);
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-sizing: border-box;
}

.payment-method.active {
  background: rgba(255, 255, 255, 0.15);
  color: rgba(255, 255, 255, 1);
  border: 1px solid rgba(255, 255, 255, 0.4);
}

.method-icon {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.method-icon svg {
  width: 24px;
  height: 24px;
}

.amount-section {
  padding: 0px 0px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 12px;
}

.amount-label {
  font-size: 14px;
  color: #999;
}

.amount-value {
  font-size: 32px;
  font-weight: 600;
  /* color: #1890ff; */
  color: rgba(26, 195, 255, 1);
  /* rgba(180, 184, 187, 1) */
  /* rgba(255, 255, 255, 1) */
}

.qr-section {
  flex: 1;
  padding: 0;
  display: flex;
  flex-direction: column;
}

.qr-container {
  width: 525px;
  height: 438px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.02);
  border-radius: 12px;
  padding: 0px 20px;
  margin: 0 auto;
  box-sizing: border-box;
}

.agreement-text {
  font-size: 14px;
  color: #666;
  margin-bottom: 32px;
  text-align: center;
}

.agreement-link {
  color: #1890ff;
  text-decoration: none;
}

.agreement-link:hover {
  text-decoration: underline;
}

.qr-code-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 24px;
}

.qr-code-wrapper {
  width: 200px;
  height: 200px;
  background: white;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
}

.qr-code-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.qr-tips {
  text-align: center;
}

.qr-tips p {
  margin: 0;
  color: #666;
}

.qr-tips p:first-child {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
}

.qr-tips-small {
  font-size: 12px;
  color: #999;
}

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

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

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

.error-icon {
  font-size: 32px;
}

.retry-btn {
  padding: 8px 16px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.2s ease;
}

.retry-btn:hover {
  background: #40a9ff;
}

.pay-button {
  width: 200px;
  height: 48px;
  background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  margin-top: 24px;
}

.pay-button:hover:not(:disabled) {
  background: linear-gradient(135deg, #40a9ff 0%, #1890ff 100%);
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(24, 144, 255, 0.3);
}

.pay-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.modal-footer {
  padding: 24px 32px;
  border-top: 1px solid rgba(0, 0, 0, 0.1);
  text-align: center;
}

.footer-agreement {
  font-size: 12px;
  color: #999;
  text-decoration: none;
}

.footer-agreement:hover {
  text-decoration: underline;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .payment-modal-container {
    width: 90vw;
    height: 80vh;
    max-width: 500px;
  }
  
  .modal-header,
  .payment-methods,
  .amount-section,
  .modal-footer {
    padding-left: 20px;
    padding-right: 20px;
  }
  
  .qr-code-wrapper {
    width: 160px;
    height: 160px;
  }
  
  .pay-button {
    width: 160px;
  }
}
</style>
