<template>
  <view class="container-news">
    <view class="nav" v-if="isStick"></view>
    <view class="msg" @click="goToMsg">
      <text class="iconfont3 msgCenter">&#xe62a;</text>
      <text>消息</text>
      <text class="msgTxt" v-if="msgCenter==0?false:msgCenter">{{msgCenter}}</text>
    </view>
    <view id="header" v-if="swiperlist.length || bannerList.length">
      <view class="top" v-if="swiperlist.length > 0">
        <template>
          <swiper class="swiper" circular :autoplay="true" :interval="10000" :indicator-dots="true">
            <swiper-item v-for="(item, index) in swiperlist" :key="item.id">
              <view class="swiper-item" @click="$mUtil.imgLink(item.model_type, item.model_id, item.url, item.shop_id)">
                <image :src="item.cover" mode="widthFix"></image>
              </view>
            </swiper-item>
          </swiper>
        </template>
      </view>
      <view class="banner" v-if="bannerList.length > 0">
        <image :src="bannerList[0].cover" mode="widthFix"
          @click="$mUtil.imgLink(bannerList[0].model_type, bannerList[0].model_id, bannerList[0].url, bannerList[0].shop_id)">
        </image>
      </view>
    </view>
    <view class="main" :class="{'stickMain': isStick}">
      <view class="tabs" :class="{'stickTabs': isStick}">
        <scroll-view scroll-x class="scorll-x" :scroll-left="scrollLeft" :show-scrollbar="false">
          <view class="tab" :class="{'active': current == index}" v-for="(item, index) in list" :key="item.id"
            :id="'item'+index" @click="tabsChange(index)">
            <view class="">{{item.name}}</view>
          </view>
        </scroll-view>
      </view>
      <swiper class="list-swiper" :style="{height: tabHeight[current]+'px'}" :current="tabIndex" @change="swiperChange">
        <swiper-item class="swiper-item" v-for="(item, index) in list" :key="index">
          <!-- <scroll-view scroll-y style="height: 100%;width: 100%;" @scrolltoupper="topScroll" @scrolltolower="loadMore"
            :refresher-enabled="true" :refresher-triggered="triggered" :refresher-threshold="100"
            refresher-background="white" @refresherpulling="onPulling" @refresherrefresh="onRefresh"
            @refresherrestore="onRestore" @refresherabort="onAbort"> -->
          <news :classify_id="item.id" :ref="'page' + index" :id="'page' + index" @getSwiperHeight="getSwiperHeight">
          </news>
          <!-- </scroll-view> -->
        </swiper-item>
      </swiper>
    </view>
  </view>
</template>

<script>
  import news from '@/components/news';
  export default {
    components: {
      news
    },
    data() {
      return {
        swiperlist: [],
        msgCenter: null,
        headerHeight: 0,
        isStick: false,
        list: [],
        scrollLeft: 0,
        totalCount: 0,
        current: 0,
        tabIndex: 0,
        pageList: [],
        triggered: false,
        tabHeight: [],
        systemInfo: {},
        tabScrollTop: [],
        scrollTop: 0,
        bannerList: []
      }
    },
    onLoad() {
      this.freshing = false;
      setTimeout(() => {
        this.triggered = true;
      }, 1000)
      uni.getSystemInfo({
        success: res => {
          this.systemInfo = res
        }
      })
      this.getLocation()
      this.getSwiperList()
      this.getBanner()
      this.getClassify()
    },
    onShow() {
      this.getmessageNum()
    },
    onPageScroll(e) {
      if (e) {
        if (e.scrollTop >= this.headerHeight) {
          this.isStick = true
        } else {
          this.isStick = false
        }
        this.scrollTop = e.scrollTop
        this.getSwiperHeight()
      }
    },
    onReachBottom() {
      this.loadMore()
    },
    onPullDownRefresh() {
      this.tabScrollTop = []
      this.getmessageNum()
      this.getSwiperList()
      this.getBanner()
      this.getClassify(true)
      // this.getSwiperList()
      setTimeout(() => {
        uni.stopPullDownRefresh();
      }, 300)
    },
    methods: {
      // 获取经纬度
      getLocation() {
        uni.getLocation({
          type: 'wgs84',
          geocode: true,
          success: (res) => {
            uni.setStorageSync('locationObj', res)
          }
        });
      },
      // 获取轮播
      getSwiperList() {
        this.$http.get('/ad/ad/getShopAdByAdL/0/news-swiper').then(res => {
          if (res.code == 200) {
            this.swiperlist = res.list.slice(0, 6)
            this.$nextTick(() => {
              this.getDomHeight()
            })
          }
        })
      },
      // 获取banner
      getBanner() {
        this.$http.get('/ad/ad/getShopAdByAdL/0/news-banner').then(res => {
          if (res.code == 200) {
            this.bannerList = res.list
            this.$nextTick(() => {
              this.getDomHeight()
            })
          }
        })
      },
      async getSwiperHeight() {
        let minHeight = this.systemInfo.windowHeight - 44;
        let rect = await this.getGoodDom();
        if (rect && rect.height !== 0 && rect.height > minHeight) {
          this.tabHeight[this.current] = rect.height
          this.$forceUpdate()
        }
      },
      getGoodDom() {
        let self = this;
        return new Promise(resolve => {
          this.$nextTick(() => {
            let query = uni.createSelectorQuery();
            // #ifndef MP-ALIPAY
            query = query.in(this)
            // #endif
            query.select('#page' + this.current).boundingClientRect(data => {
              if (!data)
                return
              resolve(data)
            }).exec();
          })
        })
      },
      // 获取头部高度
      getDomHeight() {
        this.$u.getRect('#header').then(res => {
          this.headerHeight = res.height
        })
      },
      setScrollLeft(i) {
        let winWidth = uni.getSystemInfoSync().windowWidth - uni.upx2px(30)
        this.scrollLeft = this.tabarr[i].left + (this.tabarr[i].width / 2) - (winWidth / 2)
      },
      getWidth() { //得到元素的宽高
        let view = uni.createSelectorQuery().in(this);
        for (let i = 0; i < this.list.length; i++) {
          view.select('#item' + i).boundingClientRect();
        }
        view.exec(res => {
          this.tabarr = res
        })
      },
      /**获得消息数量 */
      getmessageNum() {
        let token = uni.getStorageSync("apiToken")
        if (token) {
          this.$http.get("/private/message/unread-num").then(res => {
            if (res && res.code == 200) {
              this.msgCenter = res.data
            }
          })
        } else {
          this.msgCenter = 0
        }
      },
      goToMsg() {
        let token = uni.getStorageSync("apiToken")
        if (!token) {
          uni.navigateTo({
            url: "/pages/login/index"
          })
        } else {
          uni.navigateTo({
            url: "/pages/research/setup/myMsg"
          })
        }
      },
      // 获取资讯分类
      getClassify(refresh) {
        this.$http.get('/information/classify/list').then(res => {
          if (res && res.code == 200) {
            this.list = [...[{
              id: '',
              name: '推荐'
            }], ...res.list]
            setTimeout(() => {
              this.$nextTick(() => {
                this.getWidth()
                for (let i = 0; i < this.list.length; i++) {
                  let item = this.$refs['page' + i]
                  if (Array.isArray(item)) {
                    this.pageList.push(item[0])
                  } else {
                    this.pageList.push(item)
                  }
                }
                this.switchTab(this.tabIndex, refresh);
              })
            }, 300)
          }
        })
      },
      switchTab(index, refresh) {
        this.$nextTick(() => {
          this.getSwiperHeight()
        })
        if (refresh) {
          this.pageList.map(item => {
            item.dataList = []
          })
          // this.pageList[index].dataList = []
          this.$forceUpdate()
        }

        if (this.pageList[index].dataList.length === 0) {
          this.loadTabData(index, refresh ? 'refresh' : '');
        }

        if (this.tabIndex === index) {
          return;
        }
      },
      loadTabData(index, refresh) {
        this.pageList[index].loadData(index, refresh);
      },
      // tabs通知swiper切换
      tabsChange(index) {
        this.tabIndex = index;
        this.current = index
      },
      swiperChange(e) {
        let tabTop = e.currentTarget.offsetTop; //tab距离顶部的距离
        let swiperTop = tabTop - uni.upx2px(100) - 44 - this.systemInfo.statusBarHeight;
        if (e.detail.source) {
          this.tabScrollTop[this.current] = this.scrollTop < swiperTop ? swiperTop : this.scrollTop; //给之前的tab赋值
        }
        this.tabIndex = e.detail.current;
        this.current = e.detail.current
        this.switchTab(this.current)
        this.setScrollLeft(this.current)
        if (this.scrollTop < swiperTop) return;
        if (this.tabScrollTop[this.current] < swiperTop) {
          this.tabScrollTop[this.current] = swiperTop //给当前的tab赋值
        }
        uni.pageScrollTo({
          scrollTop: this.tabScrollTop[this.current],
          duration: 0
        })
      },
      // topScroll() {
      //   // this.pageList[this.current].loadData(this.current, 'refresh');
      // },
      loadMore() {
        this.pageList[this.current].loadData(this.current, 'more');
      },
      // onPulling(e) {
      //   console.log("onpulling", e);
      // },
      // onRefresh() {
      //   if (this.freshing) return;
      //   this.freshing = true;
      //   this.pageList[this.current].loadData(this.current, 'refresh');
      //   setTimeout(() => {
      //     this.triggered = false;
      //     this.freshing = false;
      //   }, 500)
      // },
      // onRestore() {
      //   this.triggered = 'restore'; // 需要重置
      //   console.log("onRestore");
      // },
      // onAbort() {
      //   this.triggered = 'restore'; // 需要重置
      //   console.log("onAbort");
      // }
    }
  }
</script>

<style lang="scss" scoped>
  .container-news {

    .msg {
      display: flex;
      flex-direction: column;
      align-items: center;
      position: fixed;
      // top: 36rpx;
      top: 88rpx;
      right: 25rpx;
      z-index: 3;
      color: #fff;
      font-size: 24rpx;
      z-index: 7;

      .msgCenter {
        font-size: 40rpx;
      }

      .msgTxt {
        position: absolute;
        top: -25%;
        left: -30%;
        padding: 0 6rpx;
        font-size: 20rpx;
        background: #ff0000;
        border-radius: 13rpx;
      }
    }


    .swiper {
      /deep/ .uni-swiper-dot {
        width: 15rpx !important;
        height: 15rpx;
        border-radius: 50% !important;
        background-color: #ffffff !important;
        opacity: 0.5;
      }

      /deep/ .uni-swiper-dot-active {
        width: 20rpx !important;
        height: 20rpx;
        border-radius: 50% !important;
        background-color: #ffffff !important;
        opacity: 1;
      }
    }

    .nav {
      position: fixed;
      top: 0;
      width: 100%;
      height: 80rpx;
      background-color: #FA6138;
      z-index: 9;
    }

    .top {
      position: relative;
      width: 100%;
      height: 880rpx;

      .swiper,
      .swiper-item {
        width: 100%;
        height: 100%;

        image {
          width: 100%;
          height: 100% !important;
          vertical-align: middle;
        }
      }
    }

    .banner {
      width: 100%;
      height: 160rpx;

      image {
        width: 100%;
        height: 100%;
        vertical-align: middle;
      }
    }

    .stickMain {
      margin-top: calc(100rpx + 100rpx);
    }

    .tabs {
      width: 100%;
      height: 95rpx;
      padding: 0 30rpx;
      border-bottom: 1rpx solid #e6e6e6;
      font-size: 30rpx;
      font-family: PingFang SC, PingFang SC-Regular;
      font-weight: 400;
      color: #1a1a1a;
      background: #fff;

      .scorll-x {
        width: 100%;
        height: 100%;
        white-space: nowrap;
      }

      .tab {
        display: inline-block;
        height: 100%;
        line-height: 95rpx;
        margin-right: 44rpx;
      }

      .active {
        position: relative;
        font-family: PingFang SC, PingFang SC-Bold;
        font-weight: 700;
        color: #FA6138;

        &::after {
          position: absolute;
          bottom: 0;
          display: block;
          content: '';
          width: 100%;
          height: 4rpx;
          background: #FA6138;
          border-radius: 2rpx;
          z-index: 3;
        }
      }
    }

    .stickTabs {
      position: fixed;
      top: 80rpx;
      z-index: 9;
    }

    .list-swiper {
      width: 100%;
      height: calc(100vh - 100rpx);

      .swiper-item {
        width: 100%;
        height: 100%;
      }
    }
  }
</style>
