<template>
  <div class="payment-container">
    <div class="payment-card">
      <div class="payment-header">
        <h2>完成支付激活账户</h2>
        <p class="payment-desc">请完成支付以激活您的账户</p>
      </div>
      
      <div class="payment-info">
        <div class="info-item">
          <span class="label">支付金额：</span>
          <span class="value price">¥{{ paymentAmount }}</span>
        </div>
      </div>
      
      <div class="payment-methods">
        <!-- <div class="method-item" :class="{ active: selectedMethod === 'wechat_h5' }" @click="selectedMethod = 'wechat_h5'">
          <div class="method-icon">
            <svg viewBox="0 0 24 24" width="24" height="24">
              <path fill="#07C160" d="M8.5 6.5c-1.4 0-2.5 1.1-2.5 2.5s1.1 2.5 2.5 2.5 2.5-1.1 2.5-2.5-1.1-2.5-2.5-2.5zm7 0c-1.4 0-2.5 1.1-2.5 2.5s1.1 2.5 2.5 2.5 2.5-1.1 2.5-2.5-1.1-2.5-2.5-2.5zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8 0-1.12.23-2.18.64-3.15.41-.97 1.01-1.85 1.78-2.62.77-.77 1.65-1.37 2.62-1.78C9.82 4.23 10.88 4 12 4s2.18.23 3.15.64c.97.41 1.85 1.01 2.62 1.78.77.77 1.37 1.65 1.78 2.62.41.97.64 2.03.64 3.15 0 4.41-3.59 8-8 8z"/>
            </svg>
          </div>
          <span class="method-name">微信支付</span>
          <div class="method-check" v-show="selectedMethod === 'wechat_h5'">
            <el-icon><Check /></el-icon>
          </div>
        </div> -->
        
        <div class="method-item" :class="{ active: selectedMethod === 'alipay_wap' }" @click="selectedMethod = 'alipay_wap'">
          <div class="method-icon">
            <svg viewBox="0 0 24 24" width="24" height="24">
              <path fill="#1677FF" d="M12 2C6.48 2 2 6.48 2 12c0 2.85 1.2 5.41 3.11 7.24C7.64 20.69 9.68 21.5 12 21.5s4.36-.81 6.89-2.26C20.8 17.41 22 14.85 22 12c0-5.52-4.48-10-10-10zm4.64 14.32c-.78.61-1.74 1.07-2.82 1.34-.65.16-1.33.24-2.02.24-1.85 0-3.58-.72-4.88-2.03C5.72 14.67 5 12.94 5 11.09c0-1.85.72-3.58 2.03-4.88C8.33 5 10.06 4.28 11.91 4.28c1.85 0 3.58.72 4.88 2.03 1.31 1.3 2.03 3.03 2.03 4.88 0 1.85-.72 3.58-2.03 4.88-.25.25-.52.48-.8.69-.28.21-.57.4-.87.56z"/>
              <path fill="#1677FF" d="M15.5 9.5h-7c-.28 0-.5.22-.5.5s.22.5.5.5h7c.28 0 .5-.22.5-.5s-.22-.5-.5-.5zm0 2h-7c-.28 0-.5.22-.5.5s.22.5.5.5h7c.28 0 .5-.22.5-.5s-.22-.5-.5-.5zm-2 2h-5c-.28 0-.5.22-.5.5s.22.5.5.5h5c.28 0 .5-.22.5-.5s-.22-.5-.5-.5z"/>
            </svg>
          </div>
          <span class="method-name">支付宝支付</span>
          <div class="method-check" v-show="selectedMethod === 'alipay_wap'">
            <el-icon><Check /></el-icon>
          </div>
        </div>
      </div>
      
      <div class="payment-actions">
        <el-button size="large" @click="goBack">返回</el-button>
        <el-button 
          type="primary" 
          size="large" 
          :loading="paymentLoading"
          @click="handlePayment"
          :disabled="!selectedMethod"
        >
          {{ paymentLoading ? '处理中...' : '立即支付' }}
        </el-button>
      </div>
      
      <div class="payment-status" v-if="paymentStatus">
        <div class="status-item" :class="paymentStatus">
          <el-icon v-if="paymentStatus === 'success'"><SuccessFilled /></el-icon>
          <el-icon v-else-if="paymentStatus === 'failed'"><CircleCloseFilled /></el-icon>
          <el-icon v-else><Loading /></el-icon>
          <span>{{ getStatusText() }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Check, SuccessFilled, CircleCloseFilled, Loading } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import api, { paymentAPI } from '@/utils/api'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const selectedMethod = ref('alipay_wap') // 默认选择微信支付
const paymentLoading = ref(false)
const paymentStatus = ref('')
const paymentAmount = ref(399) // 注册费用
const userInfo = reactive({
  userId: '',
})

// 获取用户信息
const getUserInfo = async () => {
  try {
    // 优先从用户store获取信息
    if (userStore.user) {
      userInfo.username = userStore.user.username
      userInfo.phone = userStore.user.phone
      return
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 处理支付
const handlePayment = async () => {
  // 验证支付方式
  if (!['wechat_h5', 'alipay_wap'].includes(selectedMethod.value)) {
    ElMessage.error('请选择支付方式')
    return
  }
  
  paymentLoading.value = true
  paymentStatus.value = 'processing'
  
  try {
    // 优先使用URL参数中的token和userId（注册流程）
    let token = route.query.token
    let userId = route.query.userId
    
    // 如果没有URL参数，使用当前登录用户信息
    if (!token || !userId) {
      token = userStore.token
      userId = userStore.user?.id
    }
    
    if (!userId) {
      throw new Error('无法获取用户信息，请重新登录')
    }
    
    // 创建统一支付订单
    const response = await paymentAPI.createOrder({
      userId: userId,
      amount: paymentAmount.value,
      description: '用户注册激活费用',
      paymentMethod: selectedMethod.value
    })
    
    if (response.data.success) {
      const { outTradeNo, payUrl } = response.data.data
      
      // 根据支付方式跳转到对应支付页面
      if (selectedMethod.value === 'wechat_h5') {
        // 微信支付 - 跳转到支付页面
        window.location.href = payUrl
      } else if (selectedMethod.value === 'alipay_wap') {
        // 支付宝支付 - 跳转到支付页面
        window.location.href = payUrl
      }
      
      // 开始轮询支付状态
      startPaymentStatusPolling(outTradeNo, token)
    } else {
      throw new Error(response.data.message || '创建支付订单失败')
    }
  } catch (error) {
    console.error('支付失败:', error)
    ElMessage.error(error.message || '支付失败，请重试')
    paymentStatus.value = 'failed'
  } finally {
    paymentLoading.value = false
  }
}

// 轮询支付状态
const startPaymentStatusPolling = (outTradeNo, token) => {
  const pollInterval = setInterval(async () => {
    try {
        const response = await paymentAPI.queryStatus(outTradeNo, token)
        
        if (response.data.success) {
        // 处理支付状态（微信和支付宝）
        const data = response.data.data;
        let isPaid = false;
        
        if (selectedMethod.value === 'wechat_h5') {
          // 微信支付状态判断
          isPaid = data.trade_state === 'SUCCESS';
        } else if (selectedMethod.value === 'alipay_wap') {
          // 支付宝支付状态判断
          isPaid = data.trade_status === 'TRADE_SUCCESS';
        }
        
        if (isPaid) {
          clearInterval(pollInterval)
          paymentStatus.value = 'success'
          ElMessage.success('支付成功！账户已激活')
          
          // 如果是已登录用户，刷新用户信息并跳转到主页
          if (userStore.isAuthenticated) {
            await userStore.checkAuth() // 刷新用户信息，更新支付状态
            setTimeout(() => {
              router.push('/transfers')
            }, 2000)
          } else {
            // 如果是注册流程，跳转到登录页面
            setTimeout(() => {
              router.push('/login')
            }, 2000)
          }
        } else {
          // 检查支付失败状态
          let isFailed = false;
          
          if (selectedMethod.value === 'wechat_h5') {
            // 微信支付失败状态
            isFailed = data.trade_state === 'CLOSED' || data.trade_state === 'REVOKED' || data.trade_state === 'PAYERROR';
          } else if (selectedMethod.value === 'alipay_wap') {
            // 支付宝支付失败状态
            isFailed = data.trade_status === 'TRADE_CLOSED';
          }
          
          if (isFailed) {
            clearInterval(pollInterval)
            paymentStatus.value = 'failed'
            ElMessage.error('支付失败，请重试')
          }
        }
      }
    } catch (error) {
      console.error('查询支付状态失败:', error)
    }
  }, 3000) // 每3秒查询一次
  
  // 5分钟后停止轮询
  setTimeout(() => {
    clearInterval(pollInterval)
    if (paymentStatus.value === 'processing') {
      paymentStatus.value = 'timeout'
      ElMessage.warning('支付超时，请检查支付状态或重新支付')
    }
  }, 300000)
}

// 获取状态文本
const getStatusText = () => {
  switch (paymentStatus.value) {
    case 'processing':
      return '支付处理中...'
    case 'success':
      return '支付成功！'
    case 'failed':
      return '支付失败'
    case 'timeout':
      return '支付超时'
    default:
      return ''
  }
}

// 返回上一页
const goBack = () => {
  ElMessageBox.confirm(
    '返回将取消当前支付，确定要返回吗？',
    '确认返回',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    router.push('/register')
  })
}

// 页面加载时获取用户信息
onMounted(() => {
  getUserInfo()
})
</script>

<style scoped>
.payment-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.payment-card {
  background: white;
  border-radius: 16px;
  padding: 40px;
  width: 100%;
  max-width: 500px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
}

.payment-header {
  text-align: center;
  margin-bottom: 30px;
}

.payment-header h2 {
  color: #333;
  margin-bottom: 8px;
  font-size: 24px;
  font-weight: 600;
}

.payment-desc {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.payment-info {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 30px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-item .label {
  color: #666;
  font-size: 14px;
}

.info-item .value {
  color: #333;
  font-weight: 500;
}

.info-item .price {
  color: #e74c3c;
  font-size: 18px;
  font-weight: 600;
}

.payment-methods {
  margin-bottom: 30px;
}

.method-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border: 2px solid #e9ecef;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 12px;
}

.method-item:last-child {
  margin-bottom: 0;
}

.method-item:hover {
  border-color: #667eea;
  background: #f8f9ff;
}

.method-item.active {
  border-color: #667eea;
  background: #f8f9ff;
}

.method-icon {
  margin-right: 12px;
}

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

.method-name {
  flex: 1;
  font-weight: 500;
  color: #333;
}

.method-check {
  color: #667eea;
}

.payment-actions {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.payment-actions .el-button {
  flex: 1;
  height: 48px;
  font-size: 16px;
  border-radius: 12px;
}

.payment-status {
  text-align: center;
  padding: 16px;
  border-radius: 12px;
  background: #f8f9fa;
}

.status-item {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-weight: 500;
}

.status-item.processing {
  color: #3498db;
}

.status-item.success {
  color: #27ae60;
}

.status-item.failed {
  color: #e74c3c;
}

.status-item.timeout {
  color: #f39c12;
}

@media (max-width: 768px) {
  .payment-card {
    padding: 24px;
    margin: 16px;
  }
  
  .payment-header h2 {
    font-size: 20px;
  }
  
  .payment-actions {
    flex-direction: column;
  }
}
</style>