<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.businessName" type="text" @confirm="search" placeholder-style="color:#B3B3B3"
            placeholder="请输入关键字" @input="search" />
        </view>
      </view>
      <view class="tabsBox">
        <view class="type-box">
          <view class="item" @click.stop="pickerRef.open()">
            <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 ref="pickerRef" :columns="[selector]" keyName="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 { getBusinessList, getBusinessCategoryList } from "@/api/shop.js";
import ShopItem from "./components/ShopItem.vue";
const pickerRef = ref(null);
const regionSelectionRef = ref(null);
const instance = getCurrentInstance();

const placeholderH = ref(0);

const cityName = ref("武汉市");
const sIndex = ref(0);
const param = reactive({
  businessName: "",
  nearMe: true,
});
const RowsList = ref([]);
const tabCurrent = ref(0);
const typeList = ref([
  { name: "距离优先", order: "distance" },
  { name: "评分优先", order: "average" },
]);
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;
  let order = typeList.value[index]?.order || "distance";
  // console.log(param);
  param.nearMe = false;
  param.orderByColumn = undefined;
  param.isAsc = undefined;
  if (order == 'distance') {
    param.nearMe = true;
  } else {
    param.orderByColumn = 'average';
    param.isAsc = 'desc';
  }
  initData(param);
};

const confirmSelect = (e) => {
  // console.log(e);
  const idx = e?.indexs[0] ?? 0;
  // console.log(idx);
  selectIndex.value = idx;
  sIndex.value = idx;
  param.businessCategoryId = selector.value[idx]?.categoryId || undefined;
  // console.log(param);
  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: "全部分类", categoryId: "" }, ...(res.data || [])];
      // console.log(selector.value);
      if (id) {
        selector.value.forEach((v, i) => {
          if (String(v.categoryId) === String(id)) selectIndex.value = i;
        });
      }
    }
  });
};

// 获取当前位置
const getLoca = async () => {
  await uni.getLocation({
    type: "gcj02",
    success: (res) => {
      param.userLongitude = res.longitude;
      param.userLatitude = res.latitude;
      initData(param);
    },
    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);
  }
};

const initData = (params = {}) => {
  uni.showLoading({
    title: '加载中',
    mask: true
  })
  getBusinessList(params).then((res) => {
    uni.hideLoading();
    if (res && res.code == 200) {
      RowsList.value = res.data || [];
    } else {
      RowsList.value = [];
    }
  }).finally(() => {
    uni.stopPullDownRefresh();
  });
}


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

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

onPullDownRefresh(() => {
  initData(param);
  //   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>
