<template>
  <div class="my-page relative" style="min-height: 100vh;">
    <div v-if="is_first_load" class="loading relative">
        <PageInitLoading />
      </div>
    <div v-else class="ml30 mr30 pt30 pb60">
      <van-empty v-if="empty" description="暂无数据" />
      <div v-else-if="!is_show">
        <template v-for="(item, index) in list" :key="index">
          <div class="my-coupon-item box-shadow-darkGray mb30 inner30 ulib-r20">
            <CouponItem
              :price-num="item.price" 
              :desc-left="'使用规则'"
              :is-desc-link="true"
              :title="item.typeCn" 
              :desc-right="item.timeStart+'-'+item.timeEnd"
              :is-active="!Number(item.btText.status)|| Number(item.btText.status)===1"
              :date-rule="item.rule"
              :data-index="index"
              :index="index"
              @goLink="goLink"
            />
            <div class="fn-flex fn-flex-center mt30">
              <div class="fn-flex-item">
                <h4 :class="['font-30',!Number(item.btText.status)?'':'color-666']">{{ item.title }}</h4>
                <p class="font-24 mt15" @click="handleShowStores(item)" v-if="item.btText.status>0">
                  <span class="color-999">{{item.bizTip}}</span>
                  <span v-if="0" :class="[!Number(item.btText.status)?'text-color-theme':'color-999']">5</span>
                  <span v-if="0" :class="[!Number(item.btText.status)?'':'color-666']">家门店</span><van-icon name="arrow" />
                </p>
              </div>
              <div class="ml15 color-fff">
                <van-button :class="['ulib-r100 w10vw',Number(item.btText.status)===1?'':'bg-999']" size="small" :type="Number(item.btText.status)===1?'danger':'info'" round @click.stop="bindShowCode(item)">{{ item.btText.txt }}</van-button>
              </div>
            </div>
          </div>
        </template>
      </div>
      <van-list v-else v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
        <template v-for="(item, index) in list" :key="index">
          <div class="my-coupon-item box-shadow-darkGray mb30 inner30 ulib-r20">
            <CouponItem
              :price-num="item.price"
              :desc-left="'使用规则'"
              :is-desc-link="true"
              :title="item.typeCn"
              :desc-right="item.timeStart+'-'+item.timeEnd"
              :is-active="!Number(item.btText.status)|| Number(item.btText.status)===1"
              :date-rule="item.rule"
              :data-index="index"
              :index="index"
              @goLink="goLink"
            />
            <div class="fn-flex fn-flex-center mt30">
              <div class="fn-flex-item">
                <h4 :class="['font-30',Number(item.btText.status)===1?'':'color-666']">{{ item.title }}</h4>
                <p class="font-24 mt15" @click="handleShowStores(item)">
                  <span class="color-999">{{item.bizTip}}</span>
                  <span v-if="0" :class="[!Number(item.btText.status)?'text-color-theme':'color-999']">5</span>
                  <span v-if="0" :class="[!Number(item.btText.status)?'':'color-666']">家门店</span><van-icon name="arrow" />
                </p>
              </div>
              <div class="ml15 color-fff">
                <van-button :class="['ulib-r100 w10vw',Number(item.btText.status)===1?'':'bg-999']" size="small" :type="Number(item.btText.status)===1?'danger':'info'" round @click.stop="bindShowCode(item)">{{ item.btText.txt }}</van-button>
              </div>
            </div>
          </div>
        </template>
      </van-list>
      <PopCode :title="popCodeTitle" :code="code" :show-pop="showCodePop" @update:show-pop="showCodePop = $event" />
      <PopContent :content="content" :show-pop="showContentPop" @update:show-pop="showContentPop = $event" />
      <PopStores @update:showPop="handleShowStorePop" :show-pop="showStorePop" :coupons="cur_coupons" :id="cur_coupon_id" />
    </div>
    <SideMenu :name="'我的'"/>
  </div>
</template>

<script setup>
import CouponItem from '@/components/CouponItem.vue'
import PopCode from '@/components/PopCode.vue'
import PopContent from '../components/PopContent.vue'
import PopStores from '@/components/PopStores.vue'
import PageInitLoading from '@/components/PageInitLoading.vue'
import SideMenu from '@/components/SideMenu.vue' // 导入SideMenu组件
import WechatUtils,{ WechatShare } from '@/utils/wechat'

import api from '@/utils/api'
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()

const showCodePop = ref(false);
const showContentPop = ref(false);

const popCodeTitle = ref('');
const code = ref('');
const content = ref('');

const list = ref([]);
const loading = ref(false);
const finished = ref(false);
const totalCount = ref(0);
const page  = ref(1);
const empty = ref(false);
const is_show = ref(0)

const is_first_load = ref(true)

onMounted(async () => {
  let appid = localStorage.getItem('app_id')
  if(appid) {
    await WechatUtils.init(appid);
    // 隐藏分享
    await WechatShare.hideAllNonBaseMenuItem();
  }
  await getMyCoupon()
});
const onLoad = async () => {
  await getMyCoupon()
};

const getMyCoupon = async () => {
  loading.value = true;
  try {
    const response = await api.get('/auto/ucenter/coupons', {
      page: page.value,
      size: 20
    });
    
    if (response.code === 200) {
      if (page.value === 1) {
        list.value = [];
        if(response.data.list.length === 0){
          empty.value = true;
        }
      }
      list.value = response.data.list.concat(list.value);
      totalCount.value = response.data.count;
      is_show.value = Number(response.data.show)

      if  (list.value.length >= totalCount.value) {
        finished.value = true;
      }
      page.value++;
    } else {
      showToast(response.message || '获取补贴列表失败');
    }
  } catch (error) {
    console.error('获取补贴列表异常:', error);
    showToast('网络异常，请稍后重试');
  } finally {
    is_first_load.value = false;
    loading.value = false;
  }
};

const goLink = (index) => { 
  content.value = list.value[index].rule;
  showContentPop.value = true;
};
const bindShowCode = (item) => {
  if(Number(item.btText.status)===1){
    let id = item.id;
    router.push({ path: '/my/allowance/form', query: { couponId:id } })
  }
  // code.value = item.sid;
  // popCodeTitle.value = item.title;
  // showCodePop.value = true;
};

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

const handleShowStores = (item) => { 
  cur_coupons.value = item.coupons
  cur_coupon_id.value = item.couponId
  showStorePop.value = true
};
</script>

<style></style>