<template>
  <transition name="msgbox-fade">
    <div class="popup-wrap mod-lottery">
      <div class="popup-modal"></div>
      <div class="popup-box">
        <div class="popup-hd">
          <div class="popup-hd-title"><em>{{$t('lottery.title')}}</em></div>
          <span class="popup-close" @click="$emit('visible:lottery')"></span>
        </div>
        <div class="popup-bd">
          <div class="lottery-wrap">
            <p class="left-time">{{$t('lottery.text1')}}：{{leftTimes}}</p>
            <div class="lottery-wheel" v-if="rewardList.length">
              <div class="wheel" :style="{transform: `rotate(${rotateDeg}deg)`}">
                <div class="rotate-box" v-for="(item, key) in rewardList" :key="key">
                  <div class="wheel-item">
                    <span class="amount">{{item}}</span>
                    <i class="gold-eos-icon"></i>
                  </div>
                </div>
              </div>
              <div class="lottery-btn" :class="{'lottery-btn-small': isRotating}" v-if="ttl == 0" @click="runLottery">
                {{isRotating ? $t('lottery.text2') : $t('lottery.text3')}}
              </div>
              <div class="lottery-btn disabled" v-else-if="ttl == -1">{{$t('lottery.text3')}}</div>
              <div class="lottery-btn disabled time-count-down" v-else>{{timeStr}}</div>
            </div>
            <transition name="msgbox-fade">
              <div class="lottery-result" v-if="luckResult">
                <div class="num">{{$t('lottery.text5')}}：{{luckResult.luckdraw_num}}</div>
                <div class="lottery-fair">
                  <span class="title">{{$t('lottery.text5')}}</span>
                  <a target="_blank" :href="`https://eospark.com/block/${luckResult.next_block_num}`" class="fair-num">{{luckResult.next_block_num}}</a>
                  <a target="_blank" :href="`https://eospark.com/block/${luckResult.next_block_num}`" class="hash" v-html="luckHash"></a>
                </div>
                <div class="lottery-fair">
                  <span class="title">{{$t('lottery.text3')}}</span>
                  <a target="_blank" :href="`https://eospark.com/tx/${luckResult.trx_id}`" class="fair-num">{{luckResult.draw_block_num}}</a>
                  <a target="_blank" :href="`https://eospark.com/tx/${luckResult.trx_id}`" class="hash">...{{luckResult.trx_id.substring(luckResult.trx_id.length - 30,luckResult.trx_id.length)}}</a>
                </div>
              </div>
            </transition>
            <p class="lottery-tips">{{$t('lottery.text4')}}</p>
          </div>
        </div>
      </div>
    </div>
  </transition>
</template>
<script>
import API from '@/api'
import { mapState } from 'vuex'
import { showError } from '@/util/util'

export default {
  name: "lottery",
  data() {
    return {
      rewardList: [],
      rotateDeg: 60,
      isRotating: false,
      leftTimes: 0, //抽奖剩余次数
      ttl: 0, //剩余秒数
      luckResult: null, //抽奖结果
      timeStr: ''
    }
  },
  computed: {
    identity() {
      return { authorization:[`${this.account.name}@${this.account.authority}`] }
    },
    luckHash() {
      if(this.luckResult) {
        let hash = this.luckResult.next_block_id
        let luckNum = this.luckResult.luckdraw_num.toString()
        let subHash = hash.substring(hash.length - 30,hash.length)
        let hashArr = subHash.split('')
        let luckLen = luckNum.length
        let k = 0
        for(let i = hashArr.length - 1; i >= 0; i--) {
          let char = hashArr[i]
          if(luckNum.indexOf(char) > -1 && k < luckLen) {
            let newChar = `<span class="yellow">${char}</span>`
            hashArr.splice(i, 1, newChar)
            k ++
          }
        }
        return '...' + hashArr.join('')
      } else {
        return ''
      }
    },
    ...mapState({
      eos: state => state.eos,
      account: state => state.account,
    }),
  },
  methods: {
    async runLottery() {
      this.$showLoading()
      var doAction = (param) => {
        API.eos.sendLuckTrx(param)
        .then(({data}) => {
          this.$hideLoading()
          if(data.code == 0) {

            // 计算角度
            let rewardAmount = data.data.luckdraw_amount_int / 10000
            let ind = this.rewardList.indexOf(rewardAmount.toString())
            this.rotateDeg = 1800 + ind * 60
            this.isRotating = true

            // 结束抽奖
            setTimeout(() => {
              this.isRotating = false
              this.luckResult = data.data
              this.$store.commit('updateBalance', data.data.luckdraw_amount_int)
              this.leftTimes --
              this.ttl = 3600
              this.timer = setInterval(() => {
                this.updateTime()
              }, 1000)
            }, 3500)
          }
        }).catch(err => {
          this.$hideLoading()
        })
      }

      if(this.$isLogin()) {
        var memo = 'luckdraw'
      } else {
        var memo = 'luckdraw|' + await this.$getRandom()
      }

      window.EOS.contract('eosgetadmin1').then(contract => {
        contract.luckdraw(this.account.name, memo, this.identity)
          .then(trx => {
            doAction({
              transaction_id: trx.transaction_id,
              block_num: trx.processed.block_num ? trx.processed.block_num : ''
            })
          })
          .catch(msg => {
            this.$hideLoading()
            if (msg.type === 'signature_rejected') {
              return
            }
            let json = JSON.parse(msg)
            let details = json.error.details
            showError(details[0].message)
          })
      })
    },
    updateTime() {
      if(this.ttl > 0) {
        let ttl = this.ttl
        let M = Math.floor(ttl % 3600 / 60)
        M = M < 10 ? '0' + M : M;
        let S = Math.floor(ttl % 3600 % 60)
        S = S < 10 ? '0' + S : S;
        this.timeStr = `${M}:${S}`
        this.ttl -= 1
        if(this.ttl == 0) {
          clearInterval(this.timer)
        }
      }
    },
    getLuckInfo() {
      API.eos.getLuckInfo({
        player: this.account.name
      }).then(({data}) => {
        this.leftTimes = data.data.times
        this.ttl = data.data.limit //-1不能抽，0可以抽, 大于0是倒计时秒数
        
        let rewardData = data.data.reward_conf
        rewardData.forEach(e => {
          this.rewardList.push(e.formatAmount.toFixed(4))
        })

        if(this.ttl > 0) {
          this.timer = setInterval(() => {
            this.updateTime()
          }, 1000)
        }
      })
    },
    beforeDestroy() {
      if(this.timer) {
        clearInterval(this.timer)
      }
    }
  },
  async created() {
    if(!this.account.name) {
      await this.$parent.login()
    }
    this.getLuckInfo()
  },
};
</script>
<style lang="scss">
.popup-wrap {
  &.mod-lottery{
    .popup-box{
      width: px2rem(730);
    }
  }
}
.lottery-wrap{
  color: #ffffff;
  .left-time{
    font-size: px2rem(16);
    text-align: center;
  }
}
.lottery-result{
  .num{
    width: px2rem(230);
    height: px2rem(70);
    font-size: px2rem(18);
    line-height: px2rem(70);
    margin: 0 auto;
    background-color: #394d80;
    font-weight: bold;
    margin: px2rem(20) auto px2rem(30);
  }
}
.lottery-fair{
  text-align: center;
  font-size: px2rem(14);
  margin-bottom: px2rem(8);
  font-weight: bold;
  .fair-num{
    display: inline-block;
    margin: 0 px2rem(6);
    width: px2rem(80);
    text-align: left;
    text-decoration: none;
    color: #ffffff;
  }
  .hash{
    display: inline-block;
    width: px2rem(320);
    text-align: left;
    text-decoration: none;
    color: #ffffff;
    .yellow{
      color: #ffeb00;
      font-weight: bold;
    }
  }
  .title{
    display: inline-block;
    width: px2rem(60);
    text-align: left;
  }
}
.lottery-tips{
  font-size: px2rem(14);
  line-height: 1.4;
  font-weight: bold;
  margin: px2rem(30) 0 px2rem(20);
}
.lottery-wheel{
  width: px2rem(504);
  height: px2rem(504);
  margin: px2rem(12) auto;
  position: relative;
  .rotate-box{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    &:nth-child(2) {
      .wheel-item{
        transform: rotate(60deg);
      }
    }
    &:nth-child(3) {
      .wheel-item{
        transform: rotate(120deg);
      }
    }
    &:nth-child(4) {
      .wheel-item{
        transform: rotate(180deg);
      }
    }
    &:nth-child(5) {
      .wheel-item{
        transform: rotate(240deg);
      }
    }
    &:nth-child(6) {
      .wheel-item{
        transform: rotate(300deg);
      }
    }
  }
  .wheel{
    position: absolute;
    background: url('./img/wheel.png') no-repeat;
    width: px2rem(504);
    height: px2rem(504);
    background-size: 100%;
    transition: transform 3s ease;
  }
  .lottery-btn{
    position: absolute;
    top: 50%;
    left: 50%;
    width: px2rem(135);
    height: px2rem(154);
    box-sizing: border-box;
    padding-top: px2rem(70);
    margin-top: -px2rem(77);
    margin-left: -px2rem(135 / 2);
    background: url('./img/lottery-btn.png') no-repeat;
    background-size: 100%;
    text-align: center;
    color: #ffffff;
    font-size: px2rem(36);
    cursor: pointer;
    transition: all .3s ease-in-out;
    &:hover{
      background: url('./img/lottery-btn-hover.png') no-repeat;
      background-size: 100%;
    }
    &.disabled{
      background: url('./img/lottery-btn-disabled.png') no-repeat;
      background-size: 100%;
      cursor: default;
    }
    &.time-count-down{
      font-size: px2rem(28);
      padding-top: px2rem(74);
    }
  }
  .lottery-btn-small{
    font-size: px2rem(24);
  }
  .wheel-item{
    text-align: center;
    width: px2rem(100);
    margin: 0 auto;
    text-align: center;
    padding-top: px2rem(86);
    transform-origin: 50% px2rem(504/2);
    .amount{
      display: block;
      font-weight: bold;
      font-size: px2rem(24);
      color: #df951f;
    }
  }
}
.gold-eos-icon{
  background: url('./img/gold-eos-icon.png') no-repeat;
  background-size: 100%;
  display: block;
  width: px2rem(22);
  margin: px2rem(6) auto;
  height: px2rem(32);
}
</style>
