<template>
  <div class="search-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 v-if="isLoggedIn" class="search-container">
      <div class="search-input-card">
        <div class="search-input">
          <van-field v-model="searchValue" placeholder="搜索Id号码" clearable class="user-search-field" />
          <van-button type="primary" class="search-btn" @click="onSearch">搜索</van-button>
        </div>
      </div>
    </div>

    <!-- 未登录提示 -->
    <div v-if="!isLoggedIn" class="login-prompt-section">
      <div class="login-prompt-card">
        <div class="prompt-text">请先完成登录后，即可进行钻石充值~</div>
      </div>
    </div>

    <!-- 充值金额选择 -->
    <div class="recharge-section">
      <h2 class="section-title">充值金额</h2>

      <div class="recharge-grid">
        <div v-for="(item, index) in coinOptionsWithCustom" :key="index" class="recharge-item"
          :class="{ active: selectedRecharge === index, disabled: !isLoggedIn }"
          @click="isLoggedIn ? selectRecharge(index) : null">
          <div class="diamond-icon">
            <img src="@/assets/images/recharge_zuanshi.png" alt="钻石" class="diamond-img" />
          </div>
          <template v-if="!item.isCustom">
            <div class="recharge-amount">{{ item.amount }}</div>
            <div class="recharge-price">¥{{ item.price }}</div>
          </template>
          <template v-else>
            <div class="recharge-amount">自定义金额</div>
            <div class="recharge-price">点击输入</div>
          </template>
        </div>
      </div>

      <div v-if="isCustomSelected" class="custom-input">
        <van-field v-model="customAmount" type="number" input-align="center" placeholder="请输入自定义金额(元)" clearable
          :disabled="!isLoggedIn" />
      </div>
    </div>

    <!-- 支付方式 -->
    <div v-if="isLoggedIn" 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 v-if="!isLoggedIn" class="login-button">
      <van-button type="primary" block round @click="goToLogin">立即登录</van-button>
    </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" :class="{ disabled: !isLoggedIn }" @click="isLoggedIn ? toggleAgreement() : null">
        <div class="checkbox-wrapper" :class="{ checked: agreementChecked, disabled: !isLoggedIn }">
          <van-icon v-if="agreementChecked" name="success" size="14" color="#fff" />
        </div>
        <div class="agreement-text">
          我已阅读并同意 <span class="agreement-link" @click.stop="isLoggedIn ? showAgreement() : null">《用户充值协议》</span>
        </div>
      </div>
    </div>

    <!-- 支付按钮 -->
    <div v-if="isLoggedIn" 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>
import { getProductList } from '@/api/product'
import { getUserInfo } from '@/api/user'
import { getPlatformType, getDevicePayWayId } from '@/utils/config'

export default {
  name: 'SearchPage',
  data() {
    return {
      tianyongchao: '',
      copyData: '',
      userCode: '',
      searchValue: '',
      coinOptions: [],
      selectedRecharge: 0,
      paymentMethod: 'alipay',
      agreementChecked: false,
      agreementVisible: false,
      // 自定义金额
      customAmount: '',
      // 登录状态
      isLoggedIn: false
    }
  },
  created() {
    // 获取产品列表
    this.fetchProductList()
  },
  computed: {
    selectedRechargeOption() {
      return this.coinOptionsWithCustom[this.selectedRecharge] || null
    },
    // 显示列表 = 产品列表 + 自定义
    coinOptionsWithCustom() {
      return [...(this.coinOptions || []), { isCustom: true }]
    },
    // 是否选择了自定义
    isCustomSelected() {
      return this.selectedRecharge === this.coinOptionsWithCustom.length - 1
    }
  },
  methods: {
    // 获取产品列表
    async fetchProductList() {
      try {
        const payWayId = getDevicePayWayId()
        const res = await getProductList(payWayId)
        this.coinOptions = res.data || []
      } catch (error) {
        console.error('获取产品列表失败:', error)
        // 设置默认数据，以防接口调用失败
        this.coinOptions = [
          { 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 }
        ]
      }
    },
    async onSearch() {
      if (!this.searchValue) {
        this.$toast('请输入用户ID')
        return
      }

      try {
        // 显示加载提示
        this.$toast.loading({
          message: '搜索中...',
          forbidClick: true,
          duration: 0
        })

        // 从接口获取用户信息
        const res = await getUserInfo(this.searchValue)
        this.$toast.clear()

        if (res.data && res.data.userId) {
          // 设置登录状态为已登录
          this.isLoggedIn = true
          // 跳转到充值页面，并传递用户信息
          this.$router.push({
            path: '/recharge',
            query: {
              id: res.data.userId,
              nickname: res.data.userName,
              avatar: res.data.avatar
            }
          })
        } else {
          // 设置登录状态为未登录
          this.isLoggedIn = false
          this.$toast('未找到该用户')
        }
      } catch (error) {
        this.$toast.clear()
        // 设置登录状态为未登录
        this.isLoggedIn = false
        console.error('获取用户信息失败:', error)
        this.$toast('搜索用户失败，请重试')
      }
    },
    selectRecharge(index) {
      this.selectedRecharge = index
    },
    // 切换协议勾选状态
    toggleAgreement() {
      this.agreementChecked = !this.agreementChecked
    },
    // 显示协议弹框
    showAgreement() {
      this.agreementVisible = true
    },
    confirmPay() {
      if (!this.searchValue) {
        this.$toast('请先搜索用户')
        return
      }

      // 检查协议是否勾选
      if (!this.agreementChecked) {
        this.$toast('请阅读并同意充值协议')
        return
      }

      // 自定义金额校验
      if (this.isCustomSelected) {
        const amountNumber = Number(this.customAmount)
        if (!this.customAmount || Number.isNaN(amountNumber) || amountNumber <= 0) {
          this.$toast('请输入有效的自定义金额')
          return
        }
      }

      const selectedOption = this.selectedRechargeOption
      const priceToShow = selectedOption && selectedOption.isCustom
        ? (Number(this.customAmount) || 0)
        : (selectedOption?.price || 0)

      // 使用二次确认弹窗
      this.$dialog.confirm({
        title: '支付确认',
        message: `
          <div class="confirm-dialog-content">
            <div class="confirm-price">¥${priceToShow}</div>
            <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,
        className: 'custom-dialog',
        allowHtml: true
      }).then(() => {
        // 继续搜索并支付流程
        this.onSearch()
      }).catch(() => {
        // 取消支付
      })
    },
    // 跳转到登录页面
    goToLogin() {
      this.$router.push('/login')
    }
  }
}
</script>

<style scoped>
.search-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;
}

/* 搜索框样式 */
.search-container {
  padding: 0 8px;
  margin-top: 0;
  margin-bottom: 5px;
}

.search-input-card {
  background-color: #fff;
  border-radius: 12px;
  padding: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.search-input {
  display: flex;
  align-items: center;
  margin-top: 0;
  background-color: transparent;
  border-radius: 0;
  padding: 0;
  box-shadow: none;
}

.user-search-field {
  flex: 1;
  background-color: #F5F5F5;
  border-radius: 30px;
  margin-right: 10px;
  height: 38px;
  display: flex;
  align-items: center;
}

.user-search-field :deep(.van-field__control) {
  height: 38px;
  min-height: 38px;
  text-align: left;
  padding-left: 15px;
  padding-right: 0;
  font-size: 14px;
  color: #999;
  line-height: 38px;
}

.user-search-field :deep(.van-field__placeholder) {
  text-align: left;
  width: 100%;
  padding-left: 15px;
  color: #999;
  line-height: 38px;
}

.search-btn {
  height: 38px;
  line-height: 38px;
  border-radius: 20px;
  background-color: #B66FFF;
  border: none;
  padding: 0 15px;
  font-size: 14px;
  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;
}

.custom-input {
  margin-top: 8px;
  padding: 0 2px;
}

/* 支付方式样式 */
.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);
}

/* 立即登录按钮样式 */
.login-button {
  padding: 0 8px;
  margin-bottom: 15px;
}

.login-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-dialog) {
  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 20px;
}

: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: 5px;
  position: relative;
  padding-left: 12px;
}

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

: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;
}

/* 未登录提示样式 */
.login-prompt-section {
  margin: 15px;
  margin-bottom: 20px;
}

.login-prompt-card {
  background: linear-gradient(135deg, #fff3cd 0%, #ffeaa7 100%);
  border: 1px solid #ffeaa7;
  border-radius: 12px;
  padding: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(255, 234, 167, 0.3);
}

.prompt-text {
  font-size: 14px;
  color: #856404;
  font-weight: 500;
}

/* 禁用状态样式 */
.recharge-item.disabled {
  opacity: 0.5;
  pointer-events: none;
}

.checkbox-wrapper.disabled,
.agreement-checkbox.disabled {
  opacity: 0.5;
  pointer-events: none;
}
</style>