<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 {
      width: 0;
      height:100%;
      transition:all .6s;
      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.probability}}</view>
            <view class="progress">
              <view class="text">{{item.progress}}</view>
              <view class="orange" style="{{item.progressStyle}}"></view>
            </view>
          </view>
          <!-- <video-loading v-if="item.time === 0"/> -->
          <image class="images" :src="item.photoUrl" mode="widthFix"></image>
        </view>
      </swiper-item>
    </swiper>
  </view>
</template>
<script>
  import wepy from '@wepy/core';
  import { getProbability } from '../../common/raffleProbability';
  import { getAwardsDetail } from '../../common/api.js';
  wepy.component({
    props: {
      videoList: {
        type: Array,
        value: []
      },
      loading: {
        type: Boolean,
        default: false
      },
      duration: {
        type: Number,
        value: 800
      },
      total: {
        type: Number,
        value: 0
      },
      userAccount: {
        type: Number,
        value: 0
      }
    },
    data: {
      pause: false,
      nextQueue: [],
      prevQueue: [],
      curQueue: [],
      circular: false,
      _last: 1,
      _change: -1,
      _invalidUp: 0,
      _invalidDown: 0,
      _videoContexts: [],
      loading: false
    },
    watch: {
      videoList () {
        const newVal = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
        this.loading = false;
        this.init();
        if (newVal.length) this._videoListChanged(newVal);
        this.compute(this.userAccount);
      },
      userAccount(newVal) {
        this.compute(newVal);
      }
    },
    attached() {
      this._videoContexts = [
        wx.createVideoContext('video_0', this.$wx),
        wx.createVideoContext('video_1', this.$wx),
        wx.createVideoContext('video_2', this.$wx)
      ];
    },
    created() {
      this.compute(this.userAccount);
    },
    methods: {
      compute (newVal) {
        this.nextQueue.forEach(v => {
          v.probability = getProbability(+newVal, +v.coinQuantity);
        });

        this.curQueue.forEach(v => {
          v.probability = getProbability(+newVal, +v.coinQuantity);
        });

        this.prevQueue.forEach(v => {
          v.probability = getProbability(+newVal, +v.coinQuantity);
        });

        this.curQueue = [...this.curQueue];
        this.nextQueue = [...this.nextQueue];
        this.prevQueue = [...this.prevQueue];
      },
      async getProgress(id) {
        const detail = await getAwardsDetail({ prizeId: id });
        const progress = Math.round((detail.join / detail.quantity) * 100) + '%';
        this.nextQueue.forEach(v => {
          if (v.id === id) {
            if (v.id === id) {
              v.progress = progress;
              v.batchId = detail.id;
              v.progressStyle = 'width:' + progress;
            }
          }
        });

        this.curQueue.forEach(v => {
          if (v.id === id) {
            v.progress = progress;
            v.batchId = detail.id;
            v.progressStyle = 'width:' + progress;
          }
        });

        this.prevQueue.forEach(v => {
          if (v.id === id) {
            v.progress = progress;
            v.batchId = detail.id;
            v.progressStyle = 'width:' + progress;
          }
        });

        this.curQueue = [...this.curQueue];
        this.nextQueue = [...this.nextQueue];
        this.prevQueue = [...this.prevQueue];
      },
      init() {
        this.pause = false;
        this.nextQueue = [];
        this.prevQueue = [];
        this.curQueue = [];
        this.circular = false;
        this._last = 1;
        this._change = -1;
        this._invalidUp = 0;
        this._invalidDown = 0;
        this._videoContexts = [];
        this.loading = false;
      },
      _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) {
              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) {
              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;
        });
      },
      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];
        }
      },
      async playCurrent(current) {
        await this.getProgress(this.curQueue[current].id);
        const { batchId, photoUrl, name, probability, progress } = this.curQueue[current];
        this.$emit('getAwardsInfo', {
          batchId,
          photoUrl,
          quantity: this.userAccount,
          name,
          chance: probability,
          progress: progress
        });
        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>
