<template>
  <view class="container" :style="{ marginTop: top + 'px' }" v-if="loading">
    <view class="white_container">
      <!-- 城市信息部分 -->
      <view class="searchBox" :style="{ height: localHeight + 'px' }">
        <view class="searchBox_add" @tap="map">
          <image src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/Index_add.png" mode="widthFix" />
          <view>
            {{ currentCity.cityName || '选择城市' }}
          </view>
        </view>
      </view>
      <!-- 功能导航区 -->
      <view class="function-nav">
        <view class="function-item" @click="goToShop">
          <div class="icon-box">
            <image class="iconImg" src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/index_shop.png"
              mode="widthFix" />
          </div>
          <text>店铺管理</text>
        </view>
        <view class="function-item" @click="goToOrder">
          <div class="icon-box">
            <image class="iconImg" src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/index_order.png"
              mode="widthFix" />
          </div>
          <text>供应商订单</text>
        </view>
        <view class="function-item" @click="goToWuye">
          <div class="icon-box">
            <image class="iconImg" src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/index_wuye.png"
              mode="widthFix" />
          </div>
          <text>物业管理</text>
        </view>
      </view>
      <!-- 搜索框 -->
      <div class="search2" v-if="isShowSearch">
        <div class="searchBox2">
          <image src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/com_communitySearchIcon.png"
            mode="aspectFill"></image>
          <div class="hot-word-container">
            <div class="hot-word-scroll" :style="{ transform: 'translateY(' + scrollPosition + 'px)' }">
              <div v-for="(word, index) in hotWord" :key="index" class="hot-word-item"
                @click="handleHotWordClick(word)">
                {{ word }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 轮播图 -->
      <view class="swiper">
        <swiper @animationfinish="swipers" autoplay circular>
          <swiper-item v-for="(item, index) in bannerList" :key="index" @click="headerServerClick(item)">
            <image :src="item.pic_src" mode="aspectFill" />
          </swiper-item>
        </swiper>

        <view class="cirList">
          <view :class="['cir', currentIdx == index ? 'active' : '']" v-for="(item, index) in bannerList" :key="index">
          </view>
        </view>
      </view>

      <!-- 宫格列表 -->
      <view class="tabList">
        <u-grid :col="rowNum" :border="false">
          <u-grid-item v-for="(item, index) in tabList" @click="headerServerClick(item)" :key="index">
            <image class="grid_Pic" :src="item.icon_src" mode=""></image>
            <text>{{ item.title }}</text>
          </u-grid-item>
        </u-grid>
      </view>
    </view>

    <!-- 广告横幅 -->
    <view class="serverList1">
      <view class="serverList1_left">
        <!-- <image src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/index_ad_left.jpg" mode="aspectFit" /> -->
        <image :src="serverLeft" mode="aspectFit" />
      </view>
      <view class="serverList1_right">
        <view :class="['serverItemRight', `serverItemRight${index + 1}`]" @tap="headerServerClick(item)"
          v-for="(item, index) in serverRightList" :key="index">
          <image :src="item.pic_src" mode="" />
          <!-- <view>{{ item.ad_position }}</view> -->
        </view>
      </view>
    </view>

    <view class="white_container margin_top20 padding_bottom32">
      <view v-if="!currentCity.district" class="Tit">定位错误 未知区域</view>
      <view v-else class="Tit">
        <view class="local">{{ currentCity.district }}</view>附近
        <view class="Tit_desc">公积金补贴商户</view>
      </view>
      <view class="serverList">
        <view class="serverList_left">
          <swiper>
            <swiper-item v-for="(item, index) in homeLeftList" :key="index">
              <image :src="item.pic_src" alt="" mode="aspectFit" />
              <!-- <view>{{ item.ad_position }}</view> -->
            </swiper-item>
          </swiper>
        </view>

        <view class="serverList_right">
          <view class="serverList_right1">
            <view :class="['serverItem', `serverItem${index + 1}`]" @tap="headerServerClick(item)"
              v-for="(item, index) in homeRightList1" :key="index">
              <view class="serverTit">{{ item.title }}</view>
              <image v-if="item.pic_src" :src="item.pic_src" mode="" />
              <!-- <view>{{ item.ad_position }}</view> -->
            </view>
          </view>
          <view class="serverList_right2">
            <view :class="['serverItem', `serverItem${index + 4}`]" @tap="headerServerClick(item)" 
               v-for="(item, index) in homeRightList2" :key="index">
              <view class="serverTit">{{ item.title }}</view>
              <image :src="item.pic_src" mode="" />
              <!-- <view>{{ item.ad_position }}</view> -->
            </view>
          </view>
        </view>
      </view>
      <!-- <view class="merchant" @click="headershopEnterClick">商户申请入驻</view> -->
    </view>

    <!-- <view class="white_container margin_top20 main padding_bottom32">
      <image v-for="(item, index) in bottomList" :key="index" class="list_pic" :src="item.pic_src" mode="">
      </image>
    </view> -->
    <!-- 分类标签栏 -->
    <view class="category-tabs">
      <view class="tabs-container">
        <scroll-view scroll-x enable-flex class="tabs-scroll" :scroll-into-view="activeCategoryId">
          <view class="tab-item" v-for="item in categoryList1" :key="item.id" :id="'category-' + item.id"
            :class="{ activeTab: currentCategoryId === item.id }" @click="switchCategory(item.id)">
            {{ item.cate_name }}
          </view>
        </scroll-view>
        <view class="dropdown-btn" :class="{ active: showDropdown }" @click="toggleDropdown">
          <u-icon v-if="!showDropdown" name="arrow-down" class="dropdown-icon"></u-icon>
          <u-icon v-else name="arrow-up" class="dropdown-icon active"></u-icon>
        </view>
      </view>

      <!-- 分类下拉列表 -->
      <view class="category-dropdown" v-if="showDropdown">
        <view class="dropdown-title">商品分类</view>
        <view class="category-grid">
          <view class="category-grid-item" v-for="item in categoryList" :key="item.id"
            :class="{ activeTab: currentCategoryId === item.id }" @click="selectCategoryFromDropdown(item.id)">
            {{ item.cate_name }}
          </view>
        </view>
      </view>

      <!-- 商家列表展示 -->
      <!-- <view class="store-list-container">
        <view class="overlay" v-if="showDropdown"></view>
        <view class="store-item" v-for="(store, index) in merchantList" :key="index">
          <view class="store-image">
            <image :src="store.cate_image" mode="aspectFill"></image>
          </view>
          <view class="store-info">
            <view class="store-name">{{ store.merchant_name }}</view>
            <view class="startList">
                <image
                  v-for="index in 5"
                  :key="index"
                  :src="
                    index < item.rating
                      ? 'https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/local_start1.png'
                      : 'https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/local_start2.png'
                  "
                  mode="aspectFill"
                ></image>
            </view>
            <view class="store-tags">
              <text class="tag" v-for="(tag, idx) in store.tags" :key="idx">{{ tag }}</text>
            </view>
            <view class="store-address">
              <image class="address-icon"
                src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/address.png"
                mode="aspectFit">
              </image>
              <text>{{ store.address }}</text>
            </view>
            <view class="store-distance">
              <image class="distance-icon"
                src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/distance.png"
                mode="aspectFit">
              </image>
              <text>{{ store.distance }}km</text>
            </view>
          </view>
          <view class="review-btn" @click="gotoReview(store.id)">点评</view>
        </view>
      </view> -->
      <div class="merchantList">
        <view class="overlay" v-if="showDropdown"></view>
        <div class="merchantItem" v-for="item in merchatList" :key="item.id" @click="Info(item)">
          <div class="merchantItem_left">
            <image :src="item.showImg" mode="aspectFill"></image>
          </div>
          <div class="merchantItem_right">
            <div class="merchantItem_right_tit">
              <div class="merchantItem_right_tit_left">
                {{ item.merchant_name }}
              </div>
              <div class="merchantItem_right_tit_right">
                {{ item.distances }}
              </div>
            </div>
            <div class="merchantItem_right_con">
              <div class="merchantItem_right_con_left">
                <div class="startList">
                  <image v-for="index in 5" :key="index" :src="index < item.rating
                    ? 'https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/local_start1.png'
                    : 'https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/local_start2.png'
                    " mode="aspectFill"></image>
                </div>
                <div class="merchangtItem_tag" v-if="item.refund_property_fee_ratio">
                  买单返物业费
                </div>
                <div class="merchangtItem_tag" v-if="item.refund_user_points_ratio">
                  买单返积分
                </div>
              </div>
              <div class="merchantItem_right_con_right" @click="toJump(item)">
                <image src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/local_review.png"
                  mode="aspectFill"></image>
                点评
              </div>
            </div>
            <div class="merchantItem_right_add">
              {{ item.comAddress }}
            </div>
          </div>
        </div>
      </div>
    </view>

    <view class="more" v-if="flag">下拉加载后续10条，共计{{ bottomTotal }}条</view>
    <nav-footer />
  </view>

</template>


<script>
import {
  NavgateTo,
  calculateDistance,
} from '../../utils/index';

import {
  util,
  picUrl,
  request,
  menuButtonInfo
} from '../../utils/index.js';
import {
  apiArr
} from '../../api/community.js';

import {
  apiArr as apiArr2
} from '../../api/v2Home.js'

import {
  apiArr as citys
} from '../../api/area.js';

import nav from '../../components/nav/nav'; //1.导入组件


export default {
  components: {
    nav
  }, //2.注册组件
  data() {
    return {
      isShowSearch: false,

      loading: false,
      city: "",
      qqmap_key: '',
      tabList: [], // 金刚位列表信息
      nearbyLocation: '', // 城区附近地址
      flag: false,
      currentIdx: 0,
      currentCity: "", // 地址信息
      top: 0,
      localHeight: 44,
      userlocat: "",

      bannerList: [],
      buttonList: [],

      currentProviceCity: "",


      rowNum: 0,
      colNum: 0,

      homeLeftList: [],//中间左侧的广告
      homeRightList: [], // 中间右侧广告
      homeRightList1: [], // 中间右侧广告 左
      homeRightList2: [], // 中间右侧广告 右
      bottomPageSize: 10,
      bottomPageNum: 1,
      bottomList: [],
      bottomTotal: 0,
      flag: false,

      hotWord: [], // 搜索热词
      scrollPosition: 0, // 滚动位置
      scrollInterval: null, // 滚动定时器
      itemHeight: 40, // 每个热词项的高度

      // 中部1左侧广告
      serverLeft: '',

      // 中部1右侧广告
      serverRightList: [],

      // 分类数据
      categoryList1: [],
      categoryList: [],
      currentCategoryId: null,
      showDropdown: false,
      activeCategoryId: '',

      merchatList: [], // 当前显示的店铺列表
    }
  },

  methods: {
    goToShop() {
      uni.showModal({
        title: '提示',
        content: '此功能暂未开通！',
        showCancel: false,
        complete: (res) => {
          if (res.cancel) {

          }
        }
      })
    },

    goToOrder() {
      uni.showModal({
        title: '提示',
        content: '此功能暂未开通！',
        showCancel: false,
        complete: (res) => {
          if (res.cancel) {

          }
        }
      })
    },

    goToWuye() {
      uni.navigateTo({
        url: '/packages/workOrderDashboard/guide/index'
      })
    },

    swipers(e) {
      this.currentIdx = e.detail.current
    },

    // 处理热词点击
    handleHotWordClick(word) {
      console.log('点击的热词:', word);
    },

    // 启动滚动动画
    startScrollAnimation() {
      // 清除已有的定时器
      if (this.scrollInterval) {
        clearInterval(this.scrollInterval);
      }

      // 如果没有热词，不启动滚动
      if (this.hotWord.length === 0) {
        return;
      }

      let index = 0;
      const totalHeight = this.hotWord.length * this.itemHeight;
      const containerHeight = this.itemHeight; // 容器高度，只显示一项

      this.scrollInterval = setInterval(() => {
        index++;
        // 当滚动到底部时，重置到顶部
        if (index * this.itemHeight >= totalHeight) {
          this.scrollPosition = 0;
          index = 0;
        } else {
          this.scrollPosition = -index * this.itemHeight;
        }
      }, 2000); // 每2秒滚动一次
    },

    // 停止滚动动画
    stopScrollAnimation() {
      if (this.scrollInterval) {
        clearInterval(this.scrollInterval);
        this.scrollInterval = null;
      }
    },

    map() {
      uni.navigateTo({
        url: '/pages/shopcity/shopcity'
      });
    },

    init() {
      uni.showLoading({
        title: '加载中',
        mask: true
      });
      uni.request({
        url: apiArr.get_host_info,
        method: 'POST',
        header: {
          'Content-type': 'application/x-www-form-urlencoded'
        },
        dataType: 'json',
        success: (result) => {
          let wxapp = result.data.all.wxapp;
          if (wxapp) {
            this.qqmap_key = wxapp.qqmap_key;
            // 获取当前地址信息
            this.getUserLocation();
          }
        }
      });
    },


    getUserLocation() {
      let that = this
      const { qqmap_key } = this;
      let userlocat = uni.getStorageSync('location');

      uni.getLocation({
        type: 'wgs84',
        success: (res) => {
          const latitude = userlocat ? userlocat.lat : res.latitude;
          const longitude = userlocat ? userlocat.lng : res.longitude;
          uni.request({
            url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${qqmap_key}&get_poi=0`,
            success: async (res) => {
              const { data: { result: { address_component, ad_info } } } = res;

              // 精确到xx路 信息
              let preciseLocation = {
                cityName: address_component.city, // 市区
                region: address_component.province + address_component.city + address_component.district, // 省市区
                // 无街道xx号的地方，则定位到xx街道附近 无精确到xx号
                district: address_component.district + `${address_component.street_number ? address_component.street_number : address_component.street}`, // 详细地址
                address: address_component.city + address_component.district + address_component.street_number, // 详细地址
                lat: latitude,
                lng: longitude,
              };
              that.currentCity = preciseLocation;
              uni.setStorageSync('location', preciseLocation);
              uni.setStorageSync('ad_code', ad_info.adcode);
              // TODO: 这里需要强依赖 ad_code 去查询，必须保障代码先后执行顺序正确
              const [bannerList, serverLeft, serverRightList, homeLeftList, homeRightList, bottomList, buttonList, categoryList] = await Promise.all([

                this.getHomeBanner(),// 轮播图查询
                this.getServerLeft(), // 中部1左侧广告查询
                this.getServerRight(), // 中部1右侧广告查询

                this.getHomeMidLeft(), // 中部左侧查询
                this.getHomeMidRight(), // 中部右侧查询

                // this.getHomeCenterTop(), // 中部-中上
                // this.getHomeCenter(), // 中部-中
                // this.getHomeCenterBottom(), // 中部-中下

                // this.getHomeRightTop(), // 中部-右上
                // this.getHomeRightCenter(), // 中部-右中
                // this.getHomeRightBottom(), // 中部-右下

                // this.getHomePop()
                this.getHomeBottom(true), // 底部广告查询
                this.getButtonNum(), // 金刚位设置查询 及 金刚位按钮查询

                this.getCateList(), // 分类查询标签
              ]);
              this.bannerList = bannerList;
              this.serverLeft = serverLeft;
              this.serverRightList = serverRightList;
              this.homeLeftList = homeLeftList;
              this.homeRightList = homeRightList;
              this.homeRightList1 = homeRightList.slice(0, 3);
              this.homeRightList2 = homeRightList.slice(3, 6);
              that.bottomList = bottomList;
              this.tabList = buttonList;
              this.categoryList = categoryList;
              this.categoryList1 = categoryList.slice(0, 5);
              this.loading = true;
              uni.hideLoading();
            },
            fail(err) {
              console.log(err);
            }
          });
        }
      });
    },

    headerServerClick(e) {
      console.log('当前点击内容', e);
      if (!e.link_url) {
        this.NotOpen();
        return
      }
      if (e.link_url) {
        // #ifdef APP-PLUS
        uni.navigateTo({
          url: '/pages/webview/webview?url=' + encodeURIComponent(e.link_url)
        });
        // #endif

        // #ifdef H5
        window.open(e.link_url, '_blank');
        // #endif

        // #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU
        if (e.appid) {
          uni.navigateToMiniProgram({
            appId: e.appid,
            path: e.link_url,
            //需要传递给目标小程序的数据
            extraData: {
              'data1': 'test'
            },
            success(res) {
              console.log('打开成功', res)
            }
          })
        } else {
          NavgateTo(e.link_url)
          // NavgateTo('/packages/localLife/index/index')
        }
        // 小程序中可能需要用户手动复制链接或使用web-view
        // uni.showModal({
        // 	title: '提示',
        // 	content: '即将打开外部链接，请复制后在浏览器中打开: ' + e.link_url,
        // 	confirmText: '复制链接',
        // 	success(res) {
        // 		if (res.confirm) {
        // 			uni.setClipboardData({
        // 				data: e.link_url,
        // 				success() {
        // 					uni.showToast({
        // 						title: '复制成功',
        // 						icon: 'success'
        // 					});
        // 				}
        // 			});
        // 		}
        // 	}
        // });
        // #endif
      }
    },




    NotOpen() {
      uni.showModal({
        title: '提示',
        content: '此功能暂未开通！',
        showCancel: false,
        complete: (res) => {
          if (res.cancel) {

          }
        }
      })
    },

    //   榴园厨房
    cf() {
      NavgateTo('/kitchen/index/index');
    },

    headershopEnterClick() {
      NavgateTo('/packages/shopEnter/index/index');
    },


    async getHomeBanner() {
      const res = await request(apiArr2.getHomeBanner, "POST", {
        ad_code: uni.getStorageSync('ad_code'),
        ad_position: 1,
        longitude: uni.getStorageSync('location').lng,
        latitude: uni.getStorageSync('location').lat,
        page_num: 1,
        page_size: 10
      }, { silent: false });

      if (res.rows.length) {
        let filterRes = this.filterShowList(res?.rows, 1);
        filterRes.forEach(item => {
          item.pic_src = picUrl + item.pic_src
        })
        return filterRes
      } else {
        return []
      }
    },

    async getServerLeft() {
      const res = await request(apiArr2.getHomeBanner, "POST", {
        ad_code: uni.getStorageSync('ad_code'),
        ad_position: 2,
        longitude: uni.getStorageSync('location').lng,
        latitude: uni.getStorageSync('location').lat,
        page_num: 1,
        page_size: 10
      }, { silent: false });

      if (res.rows.length) {
        let filterRes = this.filterShowList(res?.rows, 1);
        filterRes.forEach(item => {
          item.pic_src = picUrl + item.pic_src
        })
        const itemUrl = filterRes[0].pic_src
        return itemUrl
      } else {
        return []
      }
    },

    async getServerRight() {
      const rightList = []
      for (let i = 3; i < 5; i++) {
        const res = await request(apiArr2.getHomeBanner, "POST", {
          ad_code: uni.getStorageSync('ad_code'),
          ad_position: i,
          longitude: uni.getStorageSync('location').lng,
          latitude: uni.getStorageSync('location').lat,
          page_num: 1,
          page_size: 10
        }, { silent: false });
        if (res.rows.length) {
          let filterRes = this.filterShowList(res?.rows, 1);
          filterRes.forEach(item => {
            item.pic_src = picUrl + item.pic_src
          })
          rightList.push(...filterRes)
        }
      }
      return rightList
    },

    async getHomeMidLeft() {
      const res = await request(apiArr2.getHomeBanner, "POST", {
        ad_code: uni.getStorageSync('ad_code'),
        ad_position: 5,
        longitude: uni.getStorageSync('location').lng,
        latitude: uni.getStorageSync('location').lat,
        page_num: 1,
        page_size: 10
      }, { silent: false });
      if (res.rows.length) {
        let filterRes = this.filterShowList(res?.rows, 1);
        filterRes.forEach(item => {
          item.pic_src = picUrl + item.pic_src
        })
        return filterRes
      } else {
        return []
      }
    },

    async getHomeMidRight() {
      const rightList = []
      for (let i = 6; i < 12; i++) {
        const res = await request(apiArr2.getHomeBanner, "POST", {
          ad_code: uni.getStorageSync('ad_code'),
          ad_position: i,
          longitude: uni.getStorageSync('location').lng,
          latitude: uni.getStorageSync('location').lat,
          page_num: 1,
          page_size: 10
        }, { silent: false });
        if (res.rows.length) {
          let filterRes = this.filterShowList(res?.rows, 1);
          filterRes.forEach(item => {
            item.pic_src = picUrl + item.pic_src
          })
          rightList.push(...filterRes)
        }else{
          rightList.push({
            ad_position: i,
            pic_src: ''
          })
        } 
      }
      return rightList
    },

    // async getHomeCenterTop() {
    //   const res = await request(apiArr2.getHomeBanner, "POST", {
    //     ad_code: uni.getStorageSync('ad_code'),
    //     ad_position: 6,
    //     longitude: uni.getStorageSync('location').lng,
    //     latitude: uni.getStorageSync('location').lat,
    //     page_num: 1,
    //     page_size: 10
    //   }, { silent: false });
    //   if (res.rows.length) {
    //     let filterRes = this.filterShowList(res?.rows, 1);
    //     filterRes.forEach(item => {
    //       item.pic_src = picUrl + item.pic_src
    //     })
    //     return filterRes.slice(0, 6)
    //   } else {
    //     return []
    //   }
    // },

    // async getHomeCenter() {
    //   const res = await request(apiArr2.getHomeBanner, "POST", {
    //     ad_code: uni.getStorageSync('ad_code'),
    //     ad_position: 7,
    //     longitude: uni.getStorageSync('location').lng,
    //     latitude: uni.getStorageSync('location').lat,
    //     page_num: 1,
    //     page_size: 10
    //   }, { silent: false });
    //   if (res.rows.length) {
    //     let filterRes = this.filterShowList(res?.rows, 1);
    //     filterRes.forEach(item => {
    //       item.pic_src = picUrl + item.pic_src
    //     })
    //     return filterRes.slice(0, 6)
    //   } else {
    //     return []
    //   }
    // },

    // async getHomeCenterBottom() {
    //   const res = await request(apiArr2.getHomeBanner, "POST", {
    //     ad_code: uni.getStorageSync('ad_code'),
    //     ad_position: 8,
    //     longitude: uni.getStorageSync('location').lng,
    //     latitude: uni.getStorageSync('location').lat,
    //     page_num: 1,
    //     page_size: 10
    //   }, { silent: false });
    //   if (res.rows.length) {
    //     let filterRes = this.filterShowList(res?.rows, 1);
    //     filterRes.forEach(item => {
    //       item.pic_src = picUrl + item.pic_src
    //     })
    //     return filterRes.slice(0, 6)
    //   } else {
    //     return []
    //   }
    // },

    // async getHomeRightTop() {
    //   const res = await request(apiArr2.getHomeBanner, "POST", {
    //     ad_code: uni.getStorageSync('ad_code'),
    //     ad_position: 9,
    //     longitude: uni.getStorageSync('location').lng,
    //     latitude: uni.getStorageSync('location').lat,
    //     page_num: 1,
    //     page_size: 10
    //   }, { silent: false });
    //   if (res.rows.length) {
    //     let filterRes = this.filterShowList(res?.rows, 1);
    //     filterRes.forEach(item => {
    //       item.pic_src = picUrl + item.pic_src
    //     })
    //     return filterRes.slice(0, 6)
    //   } else {
    //     return []
    //   }
    // },

    // async getHomeRightCenter() {
    //   const res = await request(apiArr2.getHomeBanner, "POST", {
    //     ad_code: uni.getStorageSync('ad_code'),
    //     ad_position: 10,
    //     longitude: uni.getStorageSync('location').lng,
    //     latitude: uni.getStorageSync('location').lat,
    //     page_num: 1,
    //     page_size: 10
    //   }, { silent: false });
    //   if (res.rows.length) {
    //     let filterRes = this.filterShowList(res?.rows, 1);
    //     filterRes.forEach(item => {
    //       item.pic_src = picUrl + item.pic_src
    //     })
    //     return filterRes.slice(0, 6)
    //   } else {
    //     return []
    //   }
    // },

    // async getHomeRightBottom() {
    //   const res = await request(apiArr2.getHomeBanner, "POST", {
    //     ad_code: uni.getStorageSync('ad_code'),
    //     ad_position: 11,
    //     longitude: uni.getStorageSync('location').lng,
    //     latitude: uni.getStorageSync('location').lat,
    //     page_num: 1,
    //     page_size: 10
    //   }, { silent: false });
    //   if (res.rows.length) {
    //     let filterRes = this.filterShowList(res?.rows, 1);
    //     filterRes.forEach(item => {
    //       item.pic_src = picUrl + item.pic_src
    //     })
    //     return filterRes.slice(0, 6)
    //   } else {
    //     return []
    //   }
    // },

    // 小程序首页弹窗内容
    async getHomePop() {
      await request(apiArr2.getHomeBanner, "POST", {
        ad_code: uni.getStorageSync('ad_code'),
        ad_position: 12,
        longitude: uni.getStorageSync('location').lng,
        latitude: uni.getStorageSync('location').lat,
        page_num: 1,
        page_size: 10
      }, { silent: false }).then(res => {
        console.log(res);
      })
    },

    // 底部推荐信息
    async getHomeBottom(val = false) {
      const res = await request(apiArr2.getHomeBanner, "POST", {
        ad_code: uni.getStorageSync('ad_code'),
        ad_position: 5,
        longitude: uni.getStorageSync('location').lng,
        latitude: uni.getStorageSync('location').lat,
        page_num: this.bottomPageNum,
        page_size: this.bottomPageSize
      }, { silent: val ? false : true });
      if (res.rows.length === 0) {
        return [];
      };
      if (res.rows.length == this.bottomPageSize) {
        this.flag = true
      } else {
        this.flag = false
      }
      let filterRes = this.filterShowList(res?.rows, 1);
      filterRes.forEach(item => {
        item.pic_src = picUrl + item.pic_src
      })
      this.bottomPageNum++
      this.bottomTotal = res.total
      return filterRes
    },

    async getButtonNum() {
      const res = await request(apiArr2.getButtonNum, "POST", {}, { slice: false });
      this.rowNum = res.nav_row_num
      this.colNum = res.nav_row_total
      return await this.getHomeButton()
    },

    async getHomeButton() {
      const res = await request(apiArr2.getHomeButton, "POST", {
        ad_code: Number(uni.getStorageSync('ad_code')),
        page_num: 1,
        page_size: 50
      }, { slice: false });
      // 过滤出已发布的按钮列表
      const filterRes = this.filterShowList(res?.rows, 1);
      // 根据所需展示数量对数据进行截取
      let newList = filterRes.slice(0, this.rowNum * this.colNum);
      console.log('111', newList);
      if (newList.length !== 0) {
        newList.forEach(item => {
          item.icon_src = picUrl + item.icon_src
        })
        return newList;
      } else {
        return [];
      }
    },

    // 分类查询
    async getCateList() {
      const res = await request(apiArr2.getCateList, "POST", {
      }, { slice: false });
      if (res.rows.length) {
        this.currentCategoryId = res.rows[0].id
        this.activeCategoryId = `category-${this.currentCategoryId}`
        this.getMechantList()
        return res.rows
      } else {
        return []
      }
    },

    // 商家列表
    async getMechantList() {
      let that = this;
      await request(apiArr2.getMerchantList, "POST", {
        merchant_cate_id: that.currentCategoryId,
        page_num: that.page_num,
        page_size: that.page_size,
      }).then((res) => {
        let latitude = uni.getStorageSync("location").lat;
        let longitude = uni.getStorageSync("location").lng;
        res.rows.forEach((item) => {
          item.bigImg = item.album_images.split(",");
          item.showImg = picUrl + item.album_images.split(",")[0];
          const distanceInKm = calculateDistance(
            latitude,
            longitude,
            item.latitude,
            item.longitude
          );
          item.distances =
            distanceInKm >= 1
              ? `${distanceInKm.toFixed(1)}km`
              : `${(distanceInKm * 1000).toFixed(1)}m`;

          if (item.ad) {
            item.comAddress = item.ad.ad_name.replace(/,/g, "") + item.address;
          } else {
            item.comAddress = item.address;
          }
        });
        res.rows.sort((a, b) => {
          const valueA =
            parseFloat(a.distances.replace("km", "").replace("m", "")) *
            (a.distances.includes("km") ? 1000 : 1);
          const valueB =
            parseFloat(b.distances.replace("km", "").replace("m", "")) *
            (b.distances.includes("km") ? 1000 : 1);
          return valueA - valueB;
        });

        if (res.rows.length == this.page_size) {
          this.page_num = this.page_num + 1;
          this.flag = true;
        } else {
          this.flag = false;
        }
        this.merchatList = res.rows;
      });
    },

    //跳转商家详情
    Info(e) {
      uni.setStorageSync("merchantInfo", e);
      NavgateTo("/packages/localLife/detail/index");
    },
    //跳转点评
    toJump(e) {
      NavgateTo('/packages/localLife/comment/index');
    },

    /**
     * 首页过滤方法
     * @param {Array} list 请求地址
     * @param {any} type 过滤值
     * @returns {Array} 返回符合条件的数组内容
    */
    filterShowList(list, type) {
      if (list && list.length == 0) return [];
      return list.filter((item) => item.show_status == type);
    },

    async showSearch() {
      const res = await request(apiArr.isShowSearch, "POST", {}, { slice: false });
      this.isShowSearch = res.search_enable == 1
    },

    async getSearchVal() {
      const res = await request(apiArr.hotWord, "POST", {}, { slice: false });
      // 支持英文逗号和中文逗号分割
      this.hotWord = res.search_hot_word.split(/[,，]/)
    },

    switchCategory(id) {
      this.currentCategoryId = id;
      this.activeCategoryId = `category-${id}`;
      this.getMechantList()

      this.showDropdown = false;
    },

    toggleDropdown() {
      this.showDropdown = !this.showDropdown;
    },

    selectCategoryFromDropdown(id) {
      this.switchCategory(id);
      this.showDropdown = false;
    }
  },
  onLoad(options) {
    this.init()
    const meun = menuButtonInfo();
    this.top = meun.top;
    this.localHeight = meun.height;
    this.showSearch()
    this.getSearchVal()
  },

  onShow() {
    // 页面显示时启动滚动动画
    this.startScrollAnimation();
  },

  onHide() {
    // 页面隐藏时停止滚动动画
    this.stopScrollAnimation();
  },

  onUnload() {
    // 页面卸载时停止滚动动画
    this.stopScrollAnimation();
  },

  // 监听hotWord变化，重新启动滚动
  watch: {
    hotWord: {
      handler(newVal) {
        if (newVal.length > 0) {
          this.startScrollAnimation();
        }
      },
      immediate: true
    }
  },
  onShow() {
    this.flag = false
    this.bottomPageNum = 1
    console.log('当前页面展示的城市信息', this.currentCity)
    console.log('缓存中存储的城市信息', uni.getStorageSync('location'));
    const storageLocation = uni.getStorageSync('location');
    // 存在缓存城市信息， 并且不是第一次加载页面则调用该方法
    if (storageLocation && this.loading) {
      // 非同一城市名称 或者 同一城市详细地址不同则重新请求接口
      if (this.currentCity && this.currentCity.cityName !== storageLocation.cityName || this.currentCity.address !== storageLocation.district) {
        this.init();
      }
      this.currentCity = storageLocation;
    }
  },

  async onReachBottom() {
    if (this.flag) {
      const res = await this.getHomeBottom();
      this.bottomList = this.bottomList.concat(res);
    } else {
      uni.showToast({
        title: '没有更多了',
        icon: 'none'
      })
    }
  }
}
</script>

<style>
@import url("./index.css");
</style>