<template>
  <div class="detail-page relative" style="min-height: 100vh;">
    <van-loading v-if="loading" class="loading-center" size="24px" vertical>加载中...</van-loading>

    <template v-else-if="productDetail">
      <div class="detail-banner relative">
        <van-swipe :autoplay="3000" lazy-render>
          <van-swipe-item v-for="(item,index) in banner_list" :key="index">
            <van-image fit="cover" :style="'width:100%;height:'+Number(550/7.5)+'vw;'" :src="item.img"/>
          </van-swipe-item>
        </van-swipe>
        <div class="wp100 absolute pt140 left-0 right-0 bottom-0"
             style="background-image: linear-gradient(to top, rgba(255,255,255,1),rgba(255,255,255,0));"
        ></div>
      </div>
      <div class="detail-info ml30 mr30 relative" :style="{'margin-top':Number(-60/7.5)+'vw'}">
        <div class="ulib-r20 bg-fff inner30 box-shadow-darkGray">
          <div class="fn-flex fn-flex-center">
            <div class="mr20">
              <van-image class="imgsize-200X152" radius="10px" :src="productDetail.banner"/>
            </div>
            <div class="fn-flex-item fn-flex fn-flex-column justify-between">
              <div class="fn-flex fn-flex-center justify-between">
                <div class="wp60 font-30 line-clamp-1">{{ productDetail.title }}</div>
                <div class="tag fn-flex fn-flex-wrap">
                  <van-tag
                      v-for="(tag, index) in productDetail.carProductLabel"
                      :key="index"
                      class="ml5"
                      color="#f0f0f0"
                      round
                      text-color="#666666"
                  >
                    {{ tag }}
                  </van-tag>
                </div>
              </div>
              <div class="mt15 line-clamp-1 color-666"><p class="font-26">指导价：{{ productDetail.guide_price }}</p>
              </div>
              <div class="fn-flex mt20" v-if="productDetail.discounts">
                <div class="text-color-theme font-24 fn-flex fn-flex-center">
                  <div><i class="icon-custom icon-gift mr5"></i></div>
                  <span class="line-clamp-1">{{ productDetail.discounts3 }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="detail-coupon ml30 mr30 pt45" v-if="productDetail.coupons&&productDetail.coupons.show">
        <CouponItem
            :price-num="productDetail.coupons.price"
            :desc-left="productDetail.coupons.getNun>0?'已有' + productDetail.coupons.getNun + '人领取':''"
            :title="productDetail.coupons.typeCn"
            :desc-right="productDetail.discounts2"
            :is-active="true"
        />
      </div>
      <div class="detail-content ml30 mr30 mt40 pb40">
        <van-tabs v-model:active="content_active" animated color="#f5500b" line-width="20px">
          <van-tab v-for="(item,index) in content_list" :key="index" :title="item.title">
            <div class="pt20 font-26 color-666" style="line-height: 1.7;" v-html="item.content"></div>
          </van-tab>
        </van-tabs>
      </div>

      <div class="wp100 pb200"></div>
      <div class="detail-footer fixed left-0 bottom-0 right-0">
        <div v-if="productDetail.coupons&&productDetail.coupons.show" style="background-color:#fff4f4;" class="inner20">
          <div v-if="btn_info.status==1" class="text-center text-middle">
            <van-count-down :time="count_time">
              <template #default="timeData">
                <span class="count-down-colon">倒计时</span>
                <span v-if="timeData.days!=0"
                      class="count-down-block">{{ (timeData.days > 9) ? '' : '0' }}{{ timeData.days }}</span>
                <span v-if="timeData.days!=0" class="count-down-colon">天</span>
                <span class="count-down-block">{{ (timeData.hours > 9) ? '' : '0' }}{{ timeData.hours }}</span>
                <span class="count-down-colon">时</span>
                <span class="count-down-block">{{ (timeData.minutes > 9) ? '' : '0' }}{{ timeData.minutes }}</span>
                <span class="count-down-colon">分</span>
                <span class="count-down-block">{{ (timeData.seconds > 9) ? '' : '0' }}{{ timeData.seconds }}</span>
                <span class="count-down-colon">秒</span>
              </template>
            </van-count-down>
          </div>
          <div v-else class="text-center font-28 text-color-theme">{{ btn_info.tip }}</div>
          <div class="pt20 ml30 mr30">
            <van-button round type="danger" :disabled="btn_info.status!=1" block class="w100"
                        @click.stop="showEnrollPop">{{ btn_info.text }}
            </van-button>
          </div>
        </div>
      </div>
      <PopGetAllowance @update:showPop="handleShowPop" @showStorePop="handleShowStorePop" @success="handleSuccess"
                       :detail="productDetail" :coupons="productDetail.coupons" :cityInfo="cityInfo"
                       :show-pop="showPop"/>
      <PopStores @update:showPop="handleShowStorePop" :show-pop="showStorePop" :coupons="productDetail.coupons"
                 :id="productDetail.coupons.coupon_id"/>
      <SideMenu/>
    </template>

    <template v-else>
      <div class="empty-data text-center pt100">
        <van-empty description="暂无产品详情"/>
      </div>
    </template>


  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'

import { useRoute } from 'vue-router'
import api from '@/utils/api'
import { trackEvent } from '@/utils/analytics'
import CouponItem from '@/components/CouponItem.vue'
import PopGetAllowance from '@/components/PopGetAllowance.vue'
import PopStores from '@/components/PopStores.vue'
import SideMenu from '@/components/SideMenu.vue' // 导入SideMenu组件
import { showDialog, showToast } from 'vant' // 导入Toast组件
import WechatUtils, { WechatAuth, WechatLocation, WechatShare } from '@/utils/wechat'
import { useUserStore } from '@/stores/user'
// 导入 cookie 工具
import { getCurrentInstance } from 'vue'
import { getUserLocation, getCityInfo, cacheLocationInfo } from '@/utils/location'

const { proxy } = getCurrentInstance()

// 获取路由参数
const route = useRoute()
const productId = ref(route.params.id)

// 产品详情数据
const productDetail = ref(null)
const loading = ref(true)

// 定义tabs激活状态（初始值根据业务需求设置，示例为'1'）
const content_active = ref('1')

const count_time = ref(0)
const content_list = ref([])

const banner_list = ref([])

const btn_info = ref({})
//是否绑定手机号
const bindMobile = ref(false)


// 获取产品详情
async function getProductDetail() {
  try {
    loading.value = true
    const res = await api.wechatAPI.getProductDetail(productId.value)
    if (res.code === 200 && res.data) {
      productDetail.value = res.data
      if (productDetail.value.bindMobile) {
        bindMobile.value = true
      }
      // 更新轮播图数据
      banner_list.value = productDetail.value.imgs.map((img, index) => ({
        img,
        id: index
      }))

      // count_time.value = res.data.timeEnd
      count_time.value = Number(30 * 24 * 60 * 60 * 1000)

      btn_info.value = productDetail.value.coupons.btn_info

      // 更新内容标签页数据
      content_list.value = [
        {
          title: '活动流程',
          content: productDetail.value.coupons?.activityProcess || '暂无内容'
        },
        {
          title: '使用规则',
          content: productDetail.value.coupons?.rule || '暂无内容'
        },
        {
          title: '审核标准',
          content: productDetail.value.coupons?.checkStandard || '暂无内容'
        },
        {
          title: '常见问题',
          content: productDetail.value.coupons?.FAQ || '暂无内容'
        }
      ]
    } else {
      console.error('获取产品详情失败:', res.message)
    }
  } catch (error) {
    console.error('获取产品详情异常:', error)
  } finally {
    loading.value = false
  }
}

function handleSuccess() {
  showDialog({
    title: '领取成功',
    message: '稍后会有电话客服与您联系，\n协助您完成补贴申领。',
    confirmButtonColor: '#f84803'
  }).then(() => {
  })
  getProductDetail()
}


// 页面加载时获取产品详情
onMounted(async () => {
  let appid = localStorage.getItem('app_id')
  if (appid) {
    const wechat = await WechatUtils.init(appid)
    // 隐藏分享
    await WechatShare.hideAllNonBaseMenuItem()
  }
  await getCurrentLocation()
  getProductDetail()
})

// 监听 路由
watch(() => route.params.id, async (newId, oldId) => {
  if (newId !== oldId) {
    productId.value = newId
    await getProductDetail()
  }
})

const cityInfo = ref({
  cityId: '',
  cityName: ''
})

/**
 * 获取当前位置并解析城市编码
 */
const getCurrentLocation = async () => {
  try {
    /// 微信环境或非微信环境未获取到cityId时使用定位逻辑
    const location = await getUserLocation();
    console.log('经纬度:', location);
    if (!(location && location.latitude && location.longitude)) {
      return;
    }
    cityInfo.value = await getCityInfo(location);
  } catch (error) {
    console.error('获取位置或解析城市失败:', error)
  }
}


const showPop = ref(false)

function handleShowPop(val) {
  showPop.value = val
}

function onCountFinish(e) {
  console.log('onCountFinish', e)
}

// 补充门店弹窗控制变量
const showStorePop = ref(false)
// 补充门店列表数据（示例数据，根据实际业务调整）
// 补充门店弹窗关闭方法
function handleShowStorePop(val) {
  showStorePop.value = val
}

function showEnrollPop() {
  //友盟统计
  trackEvent('coupon', 'CLK', {
    Key_CouponId: productDetail.value.coupons.coupon_id,
    Key_CouponName: productDetail.value.coupons.title,
    Key_Brand: productDetail.value.brandName,
    Key_Series: productDetail.value.seriesName
  })
  // showPop.value=true
  if (WechatAuth.isWechatBrowser()) {
    if (bindMobile.value) {
      getCoupon()
    } else {
      showPop.value = true
    }
  } else {
    if (proxy && proxy.$auth) {
      proxy.$auth.require(() => {
        // 登录成功后执行的代码
        getCoupon()
      })
    }
  }
}

const isSubmitting = ref(false)

const getCoupon = async () => {
  // 设置提交状态
  isSubmitting.value = true
  try {
    const result = await api.post('/auto/car/coupon', {
      couponId: productDetail.value.coupons.coupon_id,
      cityId: cityInfo.value.cityId
    })

    if (result.code === 200) {
      handleSuccess()
    } else {
      showToast(result.message || '补贴领取失败')
    }
  } catch (error) {
    showToast('补贴领取失败，请稍后重试')
  } finally {
    // 重置提交状态
    isSubmitting.value = false
  }
}
</script>

<style scoped>
.count-down-colon {
  display: inline-block;
  margin: 0 4px;
  color: #f00;
}

.count-down-block {
  display: inline-block;
  width: 44px;
  height: 38px;
  color: #fff;
  font-size: 24px;
  text-align: center;
  background-color: #f00;
  border-radius: 8px;
}

.loading-center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

</style>
<style>
.van-overflow-hidden {
  --van-text-color: #f00;
}
</style>