<template>
    <div class="packet-send-wrap">
      <back-bar :title="$t('redPacket.title')" class="redpacket-backbar" v-if="meechatType=='h5'" @onBack="hidePopup"></back-bar>
      <div class="send-wrap" :class="[{'is-private':isPrivate}]">
        <i class="el-icon-close" @click="hidePopup"></i>
        <i class="el-icon-question" @click="helpShow = true"></i>
        <h3 class="title">{{ $t('redPacket.title') }}</h3>
        <p class="redpacket-tips" :class="{'hidden': !tips}">{{tips}}</p>
        <div class="main-box">
          <div class="input-item">
            <span class="text">
              <!--<em v-if="!isPrivate">{{ $t('redPacket.random') }}</em>-->
              {{ $t('redPacket.totalAmount') }}
            </span>
            <div class="packet-box" >
              <input type="number" v-model.number="money" placeholder="0.00">
              <div class="unit">
                <div :class="['cur-unit',{'has-arrow':group.eosInfo}]">{{symbol}}</div>
                <div class="code-menu" v-if="group.eosInfo">
                  <div class="code-item" @click="isGameToken = !isGameToken">
                    {{!isGameToken ? group.eosInfo.token : 'EOS'}}
                  </div>
                </div>
              </div>
            </div>
          </div>
          <p class="input-tips" v-if="!isPrivate">
            {{ $t('redPacket.tip1') }}
          </p>
          <div class="input-item pack-num-input" v-if="!isPrivate">
            <span class="text">{{ $t('redPacket.num') }}</span>
            <div class="packet-box">
              <input type="number" v-model.number="packetNum" :placeholder="$t('redPacket.placeholder1')">
              <div class="unit">{{ $t('redPacket.unit') }}</div>
            </div>
          </div>
          <p class="group-user-num" v-if="!isPrivate">
            {{ $t('redPacket.tip2', {num: group.membersNum}) }}
          </p>
          <textarea class="words" v-model="word" :placeholder="$t('redPacket.memo')"></textarea>
          <div class="sum">
            {{amountSum}} <span>{{isGameToken ? group.eosInfo.token : 'EOS'}}</span>
          </div>
          <button class="send-btn" @click="sendPacket" :class="{'is-disable': !amountSum || !packetNum, 'loading': isLoading}">
            <i v-if="isLoading" class="el-icon-loading"></i> {{ $t('redPacket.sendBtn') }}
          </button>
        </div>
        <p class="bot">{{ $t('redPacket.tip3') }}</p>
      </div>
      <div class="help-wrap" v-show="helpShow">
        <i class="el-icon-close" @click="helpShow = false"></i>
        <h3 class="title">{{ $t('redPacket.helpTitle') }}</h3>
        <div class="content">
          <div class="item">
            {{ $t('redPacket.helpRule1') }}
          </div>
          <div class="item">
            {{ $t('redPacket.helpRule2') }}
          </div>
          <div class="item">
            {{ $t('redPacket.helpRule3') }}
          </div>
        </div>
      </div>
    </div>
</template>

<script>
import { mapState, mapGetters } from 'vuex'
import { Message } from 'element-ui'
import NP from 'number-precision'
import EosHelper from '@/util/eosHelper.js'
import { getMeechatType } from '@/util/util'
import backBar from '@/components/backBar'

export default {
  name: 'packetSend',
  data () {
    return {
      visible: true,
      helpShow: false,
      money: 1,
      packetNum: 1,
      word: this.$t('redPacket.memo'),
      tips: '',
      isLoading: false,
      isGameToken: false, // 是否为游戏代币
      meechatType: getMeechatType()// meechat版本
    }
  },
  components: {
    backBar
  },
  computed: {
    ...mapState([
      'account',
      'group',
      'curSession',
      'scatter'
    ]),
    ...mapGetters(['isPrivate']),
    amountSum () {
      return this.money
    },
    symbol () {
      return this.isGameToken ? this.group.eosInfo.token : 'EOS'
    },
    minSum () {
      return this.isGameToken ? NP.divide(this.group.eosInfo.min_amount, 10000) : 0.1
    },
    maxSum () {
      return this.isGameToken ? NP.divide(this.group.eosInfo.max_amount, 10000) : 200
    }
  },
  watch: {
    money (val) {
      if (val > this.maxSum) {
        this.money = this.maxSum
        this.showTip(`${this.$t('redPacket.maxMoneyTip')} ${this.maxSum} ${this.symbol}`)
      }

      if (val && val / this.packetNum < 0.01) {
        this.money = NP.times(this.packetNum, 0.01)
        this.showTip(`${this.$t('redPacket.maxMoneyTip')} 0.01 ${this.symbol}`)
      }
    },
    packetNum (to, from) {
      if (this.money && NP.divide(this.money, to) < 0.01) {
        this.packetNum = from
        this.showTip(`${this.$t('redPacket.singleMinMoneyTip')} 0.01 ${this.symbol}`)
      }
      if (to > 100) {
        this.packetNum = 100
        this.showTip(`${this.$t('redPacket.maxNumberTip')} 100 个`)
      }
    }
  },
  methods: {
    hidePopup () {
      this.$emit('hidePopup')
    },
    showTip (msg, timeout = 3000) {
      this.tips = msg
      setTimeout(() => {
        this.tips = ''
      }, timeout)
    },
    async sendPacket () {
      if (this.money < this.minSum) {
        this.showTip(`${this.$t('redPacket.minMoneyTip')} ${this.minSum} ${this.symbol}`)
        return false
      }
      this.isLoading = true

      let eosAmount = this.amountSum.toFixed(4) + ` ${this.symbol}`
      let toAccount = 'meechatadmin'
      let memo = {
        type: 'redpack',
        num: this.packetNum,
        memo: this.word,
        sid: this.isPrivate ? this.curSession : this.group.groupId
      }
      let tokenCode = this.isGameToken ? this.group.eosInfo.token_code : 'eosio.token'
      let symbol = this.symbol
      let [balance] = await EosHelper.getCurrencyBalance(tokenCode, this.account.name, symbol)

      if (balance) {
        let userBalance = this.isGameToken ? balance.replace(new RegExp('\\s' + symbol), '') : balance.replace(/\sEOS/, '')
        if (this.amountSum > Number(userBalance)) {
          Message({
            message: this.$t('public.noMoney'),
            type: 'error'
          })
          this.isLoading = false
          return
        }
        if (this.isGameToken) {
          let tokenCode = this.group.eosInfo.token_code
          EosHelper.doSymbolTransfer(this.account.name, 'meechatadmin', eosAmount, JSON.stringify(memo), this.account.authority, tokenCode)
            .then(res => {
              this.hidePopup()
            }).catch(msg => {
              if (!msg.type) {
                let json = JSON.parse(msg)
                let details = json.error.details
                Message({
                  message: details[0].message,
                  type: 'error'
                })
              }
            }).finally(() => {
              this.isLoading = false
            })
        } else {
          EosHelper.transfer(this.account.name, toAccount, eosAmount, JSON.stringify(memo), this.account.authority)
            .then((res) => {
              this.hidePopup()
            }).catch(msg => {
              if (!msg.type) {
                let json = JSON.parse(msg)
                let details = json.error.details
                Message({
                  message: details[0].message,
                  type: 'error'
                })
              }
            }).finally(() => {
              this.isLoading = false
            })
        }
      } else {
        Message({
          message: this.$t('public.badNetwork'),
          type: 'error'
        })
        this.isLoading = false
      }
    }
  },
  mounted () {
  }
}
</script>

<style lang="scss">
@import './style.scss';
</style>
