<template>
  <div class="shop-con" ref="dom">
    <m-tabs
      v-if="isShowSticky && showTabs"
      v-model="tabIndex"
      :fixed="true"
      :tabs="tabList"
      class="tab-list"
      @change="tabChange"
    />
    <mescroll-vue
      ref="mescrollRef"
      @init="mescrollInit"
      :down="downOptions"
      :up="upOptions"
      @topclick="topClick"
    >
      <div class="shop-con-wrap">
        <shop-header />
        <div class="shop-bg-img">
          <img :src="shopData.shopImage" class="bg-img" />
          <div class="mask" />
        </div>
        <div class="desc flex-default">
          <div class="thumb">
            <img :src="shopData.shopImage" style="width: 100%; height: 100%" />
          </div>
          <div class="content" @click="goInfo">
            <div class="name">
              <span>{{ shopData.shopName }}</span>
              <m-icon icon="icon-more-light" :size="10" />
            </div>
            <div class="data flex-default">
              <div class="label">关注数&nbsp;&nbsp;{{ getfollows }}</div>
              <!-- <div class="label">
                好评率&nbsp;&nbsp;{{ statistics.commont | commontFilter }}
              </div> -->
            </div>
          </div>
          <div class="collect flex-default" @click="followMerchant">
            <m-icon icon="icon-collect2" :size="12" />
            <div class="text">{{ isFollows ? "取消关注" : "关注" }}</div>
          </div>
        </div>
        <div class="swipe-con">
          <van-swipe class="swipe" :autoplay="5000" @change="swipeChange">
            <van-swipe-item
              v-for="(item, index) of bannerList"
              :key="`banner-item-${index}`"
              class="swipe-item"
            >
              <div class="swipe-img" @click="openBanner(item)">
                <img
                  :src="item.bannerImage"
                  style="width: 100%; height: 100%"
                />
              </div>
            </van-swipe-item>
            <template #indicator>
              <div class="custom-indicator flex-center">
                <div
                  v-for="item of bannerList.length"
                  :key="`indicator-${item}`"
                  :class="item - 1 == current ? ['item', 'active'] : ['item']"
                />
              </div>
            </template>
          </van-swipe>
        </div>
        <div class="coupon-center flex-default" @click="toCouponCenter">
          <div class="text" />
          <div class="more flex-default">
            <m-icon icon="icon-more-white" :size="10" />
          </div>
        </div>
        <div class="shop-goods-con">
          <div class="shop-goods-tabs" v-if="showTabs">
            <m-tabs
              v-model="tabIndex"
              :tabs="tabList"
              class="tab-list"
              @change="tabChange"
              background="transparent"
              :style="{ width: tabWidth }"
            />
          </div>
          <div class="goods-con flex-default bg-grey">
            <list-item
              v-for="(item, index) in goods"
              :key="index"
              :itemData="item"
            />
          </div>
        </div>
      </div>
    </mescroll-vue>
  </div>
</template>

<script>
import ShopHeader from "./shop-header";
import ListItem from "./list-item.vue";
import { MescrollMixin } from "@/mixins";
export default {
  mixins: [MescrollMixin], // 使用mixin (在main.js注册全局组件)
  components: {
    ShopHeader,
    ListItem,
  },
  data() {
    return {
      downOptions: {
        // autoShowLoading: false,
        // auto: true,
        callback: this.downCallback,
      },
      upOptions: {
        callback: this.upCallback,
        onScroll: this.scroll,
      },
      current: 0,
      bannerList: [],
      tabIndex: 0,
      tabList: [],
      dotsStyles: {
        bottom: 32,
        width: 14,
        height: 3,
        border: "none",
        selectedBorder: "none",
        backgroundColor: "rgba(256, 256, 256, .3)",
        selectedBackgroundColor: "rgba(256, 256, 256)",
      },
      merchantId: "",
      isFollows: false,
      shopData: {},
      preIndex: 0, // 前一个菜单下标
      //   navTop: uni.upx2px(940), // nav距离到顶部的距离 (如计算不准确,可直接写死某个值)
      navTop: 470, // nav距离到顶部的距离 (如计算不准确,可直接写死某个值)
      isShowSticky: false, // 是否悬浮
      statistics: {
        commont: 0,
        follow: 0,
      },
      tabsLoading: false,
    };
  },
  mounted() {
    this.merchantId = this.$route.params.merchantId;
    this.requestData();
    if (this.hasLogin) {
      this.isFollow();
    }
    this.getShopCount();
    this.getShopBanner();
  },
  computed: {
    // 列表数据
    goods() {
      if (this.tabList[this.tabIndex]) {
        return this.tabList[this.tabIndex].goods;
      } else {
        return [];
      }
    },
    getfollows() {
      if (this.statistics.follow < 10000) {
        return this.statistics.follow;
      } else {
        const follow = this.statistics.follow / 10000;
        return follow.toFixed(2) + '万';
      }
    },
    showTabs() {
      return this.tabList && this.tabList.length > 0;
    },
     tabWidth() {
      let len = this.tabList.length;
      if (len <= 4) {
        return len * 80 + "px";
      }
      return "100%";
    },
  },
  filters: {
    commontFilter(val) {
      if (typeof val === "number") {
        return val.toFixed(1);
      } else {
        return "";
      }
    },
  },
  methods: {
    goInfo() {
      let params = { merchantId: this.merchantId };
      this.$router.push({ name: "shop-info", params });
    },
    getShopCount() {
      this.$api({
        apiName: "getShopCount",
        postData: { merchantId: this.merchantId },
        success: (res) => {
          this.statistics = res;
        },
      });
    },
    getShopBanner() {
      this.$api({
        apiName: "getShopBanner",
        postData: { merchantId: this.merchantId },
        success: (res) => {
          this.bannerList = res;
        },
      });
    },
    isFollow() {
      this.$api({
        apiName: "isFollow",
        requiresAuth: false,
        postData: { merchantId: this.merchantId },
        success: (res) => {
          this.isFollows = res;
        },
      });
    },
    requestData() {
      this.$api({
        apiName: "getShop",
        postData: { merchantId: this.merchantId },
        success: (res) => {
          this.shopData = res;
        },
      });
    },
    getShopNavigation(page) {
      this.$api({
        apiName: "getShopNavigation",
        postData: { merchantId: this.merchantId },
        success: (res) => {
          let dItem = {
            navigationId: "all",
            name: "全部",
            goods: null,
            hasNext: true,
            num: 1,
            y: 0,
            curPageLen: 0,
          };
          let arr = [dItem];
          for (let item of res) {
            item.name = item.navigationName;
            item.goods = null;
            item.hasNext = true;
            item.num = 1;
            (item.y = 0), (item.curPageLen = 0);
            arr.push(item);
          }
          this.tabList = arr;
          this.tabsLoading = true;
          this.upCallback(page);
        },
      });
    },
    followMerchant() {
      if (!this.checkLogin()) {
        return;
      }
      this.$showLoading();
      this.$api({
        apiName: "followMerchantId",
        postData: {
          merchantId: this.merchantId,
        },
        success: (res) => {
          this.$toast(this.isFollows ? "已取消" : "关注成功");
          this.isFollow();
        },
        complete: (res) => {
          this.$hideLoading();
        },
      });
    },
    initData() {
      this.getShopNavigationGoods({ num: 1, size: 10 });
      this.tabList[this.tabIndex].goods = [];
      this.$nextTick(() => {
        this.mescroll.setPageNum(2);
      });
    },
    getShopNavigationGoods(page) {
      let curTab = this.tabList[this.tabIndex];
      let apiName = "getShopNavigationGoods";
      if (curTab.navigationId == "all") {
        apiName = "getAllShopGoods";
      }
      this.$api({
        apiName,
        postData: {
          page: page.num,
          paramA: this.merchantId,
          paramB: this.tabList[this.tabIndex].navigationId,
          size: page.size,
          param: this.merchantId,
        },
        success: (res) => {
          let curTab = this.tabList[this.tabIndex];
          curTab.hasNext = true;
          let arr = res.list;
          if (page.num == 1) {
            curTab.goods = arr;
          } else {
            curTab.goods = curTab.goods.concat(arr);
          }
          this.mescroll.endBySize(res.list.length, res.total);
          setTimeout(() => {
            // 需先隐藏加载状态
            this.mescroll.endSuccess(res.list.length);
            // 再记录当前页的数据
            curTab.num = page.num; // 页码
            curTab.curPageLen = res.list.length; // 当前页长
            curTab.hasNext = this.mescroll.optUp.hasNext; // 是否还有下一页
            // 设置nav到顶部的距离 (需根据自身的情况获取navTop的值, 这里放到列表数据渲染完毕之后)
            // 也可以放到onReady里面,或者菜单顶部的数据(轮播等)加载完毕之后..
            if (!this.navTop) this.setNavTop();
            // 保持tab悬浮,列表数据显示第一条
            if (this.isChangeTab) {
              this.isChangeTab = false;
              this.$hideLoading();
              if (this.isShowSticky) this.mescroll.scrollTo(this.navTop, 0);
            }
          }, 20);
        },
        fail: () => {
          this.mescroll.endErr();
        },
        complete: (res) => {
          this.$hideLoading();
        },
      });
    },
    /*下拉刷新的回调 */
    downCallback() {
      // 这里加载你想下拉刷新的数据, 比如刷新轮播数据
      // loadSwiper();
      this.tabsLoading = false;
      // 下拉刷新的回调,默认重置上拉加载列表为第一页 (自动执行 page.num=1, 再触发upCallback方法 )
      this.mescroll.resetUpScroll();
    },
    /*上拉加载的回调: 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10 */
    upCallback(page) {
      if (this.tabsLoading) {
        if (this.isChangeTab) {
          this.mescroll.hideUpScroll(); // 切换菜单,不显示mescroll进度, 显示系统进度条
          this.$showLoading();
        }
        if (this.tabList.length > 0) {
          this.getShopNavigationGoods(page);
        } else {
          this.mescroll.endSuccess(0);
        }
      } else {
        this.getShopNavigation(page);
      }
    },
    setNavTop() {
      // 返回顶部
      let view = uni.createSelectorQuery().select("#tabInList");
      view
        .boundingClientRect((data) => {
          this.navTop = data.top; // 到屏幕顶部的距离
        })
        .exec();
    },
    scroll(mescroll, y, isUp) {
      // console.log('滚动条位置 = ' + this.mescroll.getScrollTop() + ', navTop = ' + this.navTop);
      // 菜单悬浮的原理: 监听滚动条的位置大于某个值时,控制顶部菜单的显示和隐藏
      if (y >= this.navTop) {
        this.isShowSticky = true; // 显示悬浮菜单
      } else {
        this.isShowSticky = false; // 隐藏悬浮菜单
      }
    },
    // 点击回到顶部按钮时,先隐藏悬浮菜单,避免闪动
    topClick() {
      this.isShowSticky = false;
    },
    // 切换菜单
    tabChange(index) {
      this.tabIndex = index
      // 记录前一个菜单的数据
      let preTab = this.tabList[this.preIndex];
      preTab.y = this.mescroll.getScrollTop(); // 滚动条位置

      this.preIndex = index;
      // 当前菜单的数据
      let curTab = this.tabList[index];

      if (!curTab.goods) {
        // 没有初始化,则初始化
        this.isChangeTab = true;
        this.mescroll.resetUpScroll();
      } else {
        // 初始化过,则恢复之前的列表数据
        this.mescroll.setPageNum(curTab.num + 1); // 恢复当前页码
        this.mescroll.endSuccess(curTab.curPageLen, curTab.hasNext); // 恢复是否有下一页或显示空布局
        this.$nextTick(() => {
          this.mescroll.scrollTo(curTab.y, 0); // 恢复滚动条的位置
        });
      }
    },
    toCouponCenter() {
      let params = { merchantId: this.merchantId };
      this.$router.push({ name: "shop-coupon-center", params });
    },
    swipeChange(index) {
      this.current = index;
    },
  },
};
</script>

<style lang="less">
.shop-con {
  height: 100vh;
  background: #f5f7fb;
  position: relative;
  .shop-bg-img {
    position: absolute;
    width: 100%;
    top: 0;
    height: calc(~"44px + 134px");
    z-index: -1;
    .bg-img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    .mask {
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
      background-color: rgba(0, 0, 0, 0.5);
    }
  }
  .shop-con-wrap {
    height: 100%;
    z-index: 10;
    position: relative;
  }
  .shop-con-wrap > .desc {
    width: 100%;
    height: 134px;
    background: rgba(0, 0, 0, 0.5);
    // border-radius: 0 0 20px 20px;
    padding: 12px 16px 78px;
    padding-top: 12px;
    align-items: center;
    margin-bottom: -55px;
    z-index: 1;
    > .thumb {
      width: 44px;
      height: 44px;
      margin-right: 10px;
      img {
        border-radius: 4px;
        object-fit: cover;
      }
    }

    > .content {
      flex: 1;
    }

    > .content .name {
      color: #ffffff;
      font-size: 18px;
      font-weight: bold;
      line-height: 25px;
      margin-bottom: 4px;
      .m-icon {
        margin-left: 5px;
      }
    }

    > .content > .data {
      color: #f1f1f1;
      align-items: center;
    }

    > .content > .data > .label {
      font-size: 10px;
      line-height: 14px;
      color: #f1f1f1;
      margin-right: 16px;
    }

    > .collect {
      align-items: center;
      height: 24px;
      border-radius: 22px;
      background: #FA9F37;
      padding: 0 9px;

      .text {
        font-size: 12px;
        color: #ffffff;
        margin-left: 4px;
      }
    }
  }
  .shop-con-wrap > .swipe-con {
    margin-bottom: 20px;
    padding: 0 8px;
    > .swipe {
    }
    .swipe-item {
      height: 280px;
      padding: 0 8px;
      width: 100%;
      height: 280px;
    }

    .swipe-img {
      width: 100%;
      height: 100%;
      // background-color: #dd2e41;
      border-radius: 10px;
      overflow: hidden;
    }

    .custom-indicator {
      width: 100%;
      position: absolute;
      bottom: 10px;
      > .item {
        background: #ffffff;
        width: 14px;
        height: 3px;
        border-radius: 2px;
        opacity: 0.3;
        margin-right: 3px;
        &:last-of-type {
          margin-right: 0;
        }
        &.active {
          opacity: 1;
        }
      }
    }
  }
  .shop-con-wrap > .coupon-center {
    width: 100%;
    height: 45px;
    padding: 0 16px;
    justify-content: space-between;
    align-items: center;
    background: center/contain no-repeat
      url("~@/assets/img/coupon-center-bg.png");
    background-color: #ffffff;
    border-radius: 10px;
    // margin-bottom: 17px;
    .text {
      width: 60px;
      height: 15px;
      background: center/contain no-repeat
        url("~@/assets/img/coupon-center-text.png");
    }

    .more {
      width: 16px;
      height: 16px;
      background: #fa6400;
      border-radius: 50%;
      align-items: center;
      //   justify-content: center;
      padding-left: 2px;
    }
  }
  .shop-con-wrap > .shop-goods-con {
    .shop-goods-tabs {
      padding-right: 150px;
      padding-left: 8px;
      width: 100%;
      .van-tabs__nav {
        background: transparent;
      }
      .m-tabs {
        background-color: transparent;
        border: 0;
        height: 44px !important;
      }
      &.tabsfixed {
        background-color: #ffffff;
        position: fixed;
        top: 0;
        left: 0;
        z-index: 1000;
      }
    }
    .goods-con {
      padding: 0 8px;
      padding-top: 15px;
      flex-wrap: wrap;
      justify-content: space-between;
      &.tabsfixed {
        padding-top: calc(44px + 8px);
      }
    }
  }
}
</style>
