<template>
  <div class="reward-gift" @click="showPicker = false">
     <div class="swiper-container" ref="gift-swiper">
       <div class="swiper-wrapper">
         <div class="swiper-slide" v-for="(page, pagesIndex) in list" :key="pagesIndex">
           <div class="gift-list" >
              <div class="gift-item" v-for="(item, index) in list[pagesIndex]" :key="index">
                <div class="box" :class="{ 'z-active': index === changeIndex && pagesIndex === pageIndex && !remainingTime(item), 'z-active-progress': index === changeIndex && pagesIndex === pageIndex && remainingTime(item)}" @click.stop="_changeGift(pagesIndex, index)">
                  <div class="img">
                    <img :src="giftImg(item)" />
                  </div>
                  <div class="name">{{ item.name }}</div>
                  <div class="price">{{ item.price == 0 ? `免费` : `${item.price}元` }}</div>
                  <div class="bg"></div>
                  <div class="progress">
                    <div class="container right">
                      <div class="halfCir" :style="{animationDuration: (remainingTime(item) / 1000 || 1) + 's'}"></div>
                    </div>
                    <div class="container left">
                      <div class="halfCir" :style="{animationDuration: (remainingTime(item) / 1000 || 1) + 's'}"></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
         </div>
       </div>
     </div>
    <div class="swiper-scrollbar"></div>
    <div class="operation" @click="showPicker = false">
      <div class="left">
        <div class="icon"></div>
        <div class="price">{{ giftInfo.id ? priceSum : '0.00' }}元</div>
      </div>
      <div class="right">
        <div class="num" v-show="giftInfo.price && giftInfo.price != 0">{{giftNum}}</div>
        <div class="icon" @click.stop="changePicker" v-show="giftInfo.price && giftInfo.price != 0"></div>
        <div class="send" :class="giftInfo.id&&sendable ? 'send-active' : ''" @click.stop="giftInfo.id&&sendable&&_giftReward()">
          发送
          <transition name="fade">
            <div class="picker" @click.stop v-if="showPicker">
              <scroll-picker :options="options" v-model="giftNum" @click.stop></scroll-picker>
            </div>
          </transition>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getRewardGiftList, rewardGift } from '@/plugins/API/apiReward';
import { mapGetters } from 'vuex';
import "vue-scroll-picker/dist/style.css"
export default {
  name: 'suspension-reward-gift',
  props: {
     show: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      pageIndex: null,
      changeIndex: null,
      giftNum: 1,
      list: [],
      showPicker: false,
      swiper: null,
      sendable: false
    };
  },
  computed: {
    ...mapGetters({
      channelInfo: 'channelInfo',
      userInfo: 'userInfo'
    }),
    remainingTime() {
       return (item) => {
         if (!item.time && !item.sendTime) return 0
         if (item.time && !item.sendTime) return 0
         const remain = item.time * 1000 - (new Date().getTime() - item.sendTime * 1000)
         return remain > 0 ? remain : 0
       }
    },
    options() {
      return this.showPicker ? [...Array(99)].map((k,i)=>i + 1) : []
    },
    giftInfo() {
      const list = this.list || [];
      if (this.changeIndex === null || this.pageIndex === null) return []
      return list[this.pageIndex][this.changeIndex] || {}
    },
    priceSum() {
      if (this.giftInfo.id) {
        const price = Number(this.giftInfo.price) || 0;
        return (price * this.giftNum).toFixed(2);
      } else {
        return 0;
      }
    }
  },
  mounted() {
    // this.$Bus.$on('bus-getRewardGiftList', this._getRewardGiftList);
    this._getRewardGiftList();
  },
  methods: {
    chunk(array, size) {
        const result = [];
        for (let x = 0; x < Math.ceil(array.length / size); x++) {
            const start = x * size;
            const end = start + size;
            result.push(array.slice(start, end));
        }
        return result;
    },
    changePicker() {
      if (this.giftInfo.id) {
        this.showPicker = !this.showPicker
      }
    },
    giftImg(gift) {
      return gift.img || `${process.env.DEF_OSS}/static/reward/gift-${gift.imgType}.png`;
    },
    // 获取礼物打赏
    async _getRewardGiftList() {
      const res = await getRewardGiftList({
        id: this.channelInfo.id,
        uin: this.channelInfo.uin
      });
      if (res.code === 200 && res.errorCode === 0) {
        const a = res.data
        this.list = this.chunk(a, 8);
      }
    },
    _initSwiper() {
     const self = this;
      const option = {
        touchRatio: 0.5,
        on: {
          slideChange() {
            self.tabIndex = this.activeIndex;
          }
        },
        scrollbar: {
          el: '.swiper-scrollbar',
        },
      };
      this.swiper = new this.$swiper(this.$refs['gift-swiper'], option);
    },
    _changeGift(page, index) {
      this.sendable = false;
        if (this.pageIndex === page && this.changeIndex === index) {
          this.changeIndex = null;
          this.pageIndex = null;
        } else {
          clearTimeout(this.timer)
          const change = this.list[page][index] // change.sendTime * 
          const remainTime = change.time * 1000 - new Date().getTime() + change.sendTime * 1000
          this.changeIndex = index;
          this.pageIndex = page;
          if (remainTime > 0){
            setTimeout(() => {
              this.sendable = true;
              change.sendTime = null
            }, remainTime)
            return
          }
          this.sendable = true;
        }
    },
    _setCount(step) {
      const num = Number(this.giftNum) + step;
      this.giftNum = num;
    },
    async _giftReward() {
      const res = await rewardGift({
        uin: this.channelInfo.uin,
        channelId: this.channelInfo.id,
        giftId: this.giftInfo.id,
        num: this.giftNum,
        backUrl: window.location.href,
        payType: 1
      });
      if (res.code === 200 && res.errorCode === 0) {
        this.pageIndex = null
        this.changeIndex = null
        if (res.data === 'success') {
          this.$emit('close')
          this._getRewardGiftList();
          return
        }
        const { tradeType, prepayInfo } = res.data;
        const { uin } = this.channelInfo;
        const DEF_SITE = process.client
          ? process.env.DEF_SITE + (window.location.protocol.split(':')[0] === 'https' ? process.env.HTTPS_PORT : process.env.HTTP_PORT)
          : `http:${process.env.DEF_SITE + process.env.HTTP_PORT}`;
        if (res.data.url) {
          window.location.href = res.data.url;
        } else if (tradeType === 'MWEB') {
          const wxh5pay = `https:${process.env.DEF_SITE + process.env.HTTPS_PORT}/pay/wxh5pay?uin=${uin}`;
          const backUrl = encodeURIComponent(window.location.href);
          const transferUrl = encodeURIComponent(`${wxh5pay}&url=${backUrl}`);
          const payUrl = encodeURIComponent(`${prepayInfo.mweb_url}&redirect_url=${transferUrl}`);
          const url = `${wxh5pay}&url=${payUrl}`;
          window.location.href = url;
        } else if (tradeType === 'JSAPI') {
          const data = encodeURIComponent(JSON.stringify(res.data));
          const url = `${DEF_SITE}/pay/wxpay?uin=${uin}&payconfig=${data}`;
          window.location.href = url;
        } else {
          this.$layer.msg('网络错误，请稍后重试！');
        }
      }
    }
  },
  watch: {
    giftNum(nVal) {
      const num = nVal > 999 ? 999 : nVal < 1 ? 1 : nVal;
      this.giftNum = parseInt(num, 10);
    },
    show() {
      this.$nextTick(() => {
        this._initSwiper();
      });
    },
    changeIndex() {
      this.giftNum = 1
      this.showPicker = false
    },
    pageIndex() {
      this.giftNum = 1
      this.showPicker = false
    }
  }
};
</script>
<style lang="less" scoped>

.reward-gift {
  .swiper-scrollbar {
    z-index: 50;
    height: 3px;
    width: 10%;
    margin-left: 45%;
    background: rgba(255, 255, 255, 0.25);
    ::v-deep  .swiper-scrollbar-drag{
      background: #fff;
    }
  }
  .gift-list {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    padding: 0 .15rem 0 .08rem;
    .gift-item {
      -webkit-backface-visibility: hidden;
      -webkit-transform: translate3d(0, 0, 0);
      position: relative;
      flex: 0 0 auto;
      width: calc(25% - 0.08rem);
      margin: 0.08rem 0 0.18rem 0.08rem;
      border-radius: .1rem;
      overflow: hidden;
      .box {
        text-align: center;
        white-space: nowrap;
        overflow: hidden;
        cursor: pointer;
        border: 1px solid transparent;
        padding: 0.05rem 0;
        background: linear-gradient(180deg, rgba(90,93,135,.3) 0%, rgba(90, 93, 135, 0) 100%);
        background-repeat: no-repeat;
        border-radius: .1rem;
        overflow: hidden;
        .bg {
          background: #171616;
          z-index: -1;
          position: absolute;
          top: 0.01rem;
          bottom: 0.01rem;
          left: 0.01rem;
          right: 0.01rem;
          width: calc(100% - 0.02rem);
          height: calc(100% - 0.02rem);
          border-radius: .1rem;
          overflow: hidden;
        }
        .img {
          margin: .02rem 0;
          position: relative;
          padding-top: calc(100% - 0.11rem);
          img {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: contain;
            transition: .3s all;
          }
        }
        .name {
          margin: .02rem 0;
          line-height: 0.2rem;
          font-size: 0.12rem;
          color: #FFF;
        }
        .price {
          margin: .02rem 0;
          line-height: 0.08rem;
          font-size: 0.12rem;
          color: #AAA;
          transform: scale(0.85);
          padding-bottom: 0.06rem;
        }
        &.z-active {
          border: 0.01rem solid #80d0f9;
          .img {
            img {
              transform: scale(1.1);
            }
          }
        }
        &.z-active-progress {
          .progress {
            .container {
              z-index: -2;
              position: absolute;
              top: -0.5rem;
              bottom: 0;
              overflow: hidden;
              .halfCir {
                  width: 1rem;
                  height: 2rem;
                  background: #FF8484;
              }
            }
            .right {
              left: 0.5rem;
              .halfCir {
                  left: 0;
                  border-radius: 0 2rem 2rem 0;
                  transform-origin: 0 50%;
                  animation: halfCir1 4s linear;
              }
            }
            .left {
              left: -0.5rem;
              .halfCir {
                  border-radius: 2rem 0 0 2rem;
                  transform-origin: 1rem 1rem;
                  animation: halfCir2 4s linear;
              }
            }
            @keyframes halfCir1 {
                50%, 100% {
                    transform: rotateZ(180deg);
                }
            }
            @keyframes halfCir2 {
                0%, 50% {
                    transform: rotateZ(0);
                }
                100% {
                    transform: rotateZ(180deg);
                }
            }
          }
          .img {
            img {
              transform: scale(1.1);
            }
          }
        }
      }
    }
  }
  .operation {
    padding: 0 0.05rem 0 0.15rem;
    height: 0.5rem;
    display: flex;
    align-items: center;
    .left {
      flex: 1;
      line-height: 0.2rem;
      display: flex;
      align-items: center;
      div {
        display: inline-block;
      }
      .icon {
        width: .12rem;
        height: .12rem;
        background: url('./img/icon-bi.png') no-repeat center 55%;
        background-size: auto 100%;
        margin-left: .03rem;
      }
      .price {
        padding-left: .05rem;
        font-size: 0.1rem;
        color: #CFCFCF;
        line-height: 0.11rem;
      }
    }
    .right {
      background: rgba(255, 255, 255, 0.1);
      box-shadow: 0px 2px 2px 0px rgba(0, 0, 0, 0.25);
      border-radius: 28px;
      border: 1px solid rgba(137,137,137, 0.5);
      display: flex;
      align-items: center;
      font-size: .12rem;
      margin-right: .1rem;
      div {
        display: inline-block;
      }
      .num {
        padding-left: .1rem;
        font-weight: 300;
        line-height: .25rem;
        width: .2rem;
      }
      .send {
        width: .5rem;
        height: .25rem;
        border-radius: 28px;
        line-height: .25rem;
        text-align: center;
        transition: all .1s;
        color: #AAA;
        .picker {
          position: relative;
          bottom: 1.5rem;
          right: .6rem;
          width: 1.2rem;
          height: 1.2rem;
          border-radius: .1rem;
          background: rgba(0, 0, 0, 0.5);
          overflow: hidden;
          border: 1px solid rgba(137,137,137, 0.4);
          z-index: 1111;
          ::v-deep .vue-scroll-picker-layer {
            .top {
              background: linear-gradient(0, rgba(0,0,0,0.2) 10%, rgba(0,0,0,0.7));
              border-bottom: unset
            }
            .middle {
              background: rgba(255 ,255, 255, .2)
            }
            .bottom {
              background: linear-gradient(180deg, rgba(0,0,0,0.2) 10%, rgba(0,0,0,0.7));
              border-top: unset
            }
          }
        }
      }
      .send-active {
        background: linear-gradient(180deg, #3388F7 0%, #256BFD 100%);
        color: #fff;
      }
      .icon {
        margin: 0 0 0 .1rem;
        width: .12rem;
        height: .12rem;
        background: url('./img/icon-right.png') no-repeat center 55%;
        background-size: auto 80%;
        transform: rotate(-90deg);
        opacity: .5;
        margin-right: .1rem;
      }
    }
  }
}
</style>
