<template>
  <view class="container">
    <view class="container-top-box">
      <view class="top-title">
        <view class="address" @click.stop="manualGetLocation">
          <span>{{ nowAddress }}</span>
          <u-icon name="arrow-down-fill" color="#333333" size="10"></u-icon>
        </view>
        <view class="title">车旅程</view>
        <view></view>
      </view>
      <view class="top-search">
        <u-search
          placeholder="请输入搜索内容"
          :showAction="false"
          v-model="keyword"
          @click="$Router.push('/pagesHome/homeSearch/index')"
          bgColor="#fff"
          :disabled="true"
        />
      </view>

      <view class="top-swiper-box">
        <u-swiper :list="swiperUrlList" @click="handlerSwiperSkip" indicator circular />
      </view>
    </view>

    <view class="container-tabbar-box">
      <view class="tabar-box">
        <view
          class="tabbar-item"
          v-for="(item, index) of categories"
          :key="index"
          @tap="handleMenuClick(item)"
        >
          <view class="item-img">
            <image class="img" :src="item.icon"></image>
          </view>
          <view class="item-name">{{ item.name }}</view>
        </view>
      </view>
    </view>

    <view class="container-list-box">
      <view class="item-box">
        <view class="item-top">
          <view class="top-title">热门推荐</view>
          <view
            class="top-more"
            @click="$Router.push('/pagesHome/popularNearby/index?queryType=1')"
          >
            <span>查看更多</span>
            <u-icon name="arrow-right" color="#999999" size="14"></u-icon>
          </view>
        </view>
        <view class="item-list">
          <view
            class="item"
            v-for="(item, index) in homeData.recommends"
            :key="item.id"
            @click="$Router.push(`/pagesHome/marketer/index?id=${item.id}`)"
          >
            <home-store v-if="index < 4" :item="item" isType="hot"></home-store>
          </view>
        </view>
      </view>

      <view class="item-box">
        <view class="item-top">
          <view class="top-title">附近商家</view>
          <view
            class="top-more"
            @click="$Router.push('/pagesHome/popularNearby/index?queryType=0')"
          >
            <span>查看更多</span>
            <u-icon name="arrow-right" color="#999999" size="14"></u-icon>
          </view>
        </view>
        <view class="item-list">
          <view
            class="item"
            v-for="(item, index) in homeData.nears"
            :key="item.id"
            @click="$Router.push(`/pagesHome/marketer/index?id=${item.id}`)"
          >
            <home-store v-if="index < 4" :item="item" isType="near"></home-store>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getCurrentLocation, getHomePageApi, getSwiperListApi } from '@/api/client/home';
import { inviteBind } from '@/api/client/mine.js';
import { mapGetters } from 'vuex';
export default {
  name: 'home',
  data() {
    return {
      list: [],
      keyword: '',
      swiperUrlList: [], // 轮播图url列表
      swiperList: [],
      homeData: {
        categories: [],
        nears: [],
        recommends: [],
      },
      queryParams: {
        longitude: '',
        latitude: '',
        region: '',
      },
      nowAddress: '', //当前地址
    };
  },
  computed: {
    ...mapGetters(['location', 'userId', 'invitationCode']),
    categories() {
      let initData = this.homeData.categories.map(item => {
        if (!item.icon) {
          item.icon = 'level';
        }
        return item;
      });
      let result =
        initData.length > 14
          ? initData.splice(0, 14).concat([
              {
                id: 'all',
                icon: '/static/pages/home/home-all.png',
                name: '全部',
                type: {
                  code: 'ALL',
                  description: '全部',
                },
              },
            ])
          : initData.push({
              id: 'all',
              icon: '/static/pages/home/home-all.png',
              name: '全部',
            });
      return result;
    },
  },
  onShow() {
    // 如果 invitationCode 存在且不等于特殊值时执行代码
    if (this.invitationCode) {
      let params = {
        userId: this.invitationCode,
        targetId: this.userId,
        type: 1,
      };
      inviteBind(params).then(res => {
        if (res && res.code == 200) {
          uni.showToast({
            title: '您已成功加入团队',
            icon: 'success',
            dration: 2000,
          });
        }
      });
      this.$store.commit('SET_INVITATIONCODE', '');
    } else {
    }
  },
  mounted() {
    this.getSwiperList();
    // 页面显示时  获取当前零维度
    uni.getLocation({
      type: 'gcj02',
      success: res => {
        let { longitude, latitude } = res;
        this.queryParams.longitude = longitude;
        this.queryParams.latitude = latitude;
        // getCurrentLocation 获取当前编码region
        this.handlerGetRegion(longitude, latitude);
      },
      fail: () => {
        this.manualGetLocation();
      },
    });
  },
  methods: {
    // 获取当前编码region
    handlerGetRegion(longitude, latitude) {
      let point = `${latitude},${longitude}`;
      getCurrentLocation({
        point,
      }).then(res => {
        let { city, district, id } = res.data;
        this.queryParams.region = res.data.id;
        if (district) {
          this.nowAddress = district.name;
        } else if (city) {
          this.nowAddress = city.name;
        } else {
          this.nowAddress = '地图';
        }
        this.getHomeData(this.queryParams);
        this.$store.commit('SET_LOCATION', {
          longitude: longitude,
          latitude: latitude,
          region: res.data.id,
          address: res.data.name,
        });
      });
    },
    /* 轮播图 */
    getSwiperList() {
      getSwiperListApi().then(res => {
        this.swiperList = res.data;
        res.data.map(rs => {
          this.swiperUrlList.push(rs.viewUrl);
        });
      });
    },
    // 获取首页数据
    getHomeData(location) {
      getHomePageApi(location).then(res => {
        this.homeData = res.data;
        // 将分类数据做缓存处理
        this.$store.commit('SET_CATEGORIES', this.homeData.categories);
      });
    },
    // 手动选择城市
    manualGetLocation() {
      uni.chooseLocation({
        success: res => {
          let { longitude, latitude } = res;
          this.queryParams.longitude = longitude.toFixed(5);
          this.queryParams.latitude = latitude.toFixed(5);
          this.handlerGetRegion(longitude.toFixed(5), latitude.toFixed(5));
        },
        fail: err => {},
      });
    },
    // 点击swiper跳转
    handlerSwiperSkip(e) {
      console.log('@@@swiperList', this.swiperList[e]);
    },
    // 点击菜单
    handleMenuClick(item) {
      if (item.name === '全部') {
        this.$Router.push('/pagesHome/category/index');
      } else {
        uni.navigateTo({
          url: `/pagesHome/category/categoryStoreList?id=${item.id}&name=${item.name}`,
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  font-size: 28rpx;
  min-height: calc(100vh - 30rpx);
  background-color: #f9f9f9;
  padding-bottom: 30rpx;
  .container-top-box {
    padding: 108rpx 32rpx 34rpx;
    box-sizing: border-box;
    background: linear-gradient(180deg, #d4e3ff 0%, #f0f1f9 53%, #f9f9f9);

    .top-title {
      display: grid;
      grid-template-columns: 33% 33% 33%;
      justify-content: space-between;
      margin-bottom: 34rpx;
      align-items: center;

      .address {
        display: flex;
        color: #333333;
      }

      .title {
        color: #0c1223;
        font-weight: bold;
        font-size: 34rpx;
        text-align: center;
      }
    }

    .top-search {
      margin-bottom: 34rpx;
    }

    .top-swiper-box {
      width: 100%;
      height: 256rpx;
      border-radius: 20rpx;
      background-color: #fff;
    }
  }

  .container-tabbar-box {
    padding: 0 32rpx 0;

    .tabar-box {
      width: 100%;
      border-radius: 20rpx;
      padding: 26rpx;
      box-sizing: border-box;
      background-color: #fff;
      display: grid;
      grid-template-columns: repeat(5, 18%);
      justify-content: space-between;
      grid-gap: 24rpx 0;
      box-shadow: 0rpx 4rpx 16rpx 0rpx rgba(0, 0, 0, 0.05);
      .tabbar-item {
        text-align: center;

        .item-img {
          .img {
            width: 56rpx;
            height: 56rpx;
          }
        }

        .item-name {
          margin-top: 16rpx;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
  }

  .container-list-box {
    padding: 0 32rpx 0;
    box-sizing: border-box;
    .item-box {
      margin-top: 32rpx;

      .item-top {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 32rpx;
        .top-title {
          color: #0c1223;
          font-size: 34rpx;
          font-weight: bold;
        }

        .top-more {
          display: flex;
          color: #999999;
          font-size: 24rpx;
          align-items: center;
        }
      }
      .item-list {
        display: grid;
        grid-template-columns: repeat(2, 47.81%);
        justify-content: space-between;
        .item {
          border-radius: 16rpx;
        }
      }
    }
  }
}
</style>
