<style lang="less">
  page{
    height: 100%;
    background-color: #000;
  }
  .video-wrapper{
    width: 100%;
    height: 100%;
  }
  #myvideo{
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 0;
    background-color:rgba(0, 0, 0, 0.7);
  }
  .userInfo{
    position: fixed;
    z-index: 10;
    top:100rpx;
    left: 30rpx;
  }
  .userimage{
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
  }
  .content{
    position: absolute;
    z-index: 9;
    bottom: 400rpx;
    width: 100%;
    color: white;
    clear: both;
  }
  .leftcont {
    width: 44%;
    float: left;
    font-size: 24rpx;
    margin-left: 30rpx;
  }
  .list-wrapper {
    height: 120rpx;
  }
  .leftcont .img {
    width: 40rpx;
    height: 40rpx;
    border-radius: 50%;
    vertical-align: middle;
  }
  .leftcont .text {
    max-width: 200rpx;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-left: 10rpx;
    vertical-align: middle;
    border-radius: 20rpx;
    display: inline-block;
    font-size: 20rpx;
    box-sizing: border-box;
    padding:6rpx 15rpx;
    background-color:rgba(238, 238, 238, 0.2);
  }

  .footer {
    position: absolute;
    z-index: 9;
    bottom: 20rpx;
    width: 100%;
  }
  .footswiper {
    height: 360rpx;
  }
  .list-item{
    width:220rpx;
    /*height: 330rpx;*/
    background-color:#fff;
    border-radius: 10rpx;
    transform: scale(0.7,0.7) translateY(65rpx);
    transition: all 0.5s;
    padding:10rpx 10rpx 5rpx 10rpx;
    margin:0 auto;
    margin-top: 2rpx;
    position: relative;
  }
  .list-item image {
    width: 210rpx;
    display: block;
    height: 210rpx;
    margin:0 auto;
    border-radius: 10rpx;
  }
  .list-item .text {
    font-size: 20rpx;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2; //行数
    -webkit-box-orient: vertical;
    overflow: hidden;
    line-height:24rpx;
    margin-top:10rpx;
  }
  .list-item .price{
    color:#FF5D15;
    font-size:22rpx;
    margin-top:2rpx;
  }
  .list-item .buy{
    font-size: 16rpx;
    color:#AAA;
  }
  .list-item.subright {
    transform: scale(0.85,0.85) translateY(26rpx) translateX(25rpx);
  }
  .list-item.subleft {
    transform: scale(0.85,0.85) translateY(26rpx) translateX(-25rpx);
  }
  .list-item.select{
    transform: scale(1,1);
    bottom: 2rpx;
  }
  .list-item.delete {
    opacity:0;
    transform:translateY(-220rpx)
  }
  .authmodal{
    width:100%;
    height:100%;
    background-color: rgba(0,0,0,0.7);
    position: fixed;
    z-index:20;
    .wrap {
      width: 90%;
      margin:0 auto;
      position: relative;
      top:200px;
      padding: 50rpx 0;
      background-color: #fff;
      border-radius: 20rpx;
      .text {
        color:#333;
        text-align: center;
        padding-top:30rpx;
        padding-bottom: 60rpx;
      }
      button {
        width:80%;
      }
    }
  }
</style>
<wxs module="tools">
  // 无限循环当current为最后一个的时候，select就应该是0 例如长度为10，当current为9时，select就应该是0
  // if(current+1==index || (current==length-1 && index==0) ) allclass = "select";
  // 无限循环当current为最后一个/两个的时候的时候，例如长度为10，当current为8/9时，select就应该是1/0
  //if(current+2 == index|| (current>=length-2 && index==current-length+2))
  //allclass='subright';

  function computClass (current,index,length) {
    var allclass = "";
    if(current-1 == index||(current == 0&&index==length-1))
      allclass='subleft';
    if(current==index)
      allclass='select';
    if(current+1==index || (current==length-1 && index==0) )
      allclass = "subright";
    return allclass;
  };
  module.exports = {
    computClass:computClass
  }
</wxs>
<template>
  <view class="video-wrapper">
    <view id="myvideo">
      <van-notify id="van-notify" />
      <video-list :videoList.sync="videoList" :userAccount="mainInfo && mainInfo.account && mainInfo.account.quantity || 0" :total="total" bindchange="changeVideo" @getAwardsInfo="getAwardsInfo">
      </video-list>
    </view>
    <view class="userInfo" style="{{userImgStyle}}" @tap="showMenu(!showMenus)">
      <image src="{{userInfo.avatarUrl || '/static/images/user@2x.png'}}" mode="cover" class="userimage"></image>
    </view>
    <view>
      <video-gold type="gold" :des="mainInfo && mainInfo.account && mainInfo.account.quantity || 0" :gold="sign" :isReceive="isReceive"></video-gold>
      <video-sign type="sign" des="签到" :sign="sign" @sign-in="signIn"></video-sign>
      <video-lottery type="lottery" des="抽奖" @tap="getAwards"></video-lottery>
      <video-share type="share" des="分享"></video-share>
    </view>
    <view class="content">
      <view class="leftcont">
        <swiper 
          class="list-wrapper"
          vertical="{{true}}" 
          circular="{{false}}" 
          display-multiple-items="{{activityDisplayItems}}" 
          bindchange="onActivityChange" 
          autoplay="{{autoplayActivity}}" 
          interval="1500">
          <swiper-item  wx:for="{{activityList}}" wx:key="index" catch:touchmove>
            <view class="imgwrap">
              <image class="img" src="{{item.avatarUrl}}"></image>
              <view class="text">{{item.content}}</view>
            </view>
          </swiper-item>
        </swiper>
      </view>
    </view>
    <!-- <view class="footer">
      <swiper
        class="footswiper"
        display-multiple-items="{{swiperItem}}"
        current="{{current}}"
        bindchange="moveSwiper"
        bindanimationfinish="swipermoveDone"
        circular="{{circular}}"
        previous-margin="140rpx"
        next-margin="120rpx"
        catch:touchmove
      >
        bindtouchstart="touchStart"
        bindtouchend="touchEnd"
        <swiper-item wx:for="{{list}}" wx:key="index">
          <view
            data-itemid="{{index}}"
            bindtap="toViewPage"
            data-item="{{item}}"
            class="list-item {{item.select?'delete':''}} {{tools.computClass(currentIndex,index,list.length)}}"
          >
            <image src="{{item.imgsrc}}"></image>
            <view class="text">{{item.text}}</view>
            <p class="price">{{item.price}}</p>
            <p class="buy">{{item.people}}人购买</p>
          </view>
        </swiper-item>
      </swiper>
    </view> -->
    <view class="authmodal" v-show="authmodal">
      <view class="wrap">
        <view class="text">来到luckii，再平凡的人，<br>也有幸运的权利！</view>
        <button open-type="getUserInfo" bindgetuserinfo="getUserInfo">授权并进入</button>
      </view>
    </view>
    <network v-if="isConnected === false"></network>
    <open-animation v-if="showAwardsModal" :joinRecord="mainInfo && mainInfo.joinRecord"></open-animation>
    <shared-popup v-if="showShareModal" :inviteinfo="mainInfo && mainInfo.inviteRecord" @getSharedGold="getSharedGold"></shared-popup>
    <popup @showMenu="showMenu" :showMenus="showMenus"></popup>
  </view>
</template>

<script>
  let touchDotX = 0, touchDotY = 0;
  import store from '../store';
  import { mapState, mapActions } from '@wepy/x';
  import wepy from '@wepy/core';
  import Notify from '../components/vant/notify/notify';
  import { login, register, getUserInfo, addGold, getPrizeList, signIn, getActivityFeed } from '../common/api.js';
  wepy.page({
    store,
    hooks: {

    },

    data: {
      list: [], // 商品list

      // 活动信息
      activityList: [],
      activityDisplayItems: 2,
  
      current: 5, // 商品列表初次展示第几个
//      userInfo: {},
      swiperItem: 2,
      videoList: [],
      length: 4,
      circular: false, // 商品是否无限循环
      topPage: 0,
      lastPage: 0,
      currentIndex: 5,  // 商品当前滑动到第几个
      authmodal: false,
      sign: true,
      showAnimation: false,
      userImgStyle: '',
      goldStyle: '',
      goldNum: 50000,
      awards: false,
      showMenus: false,
      loading: false,
      inviter: '',
      mainInfo: null,
      showShareModal: false,
      showAwardsModal: false,
      awardsInfo: {},
      isReceive: false,
      autoplayActivity: false
    },

    computed: {
      ...mapState([ 'isConnected', 'userInfo' ])
    },

    methods: {
      ...mapActions([ 'setIsConnected', 'setUserInfo' ]),
      moveSwiper(e) {
        if (e.$wx.detail.source == 'touch') {
          let current = e.$wx.detail.current;
          this.currentIndex = current;
        }
      },
      swipermoveDone(e) {
        if (e.$wx.detail.source == 'touch') {
          let current = e.$wx.detail.current;
          let totalPage = 3;
          let nextlist = [
            {value: 11, text: '白色条纹马克杯，马克吐温同款11', imgsrc: '/static/images/test1.jpg', price: '￥9.89', people: 2200, sku: '100004549235'},
            {value: 12, text: '白色条纹马克杯，马克吐温同款12', imgsrc: '/static/images/test2.png', price: '￥19.20', people: '2200', sku: '100004549235'},
            {value: 13, text: '白色条纹马克杯，马克吐温同款13', imgsrc: '/static/images/peo1.jpg', price: '￥39.08', people: 2200, sku: '100004549235'},
            {value: 14, text: '白色条纹马克杯，马克吐温同款14', imgsrc: '/static/images/peo2.jpg', price: '￥599.20', people: 2200, sku: '100004549235'},
            {value: 15, text: '白色条纹马克杯，马克吐温同款15', imgsrc: '/static/images/peo3.jpg', price: '￥2399.01', people: 2200, sku: '100004549235'}
          ];
          let that = this;
          function debounce(func, wait) {
            let timeout;
            return function () {
              if (timeout) clearTimeout(timeout);

              let callNow = !timeout;
              timeout = setTimeout(func, wait);

              if (callNow) func();
            };
          }
          /* if(current <= 2) {
            debounce(setTimeout(function(){
              that.topPage +=1;
              if(that.lastPage+that.topPage >= totalPage) {
                that.circular = true;
                return;
              }
              that.list = [...newlist, ...that.list];
//              that.current = current+1;
//              that.currentIndex = current+1;
            },1000),500);
          } */
          if (current >= this.list.length - 3) {
            debounce(setTimeout(function() {
              that.lastPage += 1;
              if (that.lastPage + that.topPage >= totalPage) {
                that.circular = true;
                return;
              }
              that.list = [ ...that.list, ...nextlist];
            }, 1000), 500);
          }
        }
      },
      toViewPage(e) {
        let item = e.$wx.currentTarget.dataset.item;
        // 解决长按触发tap事件的bug
        wx.navigateToMiniProgram({
          appId: 'wx91d27dbf599dff74',
          path: 'pages/item/detail/detail?sku=' + item.sku, // 跳转小程序的路径
          // 有效值 develop（开发版），trial（体验版），release（正式版）
          envVersion: 'release',
          success(res) {
//            console.log('跳转成功');
          }
        });
       /* wx.navigateTo({
          url: '/pages/auth'
        }); */
      },
      touchStart (event) {
        touchDotX = event.touches[0].pageX; // 获取触摸时的原点
        touchDotY = event.touches[0].pageY;
        // console.log("起始点的坐标X:" + touchDotX);
        // console.log("起始点的坐标Y:" + touchDotY);
      },
      touchMove(event) {
        let touchX = event.touches[0].pageX;
        let touchY = event.touches[0].pageY;
        // 如果元素拖动到购物车范围
        let {left, top, bottom, right} = this.shopcarPosition;
        if (touchX > left - 10 && touchX < right + 10) {
          if (touchY > top - 10 && touchY < bottom + 10) {
            this.bigshop = true;
          }
        }
      },
      // 移动结束处理动画
      touchEnd(event) {
        // 手指离开屏幕时记录的坐标
        let touchMoveX = event.changedTouches[0].pageX;
        let touchMoveY = event.changedTouches[0].pageY;
        let current = event.currentTarget.dataset;
        // 起始点的坐标(x0,y0)和手指离开时的坐标(x1,y1)之差
        let tmX = touchMoveX - touchDotX;
        let tmY = touchMoveY - touchDotY;
        // 两点横纵坐标差的绝对值
        let absX = Math.abs(tmX);
        let absY = Math.abs(tmY);
        // 起始点的坐标(x0,y0)和手指离开时的坐标(x1,y1)之间的距离
        let delta = Math.sqrt(absX * absX + absY * absY);
        // console.log('起始点和离开点距离:' + delta + 'px');
        // 如果delta超过60px（可以视情况自己微调）,判定为手势触发
        if (delta >= 40) {
          // 如果 |x0-x1|<|y0-y1|,即absX<abxY,判定为上下滑动
          if (absX < absY) {
            // 如更tmX<0，即(离开点的X)-(起始点X)小于0 ，判定为下滑
            if (tmY < 0) {
              this.deleteAnimation(current);
              // console.log("上滑=====");
              // 如更tmX>0，即(离开点的X)-(起始点X)大于0 ，判定为上滑
            } else {
              // console.log("下滑=====");
            }
          }
        } else {
          // console.log("手势未触发=====");
        }
      },
      async getUserInfo (e) {
        if (e.$wx.detail.userInfo) {
          this.setUserInfo(e.$wx.detail.userInfo);
          this.authmodal = false;
          this.registUser(e.$wx.detail.userInfo);
        }
      },
      changeVideo(e) {
        this.setIsConnected();
        // if (this.length - e.activeId === 1) {
        //   this.videoList = [{id: e.activeId + 2, url: 'https://ip1707952229.mobgslb.tbcache.com/youku/6974c3708c0337150e1743b1c/03000801005EA2A6C8FB4C2003E8807282A547-8207-4F52-9663-969096765248.mp4?sid=158960247500010009412_00_Bac09720260d484f23ac2ccebe5206930&sign=b76f4099e108fc306d3db993d1bec0a8&ctype=50&ali_redirect_domain=vali.cp31.ott.cibntv.net&ali_redirect_ex_ftag=5898cd25832bbff232de6d9fa668e8ddf8bacc5fef3f2e7b&ali_redirect_ex_tmining_ts=1589602477&ali_redirect_ex_tmining_expire=3600&ali_redirect_ex_hot=111'}];
        //   this.length += 1;
        //   console.log('add video');
        // }
      },
      deleteAnimation (current) {
        if (current && current.itemid != undefined) {
          let list = this.list;
          list = list.map((item, index) => {
            item.select = '';
            if (index == current.itemid) {
              item.select = true;
            }
            return item;
          });
          this.list = list;
          let that = this;
          // 如果剩下4个就不让他循环了，这时候就一屏显示出来了
          if (list.length <= 4) {
            this.circular = false;
          }
          if (current.itemid >= list.length - 1) {
            this.current = this.currentIndex - 1;
          }
          setTimeout(function() {
            let newlist = that.list.filter((item, index) => index != current.itemid);
            // 正常情况下，current.itemid都会比current大一个，因为current有个隐藏元素，当相等或小于的时候就有问题，要重新设置current，最小不能超过0
            if (current.itemid <= that.current) {
              that.current = Math.max(that.current - 1, 0);
            }
            that.list = newlist;
          }, 500);
        }
      },
      signIn: async function() {
        let that = this;
        const tmplIds = [
          'xbA7XopO2j0V0Ne0F61UzSxoyfKrf92GQk6Z4pQvnd4',
          '_yZWJYT-3lGCQG6g7Wa7F-0zxvGaPe4zwAI9D4zW4EY',
          '7YzXgiVNGXiRvXNmR6WUtH_WplUyo97eAy45dsyviKQ'
        ];

        wx.requestSubscribeMessage({
          tmplIds: [
            'xbA7XopO2j0V0Ne0F61UzSxoyfKrf92GQk6Z4pQvnd4',
            '_yZWJYT-3lGCQG6g7Wa7F-0zxvGaPe4zwAI9D4zW4EY',
            '7YzXgiVNGXiRvXNmR6WUtH_WplUyo97eAy45dsyviKQ'
          ],
          success (res) {
            if (res.errMsg === 'requestSubscribeMessage:ok') {
              const rs = tmplIds.some(v => res[v] === 'accept');
              if (rs) {
                that.sign = true;

                setTimeout(async () => {
                  const innerAudioContext = wx.createInnerAudioContext();
                  innerAudioContext.autoplay = true;
                  innerAudioContext.src = '/static/audio/supermarie.mp3';
                  innerAudioContext.onPlay(() => {
                  });
                  innerAudioContext.onError((res) => {
                    console.log(res.errMsg);
                    console.log(res.errCode);
                  });
                  const { coins } = await signIn();
                  if (coins === 0) return;
                  that.mainInfo.account.quantity = coins;
                }, 1500);
              } else {
                Notify({ message: '签到必须同意推送授权!', background: '#FF5D15', safeAreaInsetTop: true });
              }
            }
          },
          fail (res) {
            console.log('requestSubscribeMessage fail', res);
            let info = '订阅消息失败,请稍后重试';
            switch (res.errCode) {
              case '20004':
                info = '您关闭了主开关，无法进行订阅';
                break;
            }
            Notify({ message: info, background: '#FF5D15', safeAreaInsetTop: true });
          }
        });
      },
      onShareAppMessage: function(res) {
        if (res.from === 'button') {
          console.log('onShareAppMessage2', res.target);
        }
        const openid = wx.getStorageSync('openId');
        return {
          title: `${this.$wepy.userInfo.nickName || '您的好朋友'}邀请您来抽奖啦～`,
          path: `/pages/index?openid=${openid}`,
          imageUrl: this.$wepy.awardsInfo.photoUrl,
          success: function(res) {
            let shareId = res.shareTickets[0];
            console.log('shareId', shareId);
                // 转发成功
          },
          fail: function(res) {
                // 转发失败
            console.log(res);
          }
        };
      },
      getAwards: function() {
        const { batchId, photoUrl, quantity, name, chance, progress } = this.awardsInfo;
        if (!batchId || !this.mainInfo || !this.mainInfo.account) {
          Notify({ message: '服务器异常,请稍后重试', background: '#FF5D15', safeAreaInsetTop: true});
          return;
        }
        if (this.mainInfo && this.mainInfo.account && this.mainInfo.account.quantity === 0) {
          Notify({ message: '您的克币数为0, 无法参与抽奖', background: '#FF5D15', safeAreaInsetTop: true});
          return;
        }
        wx.navigateTo({
          url: `/pages/raffle?batchId=${batchId}&progress=${progress}&chance=${chance}&photoUrl=${photoUrl}&quantity=${quantity}&name=${name}`
        });
      },
      getAwardsInfo: function(v) {
        this.awardsInfo = v;
      },
      showMenu: function(v) {
        this.showMenus = v;
      },
      getSharedGold: async function(v) {
        this.showShareModal = false;
        await addGold(v);
        this.mainInfo.account.quantity += v.quantity;
        this.isReceive = true;
        setTimeout(() => {
          if (this.mainInfo.joinRecord && this.mainInfo.joinRecord.id) {
            this.showAwardsModal = true;
          }
        }, 1000);
      },
      getMainInfo: async function() {
        this.mainInfo = await getUserInfo(wx.getStorageSync('openId'));
        this.sign = this.mainInfo.signin;
        wx.setStorageSync('hasPhone', this.mainInfo.phone);
        if (this.mainInfo.inviteRecord && this.mainInfo.inviteRecord.length) {
          this.showShareModal = true;
        } else if (this.mainInfo.joinRecord && this.mainInfo.joinRecord.id) {
          this.showAwardsModal = true;
        }
      },
      async registUser(userInfo) {
        if (wx.getStorageSync('isRegister') === false) {
          const params = {
            ...userInfo,
            inviter: this.inviter
          };
          await register(params);
          wx.setStorageSync('isRegister', true);
        }
      },
      async showActivity() {
        // 1期方案先一次取50
        const list = await getActivityFeed({ count: 50 });
        this.activityList = list;
        this.autoplayActivity = true;
      },
      onActivityChange(e) {
        const lastIndex = this.activityList.length - this.activityDisplayItems;
        if (e.$wx.detail.current === lastIndex) {
          this.autoplayActivity = false;
        }
      }
    },
    async onLoad (options) {
      if (options.openid) {
        this.inviter = options.openid;
      }
      let statusHeight = this.$app.$options.globalData.statusBarHeight || '';
      statusHeight && (this.userImgStyle = 'top:' + statusHeight + 'px');
    },
    async onShow() {
      this.videoList = [];

      if (!wx.getStorageSync('openId')) {
        const { code } = await wepy.wx.login();
        const userInfo = await login(code);
        wx.setStorageSync('openId', userInfo.openid);
        wx.setStorageSync('isRegister', userInfo.register);
      }
      if (store.state.userInfo) {
        this.userInfo = store.state.userInfo;
        this.registUser(this.userInfo);
      } else {
        const setting = await wepy.wx.getSetting();
        if (setting.authSetting['scope.userInfo']) {
          const { userInfo } = await wepy.wx.getUserInfo();
          this.setUserInfo(userInfo);
          this.registUser(userInfo);
        } else {
          this.authmodal = true;
        }
      }
      await this.getMainInfo();
      this.videoList = await getPrizeList();
      this.showActivity();
    }
  
  });
</script>
<config>
{
    navigationBarTitleText: '主页',
    usingComponents: {
      'van-button': '../components/vant/button/index',
      'video-list': '~@/components/custom/videolist',
      'van-icon': '../components/vant/icon/index',
      'video-sign': '~@/components/custom/sign',
      'video-gold': '~@/components/custom/sign',
      'video-share': '~@/components/custom/sign',
      'video-lottery': '~@/components/custom/sign',
      'network': '~@/components/custom/network',
      'open-animation': '~@/components/custom/openAnimation',
      'popup': '~@/components/custom/popup',
      'van-notify': '~@/components/vant/notify/index',
      'shared-popup': '~@/components/custom/sharedPopup',
      'video-loading': '~@/components/custom/loading'
    },
    navigationStyle: "custom",
  }
</config>
