<template>
  <transition name="msgbox-fade">
    <div class="pub-modal-mask pub-scroll-box" v-if="visible">
      <div class="send-wrap">
        <i class="el-icon-close" @click="visible = false"></i>
        <i class="el-icon-question" @click="helpShow = true"></i>
        <h3 class="title">发红包</h3>
        <p class="redpacket-tips" :class="{'hidden': !tips}">{{tips}}</p>
        <div class="main-box">
          <div class="input-item">
            <span class="text">
              <em>拼</em>总金额
            </span>
            <div class="packet-box">
              <input type="number" v-model.number="money" placeholder="0.00">
              <span class="unit">
                {{symbol}}
                <i v-if="group.eosInfo" class="down-arrow"></i>
                <div class="code-menu" v-if="group.eosInfo">
                  <div class="code-item" @click="isGameToken = !isGameToken">
                    {{!isGameToken ? group.eosInfo.token : 'EOS'}}
                  </div>
                </div>
              </span>
            </div>
          </div>
          <p class="input-tips">
            当前为拼手气红包
          </p>
          <div class="input-item pack-num-input">
            <span class="text">红包个数</span>
            <div class="packet-box">
              <input type="number" v-model.number="packetNum" placeholder="请填写个数">
              <span class="unit">个</span>
            </div>
          </div>
          <p class="group-user-num">
            本群共{{group.userCounts}}人
          </p>
          <textarea class="words" v-model="word" placeholder="恭喜发财，大吉大利"></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> 塞钱进红包
          </button>
        </div>
        <p class="bot">未领取的红包，将于24小时后发起退款</p>
      </div>
      <div class="help-wrap" v-show="helpShow">
        <i class="el-icon-close" @click="helpShow = false"></i>
        <h3 class="title">帮助</h3>
        <div class="content">
          <div class="item">
            1. 发出的红包均为拼手气红包，抢得的
            红包金额随机；一次最多发100个红包；
          </div>
          <div class="item">
            2. 发红包时可选择币种；抢到的红包金额
            直接转账到对应币种的绑定账户；若未绑
            定账户，则所得币种余额在绑定账户后即
            刻转账；
          </div>
          <div class="item">
            3. MeeChat会从每次发出红包的金额中收
            取2%的手续费，用于支付上链成本
          </div>
        </div>
      </div>
    </div>
  </transition>
</template>

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

export default {
  name: 'packetSend',
  data () {
    return {
      helpShow: false,
      money: 1,
      packetNum: 1,
      word: '恭喜发财，大吉大利',
      tips: '',
      isLoading: false,
      isGameToken: false // 是否为游戏代币
    }
  },
  computed: {
    ...mapState([
      'account',
      'group',
      'curSession'
    ]),
    isPrivate () {
      return this.$store.getters.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.maxSum} ${this.symbol}`)
      }

      if (val && val / this.packetNum < 0.01) {
        this.money = NP.times(this.packetNum, 0.01)
        this.showTip(`单个红包最小为 0.01 ${this.symbol}`)
      }
    },
    packetNum (to, from) {
      if (this.money && NP.divide(this.money, to) < 0.01) {
        this.packetNum = from
        this.showTip(`单个红包最小为 0.01 ${this.symbol}`)
      }
      if (to > 100) {
        this.packetNum = 100
        this.showTip('红包个数最大为 100 个')
      }
    }
  },
  methods: {
    showTip (msg, timeout = 3000) {
      this.tips = msg
      setTimeout(() => {
        this.tips = ''
      }, timeout)
    },
    async sendPacket () {
      if (this.money < this.minSum) {
        this.showTip(`总金额 不能少于 ${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: '账户余额不足',
            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.visible = false
            }).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.visible = false
            }).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: '网络太差~ 请重试',
          type: 'error'
        })
        this.isLoading = false
      }
    }
  },
  mounted () {
  }
}
</script>

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