<template>
  <div style="--van-popup-background:transparent;--van-cell-background:transparent;">
    <van-popup :show="showPop" :position="'bottom'" :style="{ padding: '0' }">
      <div class="pt60 relative">
        <div class="bg-fff ulib-rt20 inner30">
          <h3 class="text-center font-34">领取补贴券</h3>
          <div class="mt20">
            <CouponItem
                :price-num="coupons.price"
                :desc-left="coupons.getNun>0?'已有' + coupons.getNun + '人领取':''"
                :title="coupons.typeCn"
                :desc-right="detail.discounts2"
                :is-active="true"
            />
          </div>
          <!--
          <div v-if="coupons.bizTip" class="text-center mt25 font-26 color-b35a5a" style="color:#b35a5a;">
            <p @click.stop="handleShowStores">{{coupons.bizTip}} <van-icon name="arrow" /></p>
          </div>
          -->
          <div class="pop-form mt5">
            <div class="bg-f2 ulib-r750 inner5 mt30">
              <van-field v-model="mobile" label="" placeholder="请输入您的常用手机号码"/>
            </div>
            <div class="bg-f2 ulib-r750 inner5 mt30">
              <van-field v-model="code" label="" placeholder="验证码" maxlength="4" type="number" inputmode="numeric">
                <template #button>
                  <span v-if="!is_show_count" @click.stop="getSmsCode"
                        class="text-color-theme font-26">发送验证码</span>
                  <van-count-down class="color-ccc font-26" v-else :time="count_time" format="ss 秒后重发"
                                  @finish="onCountFinish"/>
                </template>
              </van-field>
            </div>
            <div class="text-center font-24 mt30">领取即同意
              <span v-for="(item,index) in item_pop_bottom_info" :key="index" class="color-184ebb"
                    @click="showPopContent(item)">{{ item.title }}</span></div>
            <div class="mt30">
              <van-button round type="danger" :disabled="!(mobile && code)" block class="w100"
                          @click.stop="bindPostCoupon">立即领取
              </van-button>
            </div>
          </div>
        </div>
        <div class="absolute right-0 top-0 mr20" :style="{'margin-top': 0/7.5+'vw'}">
          <van-icon @click="handleClose" name="close" color="#fff" size="24"/>
        </div>
      </div>
    </van-popup>
    <PopContent :content="content" :show-pop="showContentPop" @update:show-pop="showContentPop = $event"/>
    <van-dialog v-model:show="showConfirm" confirmButtonColor="#f84803">
      <div class="mt40 text-color-theme inner10 text-center font-26">
        <div>补贴名额有限，抓紧时间领取吧!</div>
        <div class="mt10">有任何疑问可添加车管家的微信进行咨询~</div>
      </div>
      <div class="text-center">
        <!--
        <van-swipe class="van-swipe" :autoplay="3000">
          <van-swipe-item v-for="(image, index) in qrImages" :key="index">
            <van-image fit="cover" style="width:150px;height:150px" :src="image" />
          </van-swipe-item>
        </van-swipe>
        -->
        <div>
          <van-image fit="cover" style="width:150px;height:150px" :src="qrImage"/>
        </div>
        <!--
       <vue-qrcode class="qrcode" value="https://example.com"/>
       <vue-qrcode class="qrcode" value="https://example.com"/>
       <vue-qrcode class="qrcode" value="https://example.com"/>
       -->
      </div>
    </van-dialog>

  </div>
</template>


<script setup>
import { ref, reactive, defineEmits, watch } from 'vue'
import CouponItem from '@/components/CouponItem.vue' // 导入CouponItem组件
import PopContent from '@/components/PopContent.vue' // 导入PopContent组件
import api from '@/utils/api' // 导入API模块
import { showToast, showDialog, Lazyload, Swipe, SwipeItem } from 'vant' // 导入Toast组件
import { getBasicConfig } from '@/utils/basicSetting'
import VueQrcode from 'vue-qrcode' // 直接导入

const emit = defineEmits(['update:showPop', 'showStorePop'])
defineOptions({
  name: 'PopGetAllowance'
})
// 定义props（Vue3推荐使用defineProps宏）
const props = defineProps({
  showPop: { type: Boolean, default: false }, // 控制弹窗的显示和隐藏
  coupons: { type: Object, default: () => ({}) }, // 补贴信息
  detail: { type: Object, default: () => ({}) }, // 补贴信息
  cityInfo: { type: Object, default: () => ({}) }, // 城市信息
})
// Ensure slot 'value' is called inside template/render function
const mobile = ref('')
const code = ref('')
const is_show_count = ref(false)
const count_time = ref(60000)
const showConfirm = ref(false)
const qrImages = ref([
  'https://img.liche.cn/space/agent/admin/202509/p_56bb15d5873104537cd529832fb8521b.png',
  'https://img.liche.cn/space/agent/admin/202509/p_bdce5bb61375127d3dc9f51ee7519fa3.png',
  'https://img.liche.cn/space/agent/admin/202509/p_cf960a64eb62c7aa3cd25a3e81f9fe2d.png'
])
const qrImage = ref('')
//随机取一张qrImages图片
qrImage.value = qrImages.value[Math.floor(Math.random() * qrImages.value.length)]

watch(() => props.showPop, async (val) => {
  console.log('showPop', val)
  if (val) {
    await getBottomInfoAgreeMent()
  }
})

/**
 * 验证手机号格式
 * @param {string} phone - 手机号
 * @returns {boolean} - 是否是有效的手机号
 */
const validateMobile = (phone) => {
  const reg = /^1[3-9]\d{9}$/
  return reg.test(phone)
}


/**
 * 获取短信验证码
 */
const getSmsCode = async () => {
  // 验证手机号
  if (!mobile.value) {
    showToast('请输入手机号')
    return
  }

  if (!validateMobile(mobile.value)) {
    showToast('请输入正确的手机号格式')
    return
  }

  try {
    // 调用获取验证码接口
    const result = await api.post('/auto/sms', { mobile: mobile.value })

    if (result.code === 200) {
      showToast('验证码发送成功')
      // 开始倒计时
      showCount()
    } else {
      showToast(result.message || '验证码发送失败')
    }
  } catch (error) {
    console.error('获取验证码失败:', error)
    showToast('获取验证码失败，请稍后重试')
  }
}

// 防双击状态
const isSubmitting = ref(false)

const bindPostCoupon = async () => {
  // 防双击检查
  if (isSubmitting.value) {
    return
  }

  if (!mobile.value) {
    showToast('请输入手机号')
    return
  }

  if (!validateMobile(mobile.value)) {
    showToast('请输入正确的手机号格式')
    return
  }

  if (!code.value) {
    showToast('请输入验证码')
    return
  }

  // 设置提交状态
  isSubmitting.value = true

  ///auto/car/coupon
  try {
    const result = await api.post('/auto/car/coupon', {
      mobile: mobile.value,
      code: code.value,
      couponId: props.coupons.coupon_id,
      cityId: props.cityInfo.cityId
    })
    if (result.code === 200) {
      if(result.data && result.data.Authorization){ //重新设置token
        localStorage.setItem('token', result.data.Authorization)
      }
      handleSuccess()
    } else {
      showToast(result.message || '补贴领取失败')
    }
  } catch (error) {
    console.error('补贴领取失败:', error)
    showToast('补贴领取失败，请稍后重试')
  } finally {
    // 重置提交状态
    isSubmitting.value = false
  }
}


const showContentPop = ref(false)

const content = ref('')
const item_pop_bottom_info = ref([])
const getBottomInfoAgreeMent = async () => {
  item_pop_bottom_info.value = await getBasicConfig('item_bottom')
}

const showPopContent = (item) => {
  content.value = item.content
  showContentPop.value = true
}

function handleSuccess() {
  emit('update:showPop', false)
  emit('success', true)
}

// 方法直接定义在script setup中（示例，根据业务需求补充逻辑）
function handleClose() {
  // 关闭弹窗逻辑
  console.log('close')
  showConfirm.value = true
  emit('update:showPop', false)
}

function showCount() {
  is_show_count.value = true
  count_time.value = 60000
}

function onCountFinish() {
  is_show_count.value = false
}

function handleShowStores() {
  emit('showStorePop', true)
}

</script>


<style>
.van-swipe {
  transform: translateZ(0);
}
</style>