<template>
  <view>
    <!-- <view v-if="currentCity && currentCity.cityName && currentCity.cityName != '衡水市'">
      <view class="not_found_404">
        <text class="not_found_text">404</text>
        <text class="not_found_desc">当前城市暂未开通服务</text>
        <button class="not_found_button" @click="obtainLocation">重新定位</button>
      </view>
    </view>
    <view v-else> -->
    <view>
      <view class="container" :style="{ marginTop: top + 'px' }" v-if="loading">
        <!-- 城市信息部分 -->
        <view class="white_container searchBox" :style="{ height: localHeight + 'px' }">
          <view class="searchBox_add" @tap="map">
            <image src="https://static.hshuishang.com/Index_add.png" mode="widthFix" />
            <view>
              {{ currentCity.cityName || '选择城市' }}
            </view>
          </view>
        </view>
        <view class="mainBox" ref="mainBox">
          <!-- 搜索框 -->
          <view class="search2" v-if="isShowSearch">
            <view class="searchBox2" @click="goSearchView">
              <image src="https://static.hshuishang.com/property-img-file/com_communitySearchIcon.png"
                mode="aspectFill"></image>
              <view class="hot-word-container">
                <view class="hot-word-scroll" :style="{ transform: 'translateY(' + scrollPosition + 'rpx)' }">
                  <view v-for="(word, index) in hotWord" :key="index" class="hot-word-item"
                    @click="handleHotWordClick(word)">
                    {{ word }}
                  </view>
                </view>
              </view>
              <!-- <input class="search_input" placeholder='请输入内容' confirm-type='search' @input="searchInput"
                @confirm="searchInput" :value="selectKeyWord" @click="goSearchView"/> -->
            </view>
          </view>
          <view class="white_container">
            <!-- 功能导航区 -->
            <!-- <view class="function-nav" v-if="showNav">
              <view class="function-item" @click="goToShop">
                <view class="icon-box">
                  <image class="iconImg" src="https://static.hshuishang.com/index_shop.png"
                    mode="widthFix" />
                </view>
                <text>店铺管理</text>
              </view>
              <view class="function-item" @click="goToOrder">
                <view class="icon-box">
                  <image class="iconImg" src="https://static.hshuishang.com/index_order.png"
                    mode="widthFix" />
                </view>
                <text>供应商订单</text>
              </view>
              <view class="function-item" @click="goToWuye">
                <view class="icon-box">
                  <image class="iconImg" src="https://static.hshuishang.com/index_wuye.png"
                    mode="widthFix" />
                </view>
                <text>物业管理</text>
              </view>
            </view> -->
            <!-- 轮播图 -->
            <view class="swiper">
              <swiper @animationfinish="swipers" autoplay circular>
                <swiper-item v-for="(item, index) in bannerList" :key="index" @click="handleAdClick(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="aspectFill"></image>
                  <text>{{ item.title }}</text>
                </u-grid-item>
              </u-grid>
            </view>
          </view>

          <!-- 广告横幅 -->
          <view class="serverList1">
            <view class="serverList1_left" v-if="serverLeftList.length > 0">
              <image :src="serverLeft" mode="aspectFill" @tap="handleAdClick(serverLeftList[0])" />
            </view>
            <view class="serverList1_right" v-if="serverRightList.length > 0">
              <view :class="['serverItemRight', `serverItemRight${index + 1}`]" v-for="(item, index) in serverRightList"
                :key="index">
                <image :src="item.pic_src" mode="" @tap="handleAdClick(item)" />
              </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" @click="handleAdClick(item)">
                    <image :src="item.pic_src" alt="" class="serverList_left_img" />
                    <!-- <view>{{ item.ad_position }}</view> -->
                  </swiper-item>
                </swiper>
              </view>

              <view class="serverList_right">
                <view class="serverList_right1">
                  <view :class="['serverItem', `serverItem${index + 1}`]" @click="headerServerClick2(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}`]" @click="headerServerClick2(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> -->
          <!-- 分类标签栏已移至mainBox下方作为子盒子，保持视觉位置不变 -->
          <u-sticky>
            <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" v-if="categoryList">
                <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>
          </u-sticky>

          <!-- 商家列表展示 -->
          <view class="merchantList" :class="{ merchantList2: merchatList.length < 3 }">
            <view class="overlay" v-if="showDropdown"></view>
            <view class="merchantItem" v-for="item in merchatList" :key="item.id" @click="Info(item)">
              <view class="merchantItem_left">
                <image :src="item.showImg" mode="aspectFill"></image>
              </view>
              <view class="merchantItem_right">
                <view class="merchantItem_right_tit">
                  <view class="merchantItem_right_tit_left">
                    {{ item.merchant_name }}
                  </view>
                  <view class="merchantItem_right_tit_right">
                    {{ item.distances }}
                  </view>
                </view>
                <view class="merchantItem_right_con">
                  <view class="merchantItem_right_con_left">
                    <view class="startList">
                      <image v-for="index in 5" :key="index" :src="index < item.rating
                        ? 'https://static.hshuishang.com/property-img-file/local_start1.png'
                        : 'https://static.hshuishang.com/property-img-file/local_start2.png'
                        " mode="aspectFill"></image>
                    </view>
                    <view class="merchangtItem_tag" v-if="item.refund_property_fee_ratio">
                      买单返岁银
                    </view>
                    <view class="merchangtItem_tag" v-if="item.refund_user_points_ratio">
                      买单返积分
                    </view>
                  </view>
                  <view class="merchantItem_right_con_right" @click.stop="toJump(item)">
                    <image src="https://static.hshuishang.com/property-img-file/local_review.png" mode="aspectFill">
                    </image>
                    点评
                  </view>
                </view>
                <view class="merchantItem_right_add">
                  {{ item.comAddress }}
                </view>
              </view>
            </view>
          </view>

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

  </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 apiArr3
} from '../../api/v2User.js'


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

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

// 首页广告位常量（对应后台 home_banner_region.ad_position）
const AD_POS = {
  TOP_BANNER: 1,        // 顶部轮播
  CARD_LEFT: 2,         // 卡片橱窗左
  CARD_RIGHT_TOP: 3,    // 卡片橱窗右上
  CARD_RIGHT_BOTTOM: 4, // 卡片橱窗右下
  MID_LEFT: 5,          // 中部广告位左
  MID_CENTER_TOP: 6,    // 中部中上
  MID_CENTER: 7,        // 中部中
  MID_CENTER_BOTTOM: 8, // 中部中下
  MID_RIGHT_TOP: 9,     // 中部右上
  MID_RIGHT_CENTER: 10, // 中部右中
  MID_RIGHT_BOTTOM: 11, // 中部右下
  POPUP: 12,            // 小程序弹窗
  BOTTOM_RECOMMEND: 13, // 底部推荐
};

export default {
  components: {
    nav
  }, //2.注册组件
  data() {
    return {
      showNav: false,
      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: 50, // 每个热词项的高度

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

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

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

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

  methods: {
    goSearchView() {
      NavgateTo('/packages/shop/search/index');
    },
    goToShop() {
      uni.showModal({
        title: '提示',
        content: '此功能暂未开通！',
        showCancel: false,
        complete: (res) => {
          if (res.cancel) {

          }
        }
      })
    },

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

          }
        }
      })
    },

    // 统一广告点击：按后台 promotion_type 分发跳转
    // 1无 / 3跳本小程序页面(link_url) / 4跳其他小程序(appid+link_url) / 5选择商品(跳广告商品列表页)
    handleAdClick(item) {
      if (!item) return
      switch (item.promotion_type) {
        case 3: // 跳转本小程序页面
          if (!item.link_url) return this.NotOpen()
          if (item.link_url === '/packages/shopEnter/index/index') return this.headershopEnterClick()
          return NavgateTo(item.link_url, { isLogin: false })
        case 4: // 跳转其他小程序
          if (!item.appid) return this.NotOpen()
          return uni.navigateToMiniProgram({
            appId: item.appid,
            path: item.link_url || '',
            envVersion: 'release'
          })
        case 5: // 选择商品 → 广告商品列表页
          return NavgateTo('/packages/advertising/index/index?id=' + item.id, { isLogin: false })
        case 1:
        default: // 无
          return this.NotOpen()
      }
    },

    async goToWuye() {
      uni.removeStorageSync('order_dispatch_permission');
      uni.removeStorageSync('work_order_permission');
      const res = await request(apiArr3.getUserInfo, 'POST', {});
      const { community_worker } = res;
      uni.setStorageSync('order_dispatch_permission', community_worker && community_worker[0].order_dispatch_permission == 1 || false);
      uni.setStorageSync('work_order_permission', community_worker && community_worker[0].work_order_permission == 1 || false);
      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 || this.hotWord.length === 0) {
        return;
      }

      let index = 0;
      const totalHeight = this.hotWord && 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
      });
      this.qqmap_key = '55NBZ-MUQYW-EAJRL-YIWPA-ZXCR6-4NBPP';
      this.getUserLocation()
      // 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 去查询，必须保障代码先后执行顺序正确
              // 先一次性批量拉取首页各广告位（1-11），后续各 getHomeXxx 直接读缓存，
              // 把原来十几次 banner-region 请求压成一次
              await this.prefetchBannerGroups();
              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('地图API解析地址失败:', err);
              uni.showToast({
                title: '定位失败，请检查网络',
                icon: 'none'
              });
              uni.hideLoading();
            }
          });
        },
        fail(err) {
          console.log('获取位置信息失败:', err);
          if (err.errMsg.indexOf('auth deny') >= 0) {
            uni.showModal({
              title: '提示',
              content: '需要您授权位置信息才能使用此功能',
              confirmText: '去授权',
              success: (res) => {
                if (res.confirm) {
                  // #ifdef MP-WEIXIN
                  wx.openSetting();
                  // #endif
                  // #ifdef APP-PLUS
                  uni.openSetting();
                  // #endif
                }
                uni.hideLoading();
              }
            });
          } else {
            uni.showToast({
              title: '定位失败，请重试',
              icon: 'none'
            });
            uni.hideLoading();
          }
        }
      });
    },

    async headerServerClick2(e) {
      if (e.title == '更多') {
        NavgateTo('/packages/localLife/index/index', { isLogin: false })
      }
      const cate_id = this.categoryList.find(item => item.cate_name == e.title)?.id;
      if (cate_id) {
        await this.switchCategory(cate_id);
      }
      return
    },

    headerServerClick(e) {
      // const cate_id = this.categoryList.find(item => item.cate_name == e.title).id;
      // this.switchCategory(cate_id)
      // return

      if (!e.link_url) {
        this.NotOpen();
        return
      }
      if (e.link_url) {
        if (e.link_url === '/packages/shopEnter/index/index') {
          this.headershopEnterClick()
          return
        }

        // #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, { isLogin: false })
          // 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');
    },

    async headershopEnterClick() {
      if (!uni.getStorageSync('userId')) {
        NavgateTo('/packages/shopEnter/choose/index', { isLogin: false });
        return
      }
      const res = await request(apiArr2.statusQuery, "POST", {}, { silent: false });
      if (res.status) {
        NavgateTo('/packages/shopEnter/auditStatus/index?itemObj=' + JSON.stringify(res));
      } else {
        NavgateTo('/packages/shopEnter/choose/index');
      }
    },


    // 一次性拉取多个广告位，结果缓存到 this._bannerGroups，供各 getHomeXxx 读取，
    // 把原来十几次 banner-region 请求压成一次。
    async prefetchBannerGroups(positions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) {
      try {
        const res = await request(apiArr2.getHomeBannerMulti, "POST", {
          ad_code: Number(uni.getStorageSync('ad_code')),
          ad_positions: positions,
          longitude: uni.getStorageSync('location').lng,
          latitude: uni.getStorageSync('location').lat,
          page_size: 50
        }, { silent: false });
        this._bannerGroups = (res && res.groups) ? res.groups : {};
      } catch (e) {
        console.warn('批量拉取首页广告失败，回退逐个请求:', e);
        this._bannerGroups = null; // 标记不可用，各方法回退单查
      }
    },

    // 读取某广告位的数据：优先用批量缓存，缓存缺失则回退单个 page 请求（保证方法可独立工作）
    async getBannerRows(position) {
      if (this._bannerGroups) {
        const rows = this._bannerGroups[String(position)] || [];
        return rows;
      }
      const res = await request(apiArr2.getHomeBanner, "POST", {
        ad_code: uni.getStorageSync('ad_code'),
        ad_position: position,
        longitude: uni.getStorageSync('location').lng,
        latitude: uni.getStorageSync('location').lat,
        page_num: 1,
        page_size: 50
      }, { silent: false });
      return (res && res.rows) ? res.rows : [];
    },

    // 给列表统一补图片前缀
    withPicUrl(list) {
      list.forEach(item => { item.pic_src = picUrl + item.pic_src })
      return list
    },

    // 取某广告位「第一条已发布」广告（固定单格用）；无则按需返回占位或 null
    async getBannerAt(position, { placeholder = false } = {}) {
      const rows = await this.getBannerRows(position)
      const [first] = this.withPicUrl(this.filterShowList(rows, 1))
      if (first) return first
      return placeholder ? { ad_position: position, pic_src: '' } : null
    },

    // 按顺序批量取多个固定单格位置
    async getBannersAt(positions, opts) {
      return Promise.all(positions.map(p => this.getBannerAt(p, opts)))
    },

    async getHomeBanner() {
      const rows = await this.getBannerRows(AD_POS.TOP_BANNER);
      return this.withPicUrl(this.filterShowList(rows, 1));
    },

    async getServerLeft() {
      const rows = await this.getBannerRows(AD_POS.CARD_LEFT);
      const shown = this.withPicUrl(this.filterShowList(rows, 1));
      this.serverLeftList = shown; // 与展示的首图保持一致，点击取 [0] 即为当前图
      return shown.length ? shown[0].pic_src : [];
    },

    async getServerRight() {
      // 卡片橱窗右侧两格，各取第一条；无广告则不占位（保持原「无则隐藏」行为）
      const list = await this.getBannersAt([
        AD_POS.CARD_RIGHT_TOP,
        AD_POS.CARD_RIGHT_BOTTOM,
      ]);
      return list.filter(Boolean);
    },

    async getHomeMidLeft() {
      const rows = await this.getBannerRows(AD_POS.MID_LEFT);
      return this.withPicUrl(this.filterShowList(rows, 1));
    },

    async getHomeMidRight() {
      // 中部右侧宫格固定 6 格，各取第一条，保证 slice(0,3)/slice(3,6) 对齐
      return this.getBannersAt([
        AD_POS.MID_CENTER_TOP, AD_POS.MID_CENTER, AD_POS.MID_CENTER_BOTTOM,
        AD_POS.MID_RIGHT_TOP, AD_POS.MID_RIGHT_CENTER, AD_POS.MID_RIGHT_BOTTOM,
      ], { placeholder: true });
    },

    // 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: AD_POS.BOTTOM_RECOMMEND,
        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 || res.rows.length === 0) {
        return [];
      };
      if (res.rows && 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 params = {
        isShop: 1,
      }
      const res = await request(apiArr2.getCateList, "POST", params, { slice: false });
      if (res.rows && 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 && 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", { isLogin: false });
    },
    //跳转点评
    toJump(e) {
      NavgateTo('/packages/localLife/comment/index');
    },

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

    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 ? res.search_hot_word.split(/[,，]/) : []
    },

    async switchCategory(id) {
      this.currentCategoryId = id;
      this.activeCategoryId = `category-${id}`;
      await this.getMechantList(); // 等待数据加载完成

      this.showDropdown = false;
      this.$nextTick(() => {
        // 获取mainBox元素并使其滚动到底部
        const mainBox = this.$refs.mainBox;
        if (mainBox) {
          mainBox.scrollTop = 1000;
        }
      });
    },

    toggleDropdown() {
      this.showDropdown = !this.showDropdown;
      // 当展开下拉菜单时，在mainBox内滑动
      if (this.showDropdown) {
        this.$nextTick(() => {
          // 获取mainBox元素并使其滚动到底部
          const mainBox = this.$refs.mainBox;
          if (mainBox) {
            mainBox.scrollTop = 1000;
          }
        })
      }
    },

    selectCategoryFromDropdown(id) {
      this.switchCategory(id);
      this.showDropdown = false;
    },

    // 获取当前位置
    obtainLocation() {
      // 显示加载提示
      uni.showLoading({
        title: '定位中...',
        mask: true
      });

      // 清除旧的位置缓存
      uni.removeStorageSync('location');

      // 重新获取位置信息
      try {
        this.getUserLocation();
      } catch (error) {
        console.error('定位失败:', error);
        uni.showToast({
          title: '定位失败，请重试',
          icon: 'none'
        });
        uni.hideLoading();
      }
    }
  },
  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 && newVal.length > 0) {
          this.startScrollAnimation();
        }
      },
      immediate: true
    }
  },
  onShow() {
    this.showNav = uni.getStorageSync("userId") ? uni.getStorageSync("is_worker") : false
    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;
    }
  },

  onPullDownRefresh() {
    this.bottomList = [];
    this.bottomPageNum = 1;
    this.flag = false;
    this.init();
    uni.stopPullDownRefresh();
  },

  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>