<style lang="less">
  .container,.video-swiper{
    width:100%;
    height:100%;
  }
  .video_item{
    height:100%;
    width:100%;
    position: absolute;
    z-index: 1;
  }
  .rightcont {
    font-size: 24rpx;
    position: absolute;
    z-index: 9;
    bottom: 415rpx;
    width:30%;
    right: 30rpx;
    color: #fff;
    .info {
      line-height: 40rpx;
    }
  }
  .progress {
    width: 180rpx;
    height: 20rpx;
    background-color: #fff;
    margin-top: 10rpx;
    color: #666;
    position: relative;
    .text {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: 2;
      background-color: transparent;
      text-align: center;
      font-size: 18rpx;
      line-height: 20rpx;
    }
    .orange {
      height:100%;
      transition:all 1s;
      background-color: #FF5D15;
    }
  }
  .images {
    width: 100%;
  }
</style>
<template>
  <view class="container">
    <swiper
      class="video-swiper"
      :duration= "800"
      circular="{{circular}}"
      vertical
      current="1"
      bindanimationfinish="animationfinish"
      bindchange="cancelPause"
    >
      <!-- curQueue 循环会导致video重新插入，objectFit 不可变更 -->
      <swiper-item wx:for="{{curQueue}}" wx:key="index">
        <view class="video-wrapper">
          <!-- <video
            id="video_{{index}}"
            class="video_item"
            loop
            show-center-play-btn="{{false}}"
            controls="{{false}}"
            src="{{item.url}}"
            data-id="{{item.id}}"
            object-fit="{{item.objectFit || 'contain'}}"
            data-index="{{index}}"
            binderror="onError"
            bindwaiting="onWaiting"
            bindloadedmetadata="onLoadedMetaData"
            bindtimeupdate="onTimeUpdate"
            @tap="videoTap"
          >
            <video-pause :pause="pause"></video-pause>
          </video> < !-->
          <view class="rightcont">
            <view class="info">奖品库存: 1/8</view>
            <view class="info">中奖概率: {{item.id}}/3000</view>
            <view class="progress">
              <view class="text">{{progress}}%</view>
              <view class="orange" style="{{progressStyle}}"></view>
            </view>
          </view>
          <!-- <video-loading v-if="item.time === 0"/> -->
          <image class="images" :src="item.url" mode="widthFix"></image>
        </view>
      </swiper-item>
    </swiper>
  </view>
</template>
<script>
  import wepy from '@wepy/core';
  wepy.component({
    props: {
      videoList: {
        type: Array,
        value: []
      },
      loading: {
        type: Boolean,
        default: false
      },
      duration: {
        type: Number,
        value: 800
      },
      total: {
        type: Number,
        value: 0
      }
    },
    data: {
      pause: false,
      nextQueue: [],
      prevQueue: [],
      curQueue: [],
      circular: false,
      _last: 1,
      _change: -1,
      _invalidUp: 0,
      _invalidDown: 0,
      _videoContexts: [],
      progress: 0,
      progressStyle: '',
      loading: false
    },
    watch: {
      videoList () {
        const newVal = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
        this.loading = false;
        if (newVal.length) this._videoListChanged(newVal);
      }
    },
    attached() {
      this.progress = 47;
      this.progressStyle = 'width:' + this.progress + '%';
      this._videoContexts = [
        wx.createVideoContext('video_0', this.$wx),
        wx.createVideoContext('video_1', this.$wx),
        wx.createVideoContext('video_2', this.$wx)
      ];
    },
    methods: {
      _videoListChanged (newVal) {
        newVal.forEach((item, index) => {
          item.time = 0;
          this.nextQueue.push(item);
        });
        if (!this.curQueue.length) {
          this.curQueue = this.nextQueue.splice(0, 3);
          this.playCurrent(1);
        }
      },
      animationfinish(e) {
        const current = e.$wx.detail.current;
        const diff = current - this._last;
        if (diff === 0) return;
        this._last = current;
        this.playCurrent(current);
        this.$emit('change', { activeId: this.curQueue[current].id });
        this.loading = true;
        this.circular = false;

        setTimeout(() => {
          const direction = diff === 1 || diff === -2 ? 'up' : 'down';
          if (direction === 'up') {
            if (this._invalidDown === 0) {
              // console.log(this.nextQueue, this.nextQueue.length, this.prevQueue, this.prevQueue.length);
              // if (this.nextQueue.length === 0) {this.nextQueue.push(this.prevQueue.shift())}
              const change = (this._change + 1) % 3;
              const add = this.nextQueue.shift();
              const remove = this.curQueue[change];
              if (add) {
                this.prevQueue.push(remove);
                this.curQueue[change] = add;
                this._change = change;
                if (this.nextQueue.length === 0) this.nextQueue.push(this.prevQueue.shift());
              } else {
                this._invalidUp += 1;
              }
            } else {
              this._invalidDown -= 1;
            }
          }
          if (direction === 'down') {
            if (this._invalidUp === 0) {
              // if (this.prevQueue.length === 0) {this.prevQueue.push(this.nextQueue.pop())}
              const _change2 = this._change;
              const _remove = this.curQueue[_change2];
              const _add = this.prevQueue.pop();
              if (_add) {
                this.curQueue[_change2] = _add;
                this.nextQueue.unshift(_remove);
                this._change = (_change2 - 1 + 3) % 3;
                if (this.prevQueue.length === 0) this.prevQueue.push(this.nextQueue.pop());
              } else {
                this._invalidDown += 1;
              }
            } else {
              this._invalidUp -= 1;
            }
          }
          this.circular = true;
          // if (this.nextQueue.length === 0 && current !== 0) {
          //   this.circular = false;
          // }
          // if (this.prevQueue.length === 0 && current !== 2) {
          //   console.log('circular2');
          //   this.circular = false;
          // }
        });
      },
      onWaiting (e) {
        this.trigger(e, 'wait');
      },
      onLoadedMetaData (e) {
        this.trigger(e, 'loadedmetadata');
      },
      onError(e) {
        this.trigger(e, 'error');
      },
      onTimeUpdate(e) {
        const currentTime = e.$wx.detail.currentTime;
        if (currentTime > 0 && currentTime < 10) {
          const id = e.target.dataset.id;
          this.curQueue.forEach((v, i) => {
            if (v.id === id && v.time === 0) {
              this.curQueue[i].time = currentTime;
            }
          });
          this.curQueue = [...this.curQueue];
        }
      },
      playCurrent(current) {
        this._videoContexts.forEach((ctx, index) => {
          if (index !== current) {
            ctx.pause();
          } else {
            ctx.play();
          }
        });
      },
      trigger(e, type) {
        var ext = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
        var detail = e.$wx.detail;
        var activeId = e.target.dataset.id;
        this.$emit(type, Object.assign(Object.assign(Object.assign({}, detail), { activeId: activeId }), ext));
      },
      videoTap(e) {
        const current = e.currentTarget.dataset.index;
        this._videoContexts.forEach((ctx, index) => {
          if (index === current) {
            this.pause ? ctx.play() : ctx.pause();
          }
        });
        this.pause = !this.pause;
      },
      cancelPause() {
        this.pause = false;
      }
    }
  });
</script>
<config>
{
    usingComponents: {
      'video-pause': '~@/components/custom/videoPause',
      'video-loading': '~@/components/custom/loading'
    }
}
</config>
