<template>
  <div class="social">
    <div class="top">
      <div class="search_box">
        <img src="/img/search.png" alt="搜索">
        <input type="text" placeholder="搜索商家门店名称" v-model="searchQuery" @input="onSearchInput">
      </div>
    </div>

    <div class="category_box">
      <div class="list_pagebox" ref="listPagebox" @scroll="onScroll">
        <div class="cate_list" ref="cateList">
          <div class="cate_item" :class="{ active: selectedId === '' }" @click="onSelectCategory('')">
            <img src="/img/cate_all.png" alt="全部分类">
            <span>全部分类</span>
          </div>
          <div class="cate_item" v-for="item in categories" :key="item.id" :class="{ active: selectedId === item.id }"
            @click="onSelectCategory(item.id)">
            <img :src="$file(item.img) || '/img/avatar.png'" alt="分类图片">
            <!-- <img src="/img/mall_i15.png" alt=""> -->
            <span>{{ item.name }}</span>
          </div>
        </div>
      </div>
      <div class="contaniar">
        <div class="scroll_progress">
          <div class="progress_thumb" :style="thumbStyle"></div>
        </div>
      </div>

      <van-tabs class="tab" v-model:active="active" type="card" color="#841e36" title-active-color="#fff"
        title-inactive-color="#222" @change="onTabChange">
        <van-tab title="离我最近"></van-tab>
        <van-tab title="更大优惠"></van-tab>
      </van-tabs>

      <BaseList class="shoplist" url="/v1/client/DShopsClient/list" :params="searchparams" :auto-load="true">
        <template #default="{ item }">
          <div class="shopitem" @click="$navigate(`/ShopInfo?id=${item.userid}`)">
            <div class="top_box">
              <img :src="$file(item.shopimg) || '/img/avatar.png'" alt="商户图片">
              <div class="info_box">
                <div class="name_box">
                  <b>{{ item.shopname }}</b>
                  <span class="type">{{ item.shopcatename }}</span>
                </div>
                <div class="tags">
                  <div class="disc_box"><img src="/img/icon_disc.png" alt="">{{ item.feeratio }}%</div>
                  <div class="canpay_box" v-if="item.enabled"><img src="/img/icon_canpay.png" alt="">可到店消费</div>
                </div>
              </div>
            </div>
            <div class="addr_box">
              <span class="addr">
                {{ item.shopprovince + item.shopcity + item.shopcounty }}{{ item.shopstreet }}{{ item.shopaddress }}
              </span>
              <span class="distance"><img src="/img/addr_r.png" alt="">{{ (item.distance / 1000)?.toFixed(2)
              }}km</span>
            </div>
          </div>
        </template>
      </BaseList>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Social',
  data() {
    return {
      searchQuery: '',
      scrollPercent: 0,
      noScroll: true,
      selectedId: '',
      active: 0,
      categories: [],
      searchparams: {
        latitude: localStorage.getItem('user_latitude') || 29.309300,
        longitude: localStorage.getItem('user_longitude') || 120.070380,
        shopcateid: '',
        orderby: '',
        shopname: '',
      },
    }
  },
  mounted() {
    this.initLocation();
    this.init();
    this.$nextTick(() => {
      this.checkScroll();
      const ro = new ResizeObserver(() => this.checkScroll());
      ro.observe(this.$refs.cateList);
    });
  },
  computed: {
    thumbStyle() {
      if (this.noScroll) {
        return { width: '100%', transform: 'none' };
      }
      return { transform: `translateX(${this.scrollPercent}vw)` };
    },
  },
  watch: {
    active(val) {
      this.searchparams.orderby = val === 1 ? 'feeratio' : '';
    },
  },
  methods: {
    init() {
      Promise.all([
        this.$get('/v1/client/dshopcatesclient').then(res => {
          this.categories = res.data
        })
      ]).catch(err => {
        console.error('初始化失败:', err)
      })
    },
    onSelectCategory(id) {
      this.selectedId = id;
      this.searchparams.shopcateid = id;
    },
    onTabChange(val) {
      this.searchparams.orderby = val === 1 ? 'feeratio' : '';
    },
    onScroll() {
      const el = this.$refs.listPagebox
      if (!el) return
      const maxScroll = el.scrollWidth - el.clientWidth
      this.noScroll = maxScroll <= 0
      if (this.noScroll) {
        this.scrollPercent = 0
        return
      }
      const rawPercent = maxScroll > 0 ? (el.scrollLeft / maxScroll) * 15 : 0
      this.scrollPercent = Math.max(0, Math.min(rawPercent, 15))
    },
    checkScroll() {
      const el = this.$refs.cateList;
      const parent = this.$refs.listPagebox;
      if (!el || !parent) return;
      this.noScroll = el.scrollWidth <= parent.clientWidth;
    },
    onSearchInput() {
      this.searchparams.shopname = this.searchQuery;
    },
    initLocation() {
      // if (wx && this.$isWechat()) {
      //   this.$post('/v1/client/HWxinfoClient/share', JSON.stringify(location.href)).then(res => {
      //     const data = res.data || {};
      //     const jsApiList = data.jsApiList || ['getLocation'];
      //     const openTagList = data.openTagList || ['wx-open-launch-weapp'];
      //     jsApiList.push('wx-open-launch-weapp');
      //     wx.config({
      //       debug: false,
      //       appId: data.appid,
      //       timestamp: Number(data.timestamp) || 0,
      //       nonceStr: data.noncestr,
      //       signature: data.signature,
      //       jsApiList: jsApiList,
      //       openTagList: openTagList
      //     });
      //     wx.ready(() => {
      //       wx.getLocation({
      //         type: 'gcj02',
      //         success: (e) => {
      //           this.searchparams.latitude = e.latitude;
      //           this.searchparams.longitude = e.longitude;
      //         },
      //         fail: (err) => {
      //           console.log('定位失败:', err)
      //           // this.$showToast('定位被拒绝，请重新进入页面获取定位')
      //         },
      //       });
      //     });
      //     wx.error((e) => {
      //       if (localStorage.getItem('latitude') && localStorage.getItem('longitude')) {
      //         this.searchparams.latitude = localStorage.getItem('latitude');
      //         this.searchparams.longitude = localStorage.getItem('longitude');
      //         return
      //       } else {
      //         this.$geo.getWebGeo().then(res => {
      //           this.searchparams.latitude = res.lat;
      //           this.searchparams.longitude = res.lon;
      //         });
      //       }
      //     });
      //   });
      // } else {

      // }

      if (!this.$isWechat()) {
        this.$geo.getWebGeo().then(res => {
          this.searchparams.latitude = res.lat;
          this.searchparams.longitude = res.lon;
        });
      }
    },
  },
}
</script>