<template>
  <div class="recharge-page">
    <!-- 顶部标题 -->
    <div class="page-header">
      <div class="header-content">
        <div class="logo-wrapper">
          <div class="logo-container">
            <img src="@/assets/images/logo.png" alt="告白语音" class="logo-image" />
          </div>
        </div>
      </div>
    </div>
    
    <!-- 用户信息 -->
    <div class="user-info-section">
      <div class="user-info-card">
        <div class="user-avatar">
          <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar" />
          <div v-else class="avatar-placeholder">
            <van-icon name="user-o" size="28" />
          </div>
          <!--<div class="switch-btn" @click="switchUser">
          </div>-->
        </div>
        <div class="user-details">
          <div class="user-name">{{ userInfo.nickname || '未知用户' }}</div>
          <div class="user-id">
            <img src="@/assets/images/id.png" alt="ID" class="id-icon" />
            <span>{{ userInfo.id || '未知ID' }}</span>
          </div>
        </div>
        <div class="switch-account-btn" @click="switchUser">
          切换账号
        </div>
      </div>
    </div>
    
    <!-- 充值金额选择 -->
    <div class="recharge-section">
      <h2 class="section-title">充值金额</h2>
      
      <div class="recharge-grid">
        <div 
          v-for="(item, index) in rechargeOptions" 
          :key="index"
          class="recharge-item"
          :class="{ active: selectedRecharge === index }"
          @click="selectRecharge(index)"
        >
          <div class="diamond-icon">
            <img src="@/assets/images/recharge_zuanshi.png" alt="钻石" class="diamond-img" />
          </div>
          <div class="recharge-amount">{{ item.amount }}</div>
          <div class="recharge-price">¥{{ item.price }}</div>
        </div>
      </div>
    </div>
    
    <!-- 支付方式 -->
    <div class="payment-section">
      <div class="payment-option">
        <div class="payment-icon">
          <img src="@/assets/images/recharge_paypal.png" alt="支付宝支付" class="alipay-icon" />
        </div>
        <div class="payment-name">支付宝支付</div>
        <div class="payment-selected">
          <img src="@/assets/images/duihao.png" alt="选中" class="check-icon" />
        </div>
      </div>
    </div>
    
    <!-- 温馨提示 -->
    <div class="tips-section">
      <div class="tips-title">温馨提示：</div>
      <div class="tips-content">
        <div class="tip-item">1. 充值前请确定您已满18周岁并具有完全民事行为能力。</div>
        <div class="tip-item">2. 安全账号转账、理赔转账、刷单、代充均为骗局，请认真核实并确认</div>
        <div class="tip-item">3. 大额充值，支付方式可选择"零钱通"</div>
        <div class="tip-item">4. 如有疑问，请联系服务号客服</div>
      </div>
      
      <!-- 协议勾选 -->
      <div class="agreement-checkbox" @click="toggleAgreement">
        <div class="checkbox-wrapper" :class="{ checked: agreementChecked }">
          <van-icon v-if="agreementChecked" name="success" size="14" color="#fff" />
        </div>
        <div class="agreement-text">
          我已阅读并同意 <span class="agreement-link" @click.stop="showAgreement">《用户充值协议》</span>
        </div>
      </div>
    </div>
    
    <!-- 支付按钮 -->
    <div class="pay-button">
      <van-button type="primary" block round @click="confirmPay">确认支付</van-button>
    </div>
    
    <!-- 协议弹框 -->
    <van-dialog
      v-model="agreementVisible"
      title="用户充值协议"
      confirm-button-text="我已阅读"
      @confirm="agreementChecked = true"
      :show-cancel-button="false"
    >
      <div class="agreement-content">
        <iframe v-if="agreementVisible" src="https://gbyy91.com/agreement/recharge.html" frameborder="0" class="agreement-iframe"></iframe>
      </div>
    </van-dialog>
  </div>
</template>

<script>
// eslint-disable-next-line no-undef
import { getProductList } from '@/api/product'
import { getUserInfo } from '@/api/user'
import { aliPayCoin, aliPayH5 } from '@/api/pay'
import { getDevicePayWayId, getPlatformType } from '@/utils/config'

export default {
  name: 'RechargePage',
  data() {
    return {
      resultDataMess: {},
      userInfo: {
        id: '',
        nickname: '',
        avatar: ''
      },
      rechargeOptions: [],
      selectedRecharge: 0,
      paymentMethod: 'alipay',
      isLoading: false,
      agreementChecked: false,
      agreementVisible: false
    }
  },
  computed: {
    selectedRechargeOption() {
      return this.rechargeOptions[this.selectedRecharge] || null
    }
  },
  created() {
    // 获取用户信息
    this.initUserInfo()
    
    // 获取产品列表
    this.fetchProductList()
  },
  methods: {
    // 初始化用户信息
    async initUserInfo() {
      // 从路由参数获取用户信息
      const { id, nickname, avatar } = this.$route.query
      if (id) {
        // 如果路由参数中有用户ID，直接使用
        this.userInfo.id = id
        this.userInfo.nickname = nickname || '未知用户'
        this.userInfo.avatar = avatar || ''
      } else {
        // 如果没有用户ID，尝试从本地存储获取
        const savedUserId = localStorage.getItem('lastUserId')
        if (savedUserId) {
          try {
            // 从API获取用户信息
            const res = await getUserInfo(savedUserId)
            if (res.data && res.data.userId) {
              this.userInfo.id = res.data.userId
              this.userInfo.nickname = res.data.userName || '未知用户'
              this.userInfo.avatar = res.data.avatar || ''
            } else {
              this.$toast('未找到用户信息')
              this.$router.replace('/')
            }
          } catch (error) {
            console.error('获取用户信息失败:', error)
            this.$toast('获取用户信息失败')
            this.$router.replace('/')
          }
        } else {
          // 没有用户ID，返回搜索页面
          this.$toast('请先搜索用户')
          this.$router.replace('/')
        }
      }
      
      // 保存最后使用的用户ID
      if (this.userInfo.id) {
        localStorage.setItem('lastUserId', this.userInfo.id)
      }
    },
    // 获取产品列表
    async fetchProductList() {
      try {
        const payWayId = getDevicePayWayId()
        const res = await getProductList(payWayId)
        this.rechargeOptions = res.data || []
      } catch (error) {
        console.error('获取产品列表失败:', error)
        // 设置默认数据，以防接口调用失败
        this.rechargeOptions = [
          { amount: 60, price: 6 },
          { amount: 120, price: 6 },
          { amount: 300, price: 6 },
          { amount: 600, price: 6 },
          { amount: 1000, price: 6 },
          { amount: 2000, price: 6 },
          { amount: 3800, price: 6 },
          { amount: 5000, price: 6 },
          { amount: 10000, price: 6 }
        ]
      }
    },
    selectRecharge(index) {
      this.selectedRecharge = index
    },
    // 切换用户
    switchUser() {
      this.$router.push('/')
    },
    // 切换协议勾选状态
    toggleAgreement() {
      this.agreementChecked = !this.agreementChecked
    },
    // 显示协议弹框
    showAgreement() {
      this.agreementVisible = true
    },
    confirmPay() {
      if (this.isLoading) return // 防止重复点击
      
      if (!this.userInfo.id) {
        this.$toast('请先选择用户')
        return
      }
      
      // 检查协议是否勾选
      if (!this.agreementChecked) {
        this.$toast('请阅读并同意充值协议')
        return
      }
      
      const selectedOption = this.rechargeOptions[this.selectedRecharge]
      
      // 使用二次确认弹窗
      this.$dialog.confirm({
        title: '支付确认',
        message: `
          <div class="confirm-dialog-content">
            <div class="confirm-tip">请核实并确认ID是否正确，请提防：</div>
            <div class="warning-list">
              <div class="warning-item">刷单赚取佣金</div>
              <div class="warning-item">公检法要求转账到安全账户</div>
              <div class="warning-item">购物退款、理赔需要转账</div>
              <div class="warning-item">代充值</div>
              <div class="warning-item">支付返利活动</div>
            </div>
          </div>
        `,
        confirmButtonText: '确认支付',
        cancelButtonText: '取消',
        showCancelButton: true,
        showConfirmButton: true,
        allowHtml: true
      }).then(() => {
        // 调用支付接口
        this.requestAliPay(selectedOption)
      }).catch(() => {
        // 取消支付
      })
    },
    
    // 请求支付宝支付
    async requestAliPay(product) {
      // 显示加载提示
      this.isLoading = true
      this.$toast.loading({
        message: '正在发起支付...',
        forbidClick: true,
        duration: 0
      })
      
      try {
        // 获取平台类型
        const platform = getPlatformType()
        
        // 构建支付参数
        const payData = {
          userId: this.userInfo.id,
          productId: product.id
        }
        
        // 调用支付宝H5支付接口
        const res = await aliPayH5(payData, platform)
        this.$toast.clear()
        this.isLoading = false
        
        // 处理HTML表单响应
        if (typeof res === 'string' && res.includes('<form')) {
          // 创建一个div来放置表单
          const div = document.createElement('div')
          div.innerHTML = res
          document.body.appendChild(div)
          
          // 自动提交表单
          setTimeout(() => {
            const form = div.querySelector('form')
            if (form) {
              form.submit()
            } else {
              this.$toast.fail('支付表单加载失败')
            }
          }, 100)
        } else {
          this.$toast.fail('获取支付表单失败')
        }
      } catch (error) {
        this.$toast.clear()
        this.isLoading = false
        console.error('支付请求失败:', error)
        this.$toast.fail('支付请求失败，请重试')
      }
    },
    
    // 处理支付成功
    handlePaymentSuccess() {
      console.log('支付成功')
      this.$toast.success('支付成功')
      window.location.href = 'https://gbyy91.com/pay'
    },
    
    // 处理支付失败
    handlePaymentFailure(message) {
      console.error('支付失败:', message)
      this.$toast.fail(message || '支付失败，请重试')
    },
    
    // 处理支付取消
    handlePaymentCancel() {
      console.log('用户取消支付')
      this.$toast('支付已取消')
    }
  }
}
</script>

<style scoped>
.recharge-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #F5F7FA;
  padding-bottom: 10px;
  position: relative;
  overflow: hidden;
}

/* 顶部标题样式 */
.page-header {
  padding: 5px 16px 0;
  display: flex;
  align-items: center;
  margin-bottom: 0;
}

.header-content {
  display: flex;
  align-items: center;
  width: 100%;
}

.logo-wrapper {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  width: 100%;
}

.logo-container {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.logo-image {
  width: 60px;
  height: 60px;
  object-fit: contain;
}

/* 页面标题样式 */
.page-title {
  text-align: center;
  margin-bottom: 5px;
}

.page-title h1 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

/* 用户信息样式 */
.user-info-section {
  padding: 0 8px;
  margin-top: 0;
  margin-bottom: 5px;
}

.user-info-card {
  background-color: #fff;
  border-radius: 12px;
  padding: 8px;
  display: flex;
  align-items: center;
  position: relative;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.user-avatar {
  margin-right: 10px;
  position: relative;
}

.avatar, .avatar-placeholder {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  background-color: #f2f2f2;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid #F5EEFF;
}

.user-details {
  flex: 1;
}

.user-name {
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 4px;
  color: #333;
}

.user-id {
  font-size: 12px;
  color: #666;
  display: flex;
  align-items: center;
  background-color: #F5F5F5;
  padding: 2px 8px;
  border-radius: 12px;
  display: inline-flex;
}

.id-icon {
  width: 14px;
  height: 14px;
  margin-right: 4px;
}

.switch-account-btn {
  background-color: #B66FFF;
  color: white;
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 12px;
  position: absolute;
  right: 12px;
  cursor: pointer;
  box-shadow: 0 2px 6px rgba(182, 111, 255, 0.3);
}

/* 充值金额样式 */
.recharge-section {
  padding: 0 8px;
  margin-bottom: 5px;
}

.section-title {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 5px;
  color: #333;
}

.recharge-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  padding: 0 2px;
}

.recharge-item {
  background-color: #F0F0F0;
  border-radius: 8px;
  padding: 8px 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid #DDDDDD;
  position: relative;
  overflow: hidden;
}

.recharge-item.active {
  background-color: #F5EEFF;
  border: 1px solid #B66FFF;
  transform: scale(1.02);
  box-shadow: 0 2px 8px rgba(182, 111, 255, 0.2);
}

.recharge-item.active:before {
  content: "";
  position: absolute;
  top: 0;
  right: 0;
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 0 20px 20px 0;
  border-color: transparent #B66FFF transparent transparent;
}

.recharge-item.active:after {
  content: "✓";
  position: absolute;
  top: 0;
  right: 3px;
  color: white;
  font-size: 10px;
  font-weight: bold;
}

.diamond-icon {
  margin-bottom: 3px;
}

.diamond-img {
  width: 20px;
  height: 20px;
  object-fit: contain;
}

.recharge-amount {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 1px;
}

.recharge-price {
  font-size: 12px;
  color: #666;
}

/* 支付方式样式 */
.payment-section {
  padding: 0 8px;
  margin-bottom: 5px;
  background-color: #fff;
  border-radius: 12px;
  margin-left: 8px;
  margin-right: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.payment-option {
  display: flex;
  align-items: center;
  padding: 8px;
  border-bottom: 1px solid #EAEAEA;
}

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

.alipay-icon {
  width: 28px;
  height: 28px;
  object-fit: contain;
}

.payment-name {
  flex: 1;
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.payment-selected {
  display: flex;
  align-items: center;
  justify-content: center;
}

.check-icon {
  width: 20px;
  height: 20px;
  object-fit: contain;
}

/* 温馨提示样式 */
.tips-section {
  padding: 8px 12px;
  margin: 0 8px 5px;
  background-color: #f8f8f8;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.tips-title {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
}

.tips-content {
  margin-bottom: 4px;
}

.tip-item {
  font-size: 12px;
  color: #666;
  margin-bottom: 6px;
  line-height: 1.5;
}

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

.agreement-checkbox {
  display: flex;
  align-items: center;
  margin-top: 5px;
  cursor: pointer;
}

.checkbox-wrapper {
  width: 16px;
  height: 16px;
  border: 1px solid #ddd;
  border-radius: 3px;
  margin-right: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.checkbox-wrapper.checked {
  background-color: #B66FFF;
  border-color: #B66FFF;
}

.agreement-text {
  font-size: 12px;
  color: #666;
}

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

/* 协议弹框样式 */
.agreement-content {
  padding: 10px;
  height: 60vh;
  overflow: hidden;
}

.agreement-iframe {
  width: 100%;
  height: 100%;
  border: none;
}

/* 支付按钮样式 */
.pay-button {
  padding: 0 8px;
  margin-top: auto;
  margin-bottom: 5px;
}

.pay-button .van-button {
  background-color: #B66FFF;
  border: none;
  height: 38px;
  font-size: 15px;
  font-weight: 500;
  box-shadow: 0 4px 12px rgba(182, 111, 255, 0.3);
}

/* 二次确认弹窗样式 */
:deep(.custom-dialog1) {
  width: 90%;
  max-width: 300px;
  border-radius: 12px;
  overflow: hidden;
}

:deep(.custom-dialog .van-dialog__header) {
  padding: 15px 0;
  font-weight: 600;
  font-size: 16px;
  color: #333;
}

:deep(.custom-dialog .van-dialog__content) {
  padding: 10px 20px 15px;
  max-height: none;
  overflow: visible;
}

:deep(.confirm-dialog-content) {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

:deep(.confirm-price) {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
}

:deep(.confirm-tip) {
  font-size: 14px;
  color: #333;
  font-weight: 500;
  margin-bottom: 3px;
  text-align: left;
  align-self: flex-start;
}

:deep(.warning-list) {
  width: 100%;
  text-align: left;
  margin-top: 0;
}

:deep(.warning-item) {
  font-size: 13px;
  color: #666;
  margin-bottom: 4px;
  position: relative;
  padding-left: 12px;
}

:deep(.warning-item:before) {
  content: "•";
  position: absolute;
  left: 0;
  color: #666;
}

:deep(.warning-item:last-child) {
  margin-bottom: 0;
}

:deep(.custom-dialog .van-dialog__footer) {
  display: flex;
  border-top: 1px solid #eee;
}

:deep(.custom-dialog .van-button) {
  flex: 1;
  height: 44px;
  font-size: 16px;
  border: none;
  border-radius: 0;
  margin: 0;
}

:deep(.custom-dialog .van-dialog__cancel) {
  color: #333;
}

:deep(.custom-dialog .van-dialog__confirm) {
  color: #f44336;
  font-weight: normal;
}
</style> 