<template>
  <div style="--van-popup-background:transparent;--van-cell-background:transparent;--van-cell-horizontal-padding:0;">
    <van-popup :show="showPop" :position="'center'" :style="{ padding: '0' }">
      <div class="pt60 relative">
        <div class="bg-fff ulib-r20 inner30" style="width:85vw;">
          <h3 class="text-center font-34">适用门店</h3>
          <div class="mt20">
            <van-field v-model="result" is-link readonly name="area" label="地区选择" placeholder="点击选择省市区"
              @click="showArea = true" >
              <template #extra>
                <span v-if="result" class="ml10 mr10">|</span> <span v-if="result" @click.stop="initList" class="color-999 font-24">清空选择</span>
              </template>
            </van-field>

          </div>
          <div class="mt30" style="height:50vh;overflow-y:auto;">
            <div v-if="empty" class="text-center font-24 color-666">
              <van-empty description="暂无数据" />
            </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="fn-flex">
                  <div><i class="icon-custom icon-map"></i></div>
                  <div class="ml10 fn-flex-item">
                    <h4 class="font-30">{{item.biz_name}}</h4>
                    <p class="color-666 font-24 mt20">{{item.address}}</p>
                  </div>
                  <div class="wp20 text-right" @click.stop="showMapItem(item)">
                    <span class="inline-block imgsize-60X60 relative ulib-r750" style="border:1px solid #333;"><i
                        class="icon-custom icon-loc absolute box-center-middle"></i></span>
                    <p class="font-20 mt5 mr10 color-666">导航</p>
                  </div>
                </div>
                <van-divider v-if="index < list.length - 1" />
              </template>
            </van-list>
          </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>

    <van-popup v-model:show="showArea" destroy-on-close position="bottom">
      <van-area :area-list="areaList" :model-value="pickerValue" :columns-num="2" @confirm="onConfirm" @cancel="showArea = false" />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch } from 'vue'
import { areaList } from '@vant/area-data';
import api from '../utils/api'
import { WechatLocation } from '../utils/wechat'

// 声明组件名称（可选，用于devtools）
defineOptions({ name: 'PopStores' })

// 声明props（Vue 3推荐使用defineProps宏）
const props = defineProps({
  showPop: { type: Boolean, default: false },
  coupons: { type: Object, default: () => ({}) },
  id: { type: [Number, String], default: '' },
})

// 声明emits事件（与子组件通信）
const emit = defineEmits(['update:showPop'])

// 定义方法（直接在script setup中声明）
function handleClose() {
  emit('update:showPop', false)
}

function onCountFinish() {
  emit('update:showPop', false)
}

const initList = async() => {
  // 方法逻辑（根据实际需求补充）
  result.value =''
    provinceId.value = '';
    cityId.value = '';
    page.value = 1;
    finished.value = false;
    loading.value = false;
    empty.value = false;
    await getCouponBizs();
}

watch(() => props.showPop, (val) => {
  if (val) {
    initList();
  }
})

const result = ref('');
const showArea = ref(false);
const pickerValue = ref([]);
const onConfirm = async ({ selectedValues, selectedOptions }) => {
  pickerValue.value = selectedValues.length
    ? selectedValues[selectedValues.length - 1]
    : '';
  showArea.value = false;
  result.value = selectedOptions.map((item) => item.text).join('/');
  provinceId.value = selectedValues[0];
  cityId.value = selectedValues[1];
  page.value = 1;
  finished.value = false;
  loading.value = false;
  empty.value = false;
  await getCouponBizs();
};

const provinceId = ref('');
const cityId = 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 isRequesting = ref(false);

const onLoad = async () => {
  // 异步更新数据
  // setTimeout 仅做示例，真实场景中一般为 ajax 请求
  await getCouponBizs()
};

/** 
 * 请求接口 /auto/car/coupon/bizs
*/
const getCouponBizs = async () => {
  console.log('getCouponBizs',isRequesting.value,finished.value,empty.value);
  if (isRequesting.value || finished.value || empty.value) return;
  isRequesting.value = true;
  loading.value = true;
  try {
    const response = await api.get('/auto/car/coupon/bizs',{
      couponId: props.id,
      page: page.value,
      size: 10,
      ...provinceId? { provinceId: provinceId.value } : {},
      ...cityId? { cityId: cityId.value } : {}
    });
    if (response.code === 200) {
      isRequesting.value = false;
      loading.value = false;
      if (page.value === 1) {
        list.value = [];
        if(response.data.list.length===0){
          empty.value = true;
          finished.value = true;
          return
        }
      }
      if(response.data.list.length===0){
        finished.value = true;
        return
      }
      list.value = response.data.list.concat(list.value);
      totalCount.value = response.data.count;
      
      if  (list.value.length >= totalCount.value) {
        finished.value = true;
        return
      }
      page.value++;
    } else {
      isRequesting.value = false;
      loading.value = false;
      showToast(response.message || '获取补贴列表失败');
    }
    // return response;
  } catch (error) {
    isRequesting.value = false;
    loading.value = false;
    console.error('获取优惠券数据失败:', error);
    return { code: 500, message: '接口请求异常' };
  } finally {
    isRequesting.value = false;
    loading.value = false;
  }
};

/** 
 * 打开微信地图
*/
const showMapItem = (item) => {
  if(item.lat && item.lng){
    WechatLocation.openLocation({
      latitude: parseFloat(item.lat),
      longitude: parseFloat(item.lng),
      name: item.biz_name,
      address: item.address
    });
  }
}

</script>

<style></style>