<template>
  <transition name="msgbox-fade">
    <div class="pub-modal-mask pub-scroll-box" v-if="visible">
      <div class="packet-bg" v-if="!openInfo" v-loading='isLoading'>
        <i class="el-icon-close" @click="visible = false"></i>
        <div class="user-info"  :class="{'small': info.ext.redpack_status == 1}">
          <img class="avatar" v-if="info.avatar" :src="info.avatar" alt="">
          <div v-else class="avatar no-avatar" :class="'avatar_bg' + userId % 9">{{info.name.slice(0,2).toUpperCase()}}</div>
          <span class="name">{{info.name}}</span>
          <div class="text"  v-if="info.ext.redpack_status == 0">{{info.content.title}}</div>
        </div>
        <!-- redpack_status: 0 => 进行中, 1 => 已抢完, 2 => 已过期 -->
        <div class="open-btn" :class="{'loading': isLoading}" v-if="info.ext.redpack_status == 0" @click="openPacket">{{$t('redPacket.open')}}</div>
        <div class="redpack-tips" v-else-if="info.ext.redpack_status == 1">
          {{$t('redPacket.noPacketTips')}}
        </div>
        <div class="redpack-tips" v-else-if="info.ext.redpack_status == 2">
          {{$t('redPacket.expiredPacketTips')}}
        </div>
        <div class="detail" v-if="userId == info.userId || info.ext.redpack_status == 1" @click="showDetail">{{$t('redPacket.seePacketDetail')}}</div>
      </div>
      <div class="detail-bg" :class="{'is-quantity':quantity}" v-else @touchstart="touchstartForH5" @touchend="touchendForH5">
        <i class="el-icon-close" @click="visible = false"></i>
        <nav class="nav-bar">
          <i class="el-icon-arrow-left" @click="visible = false"></i>
          <!-- <a class="packet-record">红包记录</a> -->
        </nav>
        <img class="avatar" v-if="info.avatar" :src="info.avatar" alt="">
        <div v-else class="avatar no-avatar" :class="'avatar_bg' + userId % 9">{{info.name.slice(0,2).toUpperCase()}}</div>
        <span class="name">{{info.name}}</span>
        <div class="text">{{info.content.title}}</div>
        <div class="money" v-if="quantity">
          {{formatNum(quantity)}} <em>{{openInfo.tokenType}}</em>
        </div>
        <p class="state" v-if="quantity">{{$t('redPacket.transferTo')}}{{openInfo.type.toUpperCase()}}{{$t('redPacket.account')}}</p>
        <p class="state-num">
          {{ $t('redPacket.tip4', { total: openInfo.num_total, num: openInfo.num_total - openInfo.num_left, unit: $t('redPacket.unit') }) }}
        </p>
        <ul class="packet-list pub-scroll-box">
          <li v-for="(item, key) in openInfo.logs" :key="key">
            <img class="avatar" v-if="item.cover_photo" :src="item.cover_photo" alt="">
            <div v-else class="avatar no-avatar" :class="'avatar_bg' + item.user_id % 9">
              {{item.nick_name.slice(0,2).toUpperCase()}}
            </div>
            <div class="content">
              <div class="top">
                <span class="user-name">{{item.nick_name}}</span>
                <span class="amount">{{formatNum(item.quantity_int)}} {{openInfo.tokenType}}</span>
              </div>
              <div class="bottom">
                <span class="time">{{formatTime(item.update_time_int)}}</span>
                <span class="best" v-if="item.best"></span>
              </div>
            </div>
          </li>
        </ul>
        <p class="tips">{{$t('redPacket.tip3')}}</p>
      </div>
    </div>
  </transition>
</template>

<script>
import API from '@/api'
import NP from 'number-precision'
import { mapState } from 'vuex'
import { Message } from 'element-ui'
import { getMeechatType } from '@/util/util'
import dayjs from 'dayjs'

export default {
  name: 'packetGet',
  data () {
    return {
      openInfo: null,
      isLoading: false,
      isHasDetail: false,
      meechatType: getMeechatType(),
      startClientX: 0
    }
  },
  computed: {
    ...mapState([
      'userId',
      'account'
    ]),
    trxId () {
      return this.info.content.trxId
    },
    quantity () {
      if (this.openInfo && this.openInfo.logs.length) {
        let arr = this.openInfo.logs
        let item = arr.find(v => {
          return v.user_id == this.userId
        })
        if (item) {
          return item.quantity_int
        } else {
          return 0
        }
      } else {
        return 0
      }
    },
    isPrivate () {
      return this.$store.getters.isPrivate
    }
  },
  methods: {
    openPacket () {
      this.isLoading = true
      API.redpack.grabPacket({
        trx_id: this.trxId
      }).then(({ data }) => {
        // 抢光
        if (data.code === -1001) {
          this.$store.commit('unpdatePacketItem', {
            type: 'redpack_status',
            trxId: this.trxId,
            data: 1
          })
        } else {
          this.openInfo = data.data
          this.$store.commit('unpdatePacketItem', {
            type: 'grabbed',
            trxId: this.trxId,
            data: 1
          })
        }
      }).finally(() => {
        this.isLoading = false
      })
    },
    showDetail () {
      API.redpack.grabDetail({
        trx_id: this.trxId
      }).then(({ data }) => {
        this.openInfo = data.data
        if (this.meechatType == 'h5') this.initSwipeForH5()
      })
    },
    formatNum (num) {
      return NP.divide(Number(num), 10000)
    },
    formatTime (timestamp) {
      return dayjs(timestamp).format('HH:mm')
    },
    preHandleOpenInfo (openInfo) {
      if (openInfo && openInfo.logs.length === openInfo.num_total) {
        let best = openInfo.logs[0]
        openInfo.logs.forEach(item => {
          if (item.quantity_int > best.quantity_int) {
            best = item
          }
        })
        best.best = true
      }
    },
    touchstartForH5 (ev) {
      if (this.meechatType != 'h5') return

      this.startClientX = ev.changedTouches[0].clientX
    },
    touchendForH5 (ev) {
      if (this.meechatType != 'h5') return

      let clientX = ev.changedTouches[0].clientX

      if (Math.abs(clientX - this.startClientX) > 60) this.visible = false
    }
  },
  created () {
    if (this.userId) {
      API.redpack.grabDetail({
        trx_id: this.trxId
      }).then(({ data }) => {
      // 已经领取
        if ((this.info.userId == this.userId && this.isPrivate) || this.info.ext.grabbed) {
          this.openInfo = data.data
        } else if (data.data.num_left == 0) {
        // 没领取
          this.$store.commit('unpdatePacketItem', {
            type: 'redpack_status',
            trxId: this.trxId,
            data: data.data.redpack_status
          })
        }
        this.visible = true
      })
    } else {
      Message({
        message: this.$t('public.loginTip'),
        type: 'warning'
      })
    }
  }
}
</script>

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