<style lang="less">
  .container,.video-swiper{
    width:100%;
    height:100%;
  }
  .video-item {
    height:100%;
    width:100%;
    position: absolute;
    z-index: 1;
  }

  .image-item{
    height:100%;
    width:100%;
    position: absolute;
    z-index: 1;
    display: flex;
    align-items: center;
  }
  .video-wrapper {
    width: 100%;
  }
  .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;
      text-align: center;
      line-height:20rpx;
      background-color: transparent;
      font-size: 18rpx;
    }
    .orange {
      width: 0;
      height:100%;
      transition:all .6s;
      background-color: #FF5D15;
    }
  }
  .images {
    width: 100%;
  }
</style>
<template>
  <view class="container">
    <swiper
      class="video-swiper"
      duration= "400"
      circular="{{true}}"
      vertical
      current="0"
      bindanimationfinish="bindanimationfinish"
    >
      <swiper-item class="{{item.photoUrl ? 'image-item' : 'video-item'}}" v-for="(item, idx) in curQueue" :key="item.id">
        <view class="video-wrapper">
           <video
            id="video_{{idx}}"
            class="video_item"
            loop
            show-center-play-btn="{{false}}"
            enable-progress-gesture="{{false}}"
            controls="{{false}}"
            src="{{item.videoUrl}}"
            data-id="{{item.id}}"
            object-fit="{{item.objectFit || 'contain'}}"
            data-index="{{idx}}"
            binderror="onError"
            bindtimeupdate="onTimeUpdate"
            @tap="videoTap"
            v-if="!item.photoUrl"
          >
            <video-loading v-if="item.time === 0" :snapshot="item.snapshot"/>
            <video-pause :pause="pause"></video-pause>
          </video>
          <image v-if="item.photoUrl" class="images" :src="item.photoUrl" mode="widthFix"></image>
          <view class="rightcont">
            <view class="info">奖品库存: {{item.stock}}/{{item.totalStock}}</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>
        </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: []
      },
      userAccount: {
        type: Number,
        value: 0
      }
    },
    data: {
      pause: false,
      curQueue: [],
      _videoContexts: []
    },
    watch: {
      videoList () {
        const newVal = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
        this._videoListChanged(newVal);
        this.compute(this.userAccount);
      },
      userAccount(newVal) {
        this.compute(newVal);
      }
    },
    created() {
      this.compute(this.userAccount);
    },
    methods: {
      compute (newVal) {
        if (!this.curQueue.length) return;
        this.curQueue.forEach(v => {
          v.probability = getProbability(+newVal, +v.coinQuantity);
        });
        this.curQueue = [...this.curQueue];
      },
      async getProgress(id) {
        let detail = await getAwardsDetail({ prizeId: id });
        detail = detail || {};
        const progress = Math.round((detail.join / detail.quantity) * 100) + '%';

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

        this.curQueue = [...this.curQueue];
      },
      _videoListChanged (newVal) {
        this.curQueue = newVal.map((item, index) => {
          this._videoContexts.push(item.videoUrl ? wx.createVideoContext(`video_${index}`, this.$wx) : null);
          item.time = 0;
          return item;
        });
        this.playCurrent(0);
      },
      async bindanimationfinish(e) {
        const current = e.$wx.detail.current;
        this.pause = false;
        this.playCurrent(current);
      },
      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) {
        if (!this.curQueue || this.curQueue.length <= 1) return;

        this._videoContexts.forEach((ctx, index) => {
          if (index !== current) {
            ctx && ctx.pause();
          } else {
            ctx && ctx.play();
          }
        });

        this.getProgress(this.curQueue[current].id);
        const { id, photoUrl, name, probability } = this.curQueue[current];
        this.$emit('getAwardsInfo', {
          id,
          photoUrl,
          quantity: this.userAccount,
          name,
          chance: probability
        });
      },
      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;
      }
    }
  });
</script>
<config>
{
    usingComponents: {
      'video-pause': '~@/components/custom/videoPause',
      'video-loading': '~@/components/custom/loading',
      "van-image": "~@/components/vant/image/index"
    }
}
</config>
