<template>
  <transition name="msgbox-fade">
    <div class="pub-wrapper" v-if="visible">
      <div class="pub-mask" @click="visible = false"></div>
      <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" @blur="inputBlur" placeholder="0.00">
                <div class="unit">
                  <div class="cur-unit has-arrow">{{symbol}}</div>
                  <div class="code-menu">
                    <div :class="['code-item',{'disabled':loginType!='eos'}]" @click="changeSymbol('EOS')">EOS</div>
                    <div :class="['code-item',{'disabled':loginType!='meetone'}]"  @click="changeSymbol('MEETONE')" v-if="loginType=='meetone'">MEETONE</div>
                    <!-- <div :class="['code-item',{'disabled':loginType!='eth'}]"  @click="changeSymbol('ETH')">ETH</div> -->
                    <div class="code-item" @click="changeSymbol(group.eosInfo.token)" v-if="group.eosInfo">{{group.eosInfo.token}}</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')" @blur="inputBlur">
                <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>{{symbol}}</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>
    </div>
  </transition>
</template>

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

export default {
  name: 'packetSend',
  data () {
    let loginType = getUserOpt('loginType') || 'eos'

    return {
      visible: true,
      helpShow: false,
      money: 1,
      packetNum: 1,
      word: this.$t('redPacket.memo'),
      tips: '',
      loginType: loginType,
      symbol: 'EOS', // 单位
      isLoading: false,
      isGameToken: false, // 是否为游戏代币
      meechatType: getMeechatType()// meechat版本
    }
  },
  components: {
    backBar
  },
  computed: {
    ...mapState([
      'account',
      'group',
      'curSession',
      'scatter',
      'userInfo'
    ]),
    ...mapGetters(['isPrivate']),
    amountSum () {
      return this.money
    },
    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}`)
        this.showTip(`${this.$t('redPacket.singleMinMoneyTip')} 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: {
    inputBlur () {
      mobileInputBlur()
    },
    changeSymbol (type) {
      this.symbol = type

      // 游戏代币判断
      this.isGameToken = this.group.eosInfo && this.group.eosInfo.token == type
    },
    hidePopup () {
      this.visible = false
    },
    showTip (msg, timeout = 3000) {
      this.tips = msg
      setTimeout(() => {
        this.tips = ''
      }, timeout)
    },
    // 检测是否有发红包权限
    checkCanSend () {
      let loginType = this.loginType
      let checksSymbol = this.symbol.toLowerCase()

      if (checksSymbol == 'eth') {
        if (!window.ethereum || !window.web3) {
          showError('你还没有安装eth插件')
          return false
        }
      } else {
        // eos币种校验
        let eosType = getUserOpt('eosType') || 'eos'

        // 判断登录
        if (loginType != 'eos' && loginType != 'meetone') {
          Message({
            message: this.$t('redPacket.sendForEosTips'),
            type: 'error'
          })
          return false
        }

        // 判断绑定
        if (checksSymbol == 'eos' || checksSymbol == 'meetone') {
          let flag = this.userInfo.binds.some((item) => {
            return item.type == checksSymbol && item.account
          })

          if (!flag) {
            Message({
              message: this.$t('redPacket.bindForEosTips', { 'type': checksSymbol }),
              type: 'error'
            })
            return false
          }
        }

        // 判断scatter现在身份和登录身份是否一致
        if (loginType != eosType) {
          Message({
            message: '重新检查下scatter身份',
            type: 'error'
          })
          return false
        }
      }

      return true
    },
    async sendPacket () {
      if (!this.checkCanSend()) return

      if (this.money < this.minSum) {
        this.showTip(`${this.$t('redPacket.minMoneyTip')} ${this.minSum} ${this.symbol}`)
        return false
      }

      this.isLoading = true
      switch (this.symbol) {
        case 'Tron':
          this.transferTron()
          break
        case 'ETH':
          this.transferEth()
          break
        default:
          this.transferEos()
          break
      }
    },
    // eos转换
    async transferEos () {
      let eosAmount = this.amountSum.toFixed(4) + ` ${this.symbol}`
      let toAccount = this.symbol == 'MEETONE' ? 'meechat.m' : '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, toAccount, 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 {
          // eos/meetone
          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.noMoney'),
          type: 'error'
        })
        this.isLoading = false
      }
    },
    async transferEth () {
      try {
        await EthHelper.doTransfer(this.money)
        this.hidePopup()
      } catch (e) {
        this.isLoading = false
      }
    },
    transferTron () {

    }
  },
  mounted () {
  }
}
</script>

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