<template>
  <view class="list-box">
    <view class="list">
      <swiper
        class="item"
        :style="{
          height: '250px',
        }"
        indicator-color="#EDEDED"
        indicator-active-color="#F83D3D"
        :circular="true"
        :indicator-dots="true"
        :autoplay="true">
        <swiper-item v-for="(item, index) in bannerList" :key="index">
          <image
            :style="{
              width: '100%',
              height: '100%',
            }"
            :src="item.url"
            @tap="toPage(item.jump)" />
        </swiper-item>
      </swiper>
      <view
        class="item"
        v-for="(item, index) in list1"
        :key="index"
        @click="toMerDetails(item)">
        <image
          :style="{
            height: '200px',
          }"
          :src="item.head_photo" />
        <view class="text">
          <view class="title">{{ item.name }}</view>
          <view class="list_local">
            <view class="icon iconfont icon-dizhi"></view>
            <view class="desc"
              >距离我{{
                calculateDistance(
                  userLocalNum.t,
                  userLocalNum.l,
                  Number(item.lat),
                  Number(item.lon),
                )
              }}
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="list">
      <view
        class="item"
        v-for="(item, index) in list2"
        :key="index"
        @click.stop="toMerDetails(item)">
        <image
          :style="{
            height: '200px',
          }"
          :src="item.head_photo" />
        <view class="text">
          <view class="title">{{ item.name }}</view>
          <view class="list_local">
            <view class="icon iconfont icon-dizhi"></view>
            <view class="desc"
              >距离我{{
                calculateDistance(
                  userLocalNum.t,
                  userLocalNum.l,
                  Number(item.lat),
                  Number(item.lon),
                )
              }}
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import {ref} from 'vue';
import Taro from '@tarojs/taro';
import {calculateDistance, parseQueryString} from '@/utils';
import {bindParent, getBanner} from '@/api/user';
import {getMerList} from '@/api/goods';

const classId = defineModel({default: 0});

const list1 = ref<Array<MerData>>([]);
const list2 = ref<Array<MerData>>([]);

Taro.useLoad(() => {
  init();
});

const init = async () => {
  Taro.showLoading({
    title: '加载中',
  });
  await get_mer_list();
  await get_banner_list();
  if (Taro.getStorageSync('token') && Taro.getStorageSync('bind_id')) {
    try {
      const res = await bindParent({
        uid: Taro.getStorageSync('bind_id'),
      });
      Taro.showToast({
        title: res.msg,
      });
      Taro.removeStorageSync('bind_id');
    } catch (error) {
      Taro.removeStorageSync('bind_id');
      throw error;
    }
  }
  Taro.hideLoading();
};

interface MerData {
  ID: number;
  name: string;
  head_photo: string;
  lat: string;
  lon: string;
}

const merdata = ref<MerData[]>([]);

const userLocalNum = ref({
  l: 0,
  t: 0,
});

const pageVal = ref({
  page: 1,
  total: 0,
});

const get_mer_list = async () => {
  Taro.getLocation({
    type: 'wgs84',
    success: res => {
      userLocalNum.value.l = res.longitude;
      userLocalNum.value.t = res.latitude;
    },
  });
  const res = await getMerList({
    PageNum: pageVal.value.page,
    PageSize: 10,
    class_id: classId.value,
  });
  pageVal.value.total = res.data.total;

  merdata.value = res.data.data;
  const middleIndex = Math.floor(merdata.value.length / 2);
  const arr1 = merdata.value.slice(0, middleIndex);
  const arr2 = merdata.value.slice(middleIndex);
  list1.value.push(...arr1);
  list2.value.push(...arr2);
  merdata.value = [];
};
const bannerList = ref<any[]>([]);

const get_banner_list = async () => {
  const {data}: any = await getBanner();
  bannerList.value = data.data;
};

const toPage = async (url: string) => {
  console.log(url);
  // url转对象
  const obj = parseQueryString(url);
  if (obj.type === '1') {
    const {data: res} = await getMerList({});
    const mer = res.data.filter(item => item.bid === obj.bid)[0];
    Taro.setStorageSync('mer_info', mer);
  }
  Taro.navigateTo({
    url,
  });
};

const toMerDetails = item => {
  Taro.setStorageSync('mer_info', item);
  Taro.navigateTo({
    url: `/pages/mer/mer_detail/index`,
  });
};

Taro.useReachBottom(() => {
  const currTotal = list1.value.length + list2.value.length;
  if (currTotal === pageVal.value.total) {
    Taro.showToast({
      title: '没有更多了',
      icon: 'none',
    });
  } else {
    pageVal.value.page += 1;
    get_mer_list();
  }
});
</script>

<style lang="scss">
.list-box {
  margin: 20px;
  padding: 10px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;

  .list {
    overflow: scroll;

    .item {
      width: 340px;
      margin-bottom: 18px;
      border-radius: 20px;
      background-color: #fff;

      image {
        width: 100%;
        border-radius: 15px;
      }

      .text {
        padding: 15px;

        .title {
          color: #333333;
          font-size: 30px;
          overflow: hidden;
          text-overflow: ellipsis;
          // white-space: nowrap;
        }

        .list_local {
          display: flex;
          align-items: center;
          justify-content: flex-start;
          color: #808080;
          margin-top: 8px;

          .icon {
            display: inline-block;
            font-size: 30px;
          }

          .desc {
            font-size: 28px;
          }
        }
      }
    }
  }
}
</style>
