<template>
  <!-- 下注 -->
  <div class="game-bet" :class="{'en-lang': $i18n.locale == 'en','kr-lang': $i18n.locale == 'kr'}">
    <!-- 开奖结果提示框 -->
    <div class="game-result-show" v-show="resultTipShow">
      <div class="game-reuslt-content">
        {{$t('game.resultTip.bet')}}<span class="bet-amount"> {{betSum}} </span>EOS,{{$t('game.resultTip.win')}}<span class="win-amount"> {{(winAmount > 0 ? winAmount/10000 : 0)}} </span>EOS
        <span class="closeResultModal" @click="resultTipShow = false">{{$t('game.resultTip.close')}}({{resultTipTime}})</span>
      </div>
    </div>
    <div class="bet-center-box">
      <div class="gt-tips">
        {{$t('gtTips')}} {{gtRate}} GT
        <i class="gt-times-icon" v-if="gtRate > 1">X{{gtRate}}</i>
        <i class="gt-help-icon" @click="showGtRules"></i>
      </div>
      <div class="bet-left-box">
        <span class="bet-tips">{{$t('game.betTip')}}</span>
        <div class="bet-input-wrap">
          <input class="bet-input" v-model.number="betNum" @input="oninput" @focus="onFocus" type="number" placeholder="請輸入籌碼">
        </div>
      </div>
    </div>
    <div class="bet-limit">
      <p>{{$t('k3.limit')}}:</p>
      <p>100 EOS</p>
    </div>
    <div class="animate-counter-wrap">
      <i class="animate-counter counter-pur" id="counterpur">{{this.betNum}}</i>
      <i class="animate-counter counter-red" id="counterred">{{this.betNum}}</i>
      <i class="animate-counter counter-blue" id="counterblue">{{this.betNum}}</i>
      <i class="animate-counter counter-green" id="countergreen">{{this.betNum}}</i>
      <i class="animate-counter counter-yellow" id="counteryellow">{{this.betNum}}</i>
      <i class="animate-counter counter-orange" id="counterorange">{{this.betNum}}</i>
    </div>
    <div class="counter-item-wrap">
      <div class="counter"
      v-for="(item, key) in counterList"
      :key="key"
      :class="[{'current': counterNum === item}, `counter-${counterColor(item)}`]"
      @click="changeInput(item)">
      {{item}}
      </div>
    </div>
    <div class="counter-target-wrap">
      <div class="counter counter-red counter-target" id="counter1">0.1</div>
      <div class="counter counter-blue counter-target" id="counter5">0.5</div>
      <div class="counter counter-pur counter-target" id="counter10">1</div>
      <div class="counter counter-green counter-target" id="counter50">5</div>
      <div class="counter counter-yellow counter-target" id="counter100">10</div>
      <div class="counter counter-orange counter-target" id="counter200">20</div>
    </div>
    <div class="bet-btn-wrap">
      <div class="clear-btn pub-btn" @click="$emit('clearbet')" :class="{'disabled': !betArray.length}">{{$t('game.clearBtn')}}</div>
      <div class="confirm-btn pub-btn" :class="{loading: disabledConfirm}" @click="confirmBet(1)">{{disabledConfirm ? 'Loading...' : $t('game.confirmBtn')}}</div>
      <div class="continute-btn pub-btn" v-if="!tenBeting" :class="{loading: disabledTen}" @click="confirmBet(10)">{{disabledTen? 'Loading...' : $t('k3.tenBet')}}</div>
      <div class="ten-beting-btn pub-btn" :class="{'en-btn': $i18n.locale == 'en'}" v-else>{{$t('k3.tenBetting')}}<span>{{tenTime}}/10</span></div>
    </div>
    <transition name="msgbox-fade">
      <ten-bet
        v-if="tenResult"
        @update:visible="endTenBet"
        @nextbet="nextBet"
        :result="tenResult"
      >
      </ten-bet>
    </transition>
  </div>
</template>

<script>
import Rules from '@/components/popup/rules'
import { mapState } from 'vuex'
import { showError } from '@/util/util'
import API from '@/api'
import NP from 'number-precision'
import tenBet from './tenBet'

export default {
  name: 'gameMain',
  props: ['betArray', 'betSum'],
  data () {
    return {
      counterList: [0.1, 0.5, 1, 5, 10, 20],
      disabledConfirm: false,
      disabledTen: false,
      betNum: 1,
      counterNum: 0,
      winAmount: 0, // 赢的钱
      resultTipShow: false, // 提示框
      resultTipTime: 3, // 倒计时
      tenTime: 1, // 连投次数
      tenBeting: false,
      tenResult: null // 十连投结果
    }
  },
  components: {
    tenBet
  },
  computed: {
    ...mapState({
      account: state => state.account,
      invitee: state => state.invitee,
      toAccount: state => state.toAccount,
      gtRate: state => state.gtRate,
      newOpen: state => state.newOpen
    }),
    balance () {
      return this.$store.state.balance ? NP.divide(this.$store.state.balance, 10000) : 0
    }
  },
  watch: {
    newOpen (to, from) {
      if (to.player === this.account.name) {
        // 十连投
        if (to.is_finish === 1 && to.times === 10) {
          // 结束
          this.tenResult = to
        }
        if (to.times === 10) {
          this.tenTime = to.index
          this.$store.commit('updateBalance', to.win_int)
        }
        // 普通下注
        if (to.index === to.times && to.index === 1) {
          this.$hideTips()
          this.winAmount = to.win_int
          this.$store.commit('updateBalance', to.win_int)
          this.showResult()
        }
      }
    }
  },
  methods: {
    showGtRules () {
      Rules.showGTRules()
    },
    showResult () {
      this.resultTipShow = true
      let timer = setInterval(() => {
        this.resultTipTime--
        if (this.resultTipTime === 0) {
          this.resultTipShow = false
          this.resultTipTime = 3
          this.$emit('update:newgame')
          clearInterval(timer)
        }
      }, 1000)
    },
    counterColor (num) {
      let key = num.toString()
      let colorMap = {
        '0.1': 'red',
        '0.5': 'blue',
        '1': 'pur',
        '5': 'green',
        '10': 'yellow',
        '20': 'orange'
      }
      return colorMap[key]
    },
    oninput (e) {
      let bet = (e.target.value.match(/^\d*(\.?\d{0,1})/g)[0]) || ''
      this.betNum = bet ? Number(bet) : ''
      if (this.betNum) {
        this.$emit('update:betNum', this.betNum)
      }
    },
    onFocus () {
      this.counterNum = 0
      this.$emit('update:counter', false)
    },
    confirmBet (time) {
      if (!this.account.name) {
        this.$store.dispatch('doScatterLogin')
        return
      }
      if (this.betArray.length) {
        time === 1 ? this.disabledConfirm = true : this.disabledTen = true // 禁止点击
        // 下注组合
        let codeArr = []
        let mergeObj = {}
        this.betArray.forEach(v => {
          let bet = v.bet
          let type = v.code
          // 合并处理
          if (mergeObj.hasOwnProperty(type)) {
            mergeObj[type] = mergeObj[type] + bet
          } else {
            mergeObj[type] = bet
          }
        })

        for (let k in mergeObj) {
          codeArr.push(k)
          codeArr.push(mergeObj[k])
        }

        let codeStr = codeArr.join('|')
        this.eosBet(codeStr, time)
      } else {
        this.$showTips(this.$t('noBet'))
      }
    },
    changeInput (item) {
      this.counterNum = item
      this.betNum = item
      this.$emit('update:betNum', item)
      this.$emit('update:counter', true)
    },
    // EOS下注
    eosBet (codeStr, time) {
      // 余额不足
      if (this.balance < NP.times(this.betSum, time)) {
        this.$showTips(this.$t('noMoney'))
        time === 1 ? this.disabledConfirm = false : this.disabledTen = false
        return
      }

      let invitee = this.invitee || 0
      let memo = `k3|${invitee}|${time}|${codeStr}`
      let EOS = NP.times(this.betSum, time).toFixed(4)
      let identity = { authorization: [`${this.account.name}@${this.account.authority}`] }

      this.$showLoading()
      // 调起转账
      window.EOS.transfer(this.account.name, 'eosgetdice12', EOS + ' EOS', memo, identity).then(trx => {
        let param = {
          transaction_id: trx.transaction_id,
          block_num: trx.processed.block_num ? trx.processed.block_num : '',
          player: this.account.name
        }
        let oneAmount = NP.times(this.betSum, 10000)
        let balanceAmount = NP.times(oneAmount, time)

        API.game.sendTrx(param).then(({ data }) => {
          if (data.result === 1) {
            // 数目增减
            this.$store.commit('updateBalance', -balanceAmount)
            let eosAmount = NP.divide(balanceAmount, 10000)
            this.$store.commit('updateGt', NP.times(this.gtRate, eosAmount))

            // 十连投
            if (time === 10) {
              this.tenBeting = true
            } else {
              this.$showTips(this.$t('waiting'), false)
            }
          }
        }).finally(() => {
          time === 1 ? this.disabledConfirm = false : this.disabledTen = false
          this.$hideLoading()
        })
      }).catch(msg => {
        time === 1 ? this.disabledConfirm = false : this.disabledTen = false
        this.$hideLoading()
        if (msg.type === 'signature_rejected') {
          this.$showTips(this.$t('failBet'))
        } else {
          let json = JSON.parse(msg)
          let details = json.error.details
          showError(details[0].message)
        }
        // 十连投继续下注拒绝处理
        if (this.tenBeting) {
          this.endTenBet()
          localStorage.removeItem('ten_ben_checked')
        }
      })
    },
    endTenBet () {
      this.tenResult = null
      this.tenBeting = false
      this.tenTime = 1
      this.$emit('update:newgame')
    },
    nextBet () {
      this.tenResult = null
      this.tenTime = 1
      this.confirmBet(10)
    }
  }
}
</script>
