<template>
  <view>
    <view class="top-box">
      <view class="top-nav">
        <view class="city-text" @click="regionSelectionRef.open()">
          <uv-icon name="map" color="#999999" size="34rpx"></uv-icon>
          <view>{{ cityName }}</view>
        </view>
        <view class="searchBox">
          <image
            src="/static/image/order/icon_search.png"
            mode="widthFix"
          ></image>
          <input
            v-model="param.keyword"
            type="text"
            @confirm="search"
            placeholder-style="color:#B3B3B3"
            placeholder="请输入关键字"
            @input="search"
          />
        </view>
      </view>
      <view class="tabsBox">
        <view class="type-box">
          <view class="item" @click="show = true">
            <view>{{
              selectIndex === null ? "全部分类" : selector[selectIndex].name
            }}</view>
            <uv-icon name="arrow-down" color="#4d4d4d" size="26rpx"></uv-icon>
          </view>
          <view
            class="item"
            v-for="(v, i) in typeList"
            :key="i"
            :class="{ activeCls: tabCurrent == i }"
            @click="tabsChange2(i)"
          >
            <view>{{ v.name }}</view>
          </view>
        </view>
      </view>
    </view>
    <view :style="{ height: placeholderH + 'px' }"></view>
    <view class="shopListBox" v-if="RowsList.length > 0">
      <!-- 附近门店 -->
      <ShopItem
        v-for="(v, index) in RowsList"
        :key="v.businessId"
        :v="v"
      />
    </view>
    <view>
      <loadMore v-if="RowsList.length > 0" :status="LoadStatus"></loadMore>
      <noData v-if="RowsList.length <= 0" :config="{ top: 2 }"></noData>
    </view>

    <!-- 地区选择 -->
    <RegionSelection
      ref="regionSelectionRef"
      :hierarchy="2"
      @confirm="addressConfirm"
    />
    <uv-picker
      mode="selector"
      v-model="show"
      :range="selector"
      range-key="name"
      :default-selector="[sIndex]"
      @confirm="confirmSelect"
    ></uv-picker>
  </view>
</template>

<script setup>
import { computed, getCurrentInstance, nextTick, reactive, ref } from "vue";
import { onLoad, onPullDownRefresh, onShow } from "@dcloudio/uni-app";
import { getBusinessPage, getBusinessCategoryList } from "@/api/shop.js";
import { usePageData } from "@/hooks/usePageData.ts";

import ShopItem from "./components/ShopItem.vue";
const regionSelectionRef = ref(null);
const { RowsList, LoadStatus, initData } = usePageData(getBusinessPage);

const instance = getCurrentInstance();

const statusBarHeight = ref(uni.getSystemInfoSync().statusBarHeight || 0);
const sticky = computed(() => statusBarHeight.value + 44);
const placeholderH = ref(0);

const cityName = ref("武汉市");
const sIndex = ref(0);
const param = reactive({});

const tabCurrent = ref(0);
const typeList = ref([
  { name: "距离优先", order: "distance" },
  { name: "评分优先", order: "average" },
]);
const show = ref(false);
const selector = ref([]);
const selectIndex = ref(null);

const getRect = (selectorStr) =>
  new Promise((resolve) => {
    const query = uni.createSelectorQuery();
    const ctx = instance?.proxy || undefined;
    if (ctx) query.in(ctx);
    query
      .select(selectorStr)
      .boundingClientRect((res) => resolve(res || {}))
      .exec();
  });

const tabsChange2 = (index) => {
  tabCurrent.value = index;
  param.order = typeList.value[index]?.order || "distance";
  console.log(param);
  //   initData(param);
};

const confirmSelect = (e) => {
  const idx = e?.[0] ?? 0;
  selectIndex.value = idx;
  sIndex.value = idx;
  initData(param);
};

// 地区选择确认
const addressConfirm = (e) => {
  const picked = e.areaName || e.cityName || e.provinceName;
  cityName.value = picked || cityName.value;
  Object.assign(param, { ...e });
  initData(param);
};

const getTppe = async (id) => {
  await getBusinessCategoryList().then((res) => {
    if (res && res.code == 200) {
      selector.value = [{ name: "全部分类", id: "" }, ...(res.data || [])];
      if (id) {
        selector.value.forEach((v, i) => {
          if (String(v.id) === String(id)) selectIndex.value = i;
        });
      }
    }
  });
};

// 获取当前位置
const getLoca = async () => {
  await uni.getLocation({
    type: "gcj02",
    geocode: true,
    success: (res) => {
      param.longitude = res.longitude;
      param.latitude = res.latitude;
    },
    fail: () => {},
  });
};

const searchTimer = ref(null);
const search = () => {
  if (searchTimer.value) clearTimeout(searchTimer.value);
  searchTimer.value = setTimeout(() => {
    initData(param);
  }, 1000);
};

const initPage = async (options = {}) => {
  if (options?.id) {
    param.businessCategoryId = options.id;
  }
  if (options?.cityName) {
    cityName.value = options.cityName;
  }
  if (options?.cityCode) {
    param.cityCode = options.cityCode;
  }
  try {
    await getTppe(param.businessCategoryId);
    await getLoca();
  } catch (error) {
    console.log(error);
  }
  initData(param);
};

onLoad((options) => {
  initPage(options || {});
});

onShow(async () => {
  await nextTick();
  const rect = await getRect(".top-box");
  placeholderH.value = rect?.height || 0;
});

onPullDownRefresh(() => {
  //   Promise.allSettled([getLoca(), initData(param)]).finally(() => {
  //     uni.stopPullDownRefresh();
  //   });
});
</script>

<style lang="scss" scoped>
.top-box {
  width: 750rpx;
  position: fixed;
  background-color: #fff;
  z-index: 3;
}

.top-nav {
  height: 120rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30rpx;
  background-color: #fff;
}

.city-text {
  margin-right: 20rpx;
  font-size: 30rpx;
  font-family: PingFang SC, PingFang SC-Regular;
  font-weight: 400;
  text-align: center;
  color: #666666;
  display: flex;
  align-items: center;

  view {
    max-width: 100rpx;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }

  image {
    width: 26rpx;
    height: 36rpx;
    margin-right: 10rpx;
    vertical-align: middle;
  }
}

.searchBox {
  //   width: 560rpx;
  flex: 1;
  display: flex;
  padding: 10rpx 27rpx;
  border: 1rpx solid #cccccc;
  border-radius: 10rpx;
  display: flex;
  align-items: center;

  image {
    width: 35rpx;
    height: 35rpx;
    margin-right: 15rpx;
    flex-shrink: 0;
  }

  input {
    text-align: left;
  }
}

.tabsBox {
  width: 100%;
  background-color: #fff;

  .tabsBox_tabs {
    padding: 0 10rpx;

    ::v-deep .u-tab-item {
      font-weight: 700;
    }
  }
}

.type-box {
  display: flex;
  align-items: center;
  padding: 0 40rpx 20rpx;
  justify-content: space-between;

  .item {
    display: flex;
    font-size: 28rpx;
    font-family: PingFang SC, PingFang SC-Regular;
    font-weight: 400;
    color: #4d4d4d;
    align-items: center;
    color: #4d4d4d;

    &:first-child {
      min-width: 142rpx;
    }

    image {
      width: 14rpx;
      height: 10rpx;
      margin-left: 10rpx;
      vertical-align: middle;
    }
  }

  .activeCls {
    color: #fa6138;
  }

  .item2 {
    margin-left: 100rpx;
    padding-top: 20rpx;
  }
}

.content-box {
  padding: 0 30rpx;
}

.shopListBox {
  padding: 0 30rpx;

  .shopListBox_item {
    margin-top: 30rpx;
  }
}
</style>
