<template>
  <view class="home">
    <view class="nav-bar" v-if="opacity == 1">
      <u-navbar :bgColor="'#ffffff'">
        <view slot="left">
          <text>地址</text>
          <text class="iconfont icon-chevron-down"></text>
        </view>
        <view slot="center">
          <u-search
            placeholder="请输入搜索内容"
            :showAction="false"
            v-model="keyword"
          />
        </view>
      </u-navbar>
    </view>
    <!-- 顶部导航 -->
    <view
      class="home-header"
      :style="{ paddingTop: totalHeight + 'px', opacity: 1 - opacity }"
    >
      <view class="goto-address" @click="manualGetLocation">
        <text>地址</text>
        <text class="iconfont icon-chevron-down"></text>
      </view>
      <view
        class="search-item"
        @click="$Router.push('/pages/client/search/index')"
      >
        <u-search
          placeholder="请输入搜索内容"
          :showAction="false"
          v-model="keyword"
        />
      </view>
    </view>
    <!-- 轮播图 -->
    <view class="home-swiper">
      <u-swiper :list="swiperList" indicator @change="change" @click="click" />
    </view>
    <!-- 商品分类 -->
    <view class="home-list">
      <u-grid :border="false" col="5">
        <u-grid-item
          v-for="(item, index) in categories"
          :key="item.id"
          @tap="handleMenuClick(item)"
        >
          <u-icon
            :customStyle="{ paddingTop: 20 + 'rpx' }"
            :name="item.icon"
            :size="25"
          ></u-icon>
          <text class="grid-text">{{ item.name }}</text>
        </u-grid-item>
      </u-grid>
      <u-toast ref="uToast" />
    </view>
    <!-- 热门推荐 -->
    <view class="hot">
      <u-cell
        :border="false"
        value="查看更多"
        isLink
        @click="$Router.push('/pages/business/hot/index')"
      >
        <view slot="title" class="hot-title"> 热门推荐 </view>
      </u-cell>
      <block v-if="homeData.recommends && homeData.recommends.length > 0">
        <view>
          <u-grid :border="false" col="2">
            <u-grid-item
              @click="
                $Router.push(`/pages/business/detail/index?id=${item.id}`)
              "
              v-for="item in homeData.recommends"
              :key="item.id"
            >
              <recommend-item :item="item"></recommend-item>
            </u-grid-item>
          </u-grid>
        </view>
      </block>
      <block v-else>
        <u-empty
          icon="/static/default-graph/no-business.png"
          text="暂无推荐商家"
        ></u-empty>
      </block>
    </view>
    <!-- 附近商家 -->
    <view class="near">
      <u-cell
        :border="false"
        value="查看更多"
        isLink
        @click="$Router.push('/pages/business/nearby/index')"
      >
        <view slot="title" class="near-title"> 附近商家 </view>
      </u-cell>
      <block v-if="homeData.nears && homeData.nears.length > 0">
        <view>
          <u-grid :border="false" col="2">
            <u-grid-item
              @click="
                $Router.push(`/pages/business/detail/index?id=${item.id}`)
              "
              v-for="item in homeData.nears"
              :key="item.id"
            >
              <hot-item :item="item"></hot-item>
            </u-grid-item>
          </u-grid>
        </view>
      </block>
      <block v-else>
        <u-empty
          icon="/static/default-graph/no-business.png"
          text="暂无附近商家"
        ></u-empty>
      </block>
    </view>
  </view>
</template>

<script>
import { getHomePage, getCurrentLocation } from '@/api/home';
import { mapGetters } from 'vuex';
import RecommendItem from '@/components/merchant/RecommendItem.vue';
import HotItem from '@/components/merchant/HotItem.vue';
import { getHomePageApi, getCategoriesApi } from '@/api/tabbar/home';

export default {
  components: {
    RecommendItem,
    HotItem,
  },
  data() {
    return {
      list: [],
      keyword: '',
      swiperList: [
        'https://cdn.uviewui.com/uview/swiper/swiper1.png',
        'https://cdn.uviewui.com/uview/swiper/swiper2.png',
        'https://cdn.uviewui.com/uview/swiper/swiper3.png',
      ],
      homeData: {
        categories: [],
        nears: [],
        recommends: [],
      },
      scrollTop: 0,
    };
  },
  computed: {
    ...mapGetters(['location']),
    totalHeight() {
      return (
        uni.getSystemInfoSync().statusBarHeight +
        uni.getMenuButtonBoundingClientRect().height
      );
    },
    opacity() {
      if (this.scrollTop < this.totalHeight) {
        return (this.scrollTop / this.totalHeight).toFixed(2);
      }
      return 1;
    },
    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: 'grid-fill',
                name: '全部',
                type: { code: 'ALL', description: '全部' },
              },
            ])
          : initData.push({ id: 'all', icon: 'grid-fill', name: '全部' });
      return result;
    },
  },
  onPageScroll(e) {
    this.scrollTop = e.scrollTop;
  },
  onLoad() {
    setTimeout(() => {
      this.list = new Array(10000).fill(1);
    }, 5000);
    uni.getLocation({
      type: 'gcj02',
      success: res => {
        this.location.longitude = res.longitude;
        this.location.latitude = res.latitude;
        this.$store.commit('SET_LOCATION', {
          longitude: res.longitude,
          latitude: res.latitude,
        });
      },
      fail: () => {
        this.manualGetLocation();
      },
    });
  },
  methods: {
    change() {},
    click(name) {
      this.$refs.uToast.success(`点击了第${name}个`);
    },
    // 获取首页数据
    getHomeData(location) {
      getHomePageApi(location)
        .then(res => {
          this.homeData = res.data;
          // 将分类数据做缓存处理
          this.$store.commit('SET_CATEGORIES', this.homeData.categories);
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 手动选择城市
    manualGetLocation() {
      uni.chooseLocation({
        success: res => {
          this.$store.commit('SET_LOCATION', {
            longitude: res.longitude,
            latitude: res.latitude,
          });
        },
      });
    },
    // 点击菜单
    handleMenuClick(item) {
      if (item.id === 'all') {
        this.$Router.push('/pages/business/category')
      }else{
        this.$Router.push('/pages/business/list')
      }
    },
  },
  watch: {
    location: {
      handler: async function (newVal, oldVal) {
        const result = await getCurrentLocation(newVal);
        const param = Object.assign({}, { region: result.data.id }, newVal);
        this.getHomeData(param);
      },
    },
  },
};
</script>

<style lang="scss" scoped>
.home {
  background-color: #f0efef;
  .nav-bar {
    ::v-deep .u-navbar__content {
      background-color: #ffffff;
    }
  }
}

/* 头部搜索栏 */
.home-header {
  display: flex;
  align-items: center;
  height: 90rpx;
  line-height: 90rpx;
  padding: 0 20rpx;
  background-color: #ffffff;

  .goto-address {
    display: flex;
    align-items: center;

    .icon-sanjiaoxing1 {
      font-size: 24rpx;
      margin: 17rpx 10rpx 0 6rpx;
    }
  }
  .search-item {
    flex: 1;
  }
}

/* 轮播图 */
.home-swiper {
  padding: 20rpx;
  margin-bottom: 10rpx;
}

/* 商品分类 */
.home-list {
  background-color: #ffffff;
  height: 360rpx;
  margin: 0 20rpx 20rpx 20rpx;
  padding: 20rpx 0;
  border-radius: 10rpx;

  .grid-text {
    font-size: 12px;
    color: #909399;
    padding: 10rpx 0 20rpx 0rpx;
    box-sizing: border-box;
  }
}

/* 热门推荐 */
.hot {
  ::v-deep .u-cell__body {
    padding: 10rpx 20rpx;
    .hot-title {
      border-left: 4px solid $uni-color-primary;
      padding-left: 20rpx;
    }
  }
}
.near {
  ::v-deep .u-cell__body {
    padding: 10rpx 20rpx;
    .near-title {
      border-left: 4px solid $uni-color-primary;
      padding-left: 20rpx;
    }
  }
}
</style>
