<template>
  <div class="lottery-message">
    <template v-if="!isLoading">
      <!-- 未开奖 -->
      <template v-if="lotteryInfo.status !== SESSION_STATUS.end">
        <div class="lottery-message__img">
          <img :src="lotteryInfo.prizeIcon" alt="" />
        </div>
        <div class="lottery-message__name">{{ lotteryInfo.prizeName }}</div>
        <div class="lottery-message__num">共{{ lotteryInfo.prizeSum }}个</div>
        <div class="lottery-message__rules">
          <p class="lottery-message__rules-title">参与规则：</p>
          <div class="lottery-message__rules-content">
            <!-- 非口令留言 -->
            <template v-if="!lotteryInfo.specialSwitch"> 在直播间内评论留言即可参与抽奖。 </template>
            <!-- 口令留言 -->
            <template v-else>
              <p>
                输入口令<span class="lottery-message__keywords">{{ lotteryInfo.specialContent }}</span
                >即可参与抽奖
              </p>
              <div class="lottery-message__copy-wrap">
                <span class="lottery-message__copy" @click="onCopyHandler(lotteryInfo.specialContent)"
                  >一键复制口令并发送
                </span>
              </div>
            </template>
          </div>
        </div>
      </template>
      <!-- 已开奖 且中奖-->
      <template v-if="lotteryInfo.status === SESSION_STATUS.end && winInfo.isWin">
        <div class="lottery-message__img">
          <img :src="winInfo.prizeIcon" alt="" />
        </div>
        <div class="lottery-message__win-text">
          <span>恭喜中奖</span>
          <span>获得</span>
          <span>{{ winInfo.prizeName }}</span>
        </div>
        <div class="lottery-message__win-sub">
          <!-- 实物 线下核销 -->
          <template v-if="winInfo.exchangeType === LOTTERY_EXCHANGE_TYPE.offline">
            前往<span @click="openRecordHandler">抽奖记录</span>使用兑换码进行兑换
          </template>
          <!-- 实物 邮寄 -->
          <template v-if="winInfo.exchangeType === LOTTERY_EXCHANGE_TYPE.mailing && !winInfo.address">
            填写<span @click="openAddressHandler">收货地址</span>等待官方邮寄
          </template>
          <!-- 虚拟物品 -->
          <!-- <template v-if="lotteryInfo.prizeType === LOTTERY_MESSAGE_PRIZE_TYPE.online"
            >已进入您<span @click="openWalletHandler">个人中心-钱包</span>请查收</template
          > -->
        </div>
        <div class="lottery-message__rules">
          <p class="lottery-message__rules-title">中奖说明：</p>
          <div class="lottery-message__rules-content">{{ lotteryInfo.winningInstructions }}</div>
        </div>
      </template>
      <!-- 已开奖 且未中奖-->
      <template v-if="lotteryInfo.status === SESSION_STATUS.end && !winInfo.isWin">
        <img
          class="lottery-message__lost"
          src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKAAAACgCAMAAAC8EZcfAAAAmVBMVEUAAADz8//Oz9jX193T097Oz9jNztjOz9jR09vOz9jOz9jOz9jOz9jPz9jOz9jOz9jOz9jS1Nve3uPOz9jOz9jOz9jR0tvW1uHP0NnOz9jOz9jOz9jP0NnOz9jOz9fOz9jPz9jP0NnOz9jQ0drOz9jOz9jOz9nP0NrQ0drOz9jP0NnP0NnP0NrO0NjP0drOz9jPz9jOz9jNztex4xKXAAAAMnRSTlMABPoOFoj36x/B9LyPgcaidhsI8MzfJBJM55uWXq7u03tYtyrZqG4+N2RSR0NoMOKfs3vqYYoAAAiDSURBVHjazNjZlqowEAXQk4AyOCOD86xt2475/4+7a91eJqRVQhCB/dj9IJZVpxKQh2g/qXWmjfY8mFFqBfP2anptLfcGyud9LTrtGXvBckbdPUFZyNeiUWdK/VUpD2l3Gy5LzV2dIhTImDSYLnpbeigEGWzrLBO3MyD4NLNmsTcEu8+W0W7W2ZtmLROfEl5p0g843PjObbu9Of5mmDRA9XGIT7C3r3LE7ywOZw8S77xcdPz+i4EZ5V9Fr/X0x71cJzYS2JPO5emX2hHk6hCwB9b2O0QK4Wk7Yw/mR+Rn/Rh7dKoTGeQwfWzfqY2c7Cj7o62/GKKd/zBW3/kk34rJaNYpXI/o3yJGeNvAYhK32UNmvb85evnCe7wxk/Rr5rubqM8kLYI39OS+oU0Db4uaVO7nHjI7yxnmrJGLc5vFBevM7edKsTdBbr6lxp5lbMQdixsbyFE0klpniQyaUvl+kLOBtF26bz6f00PubKkTm9BUYzE1gg8g8mfoPp/65815CSyyPt/GxseEARNOSK3LBN/EB5lzJixTV54JDQMfZTiMowOksnYZtyX4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XsjfDNbQqcUTccSx2iv1rb9PpphCaqF0LXgi2KpkRv5y4RAAUmu/u+q49yp96HzlCOKlehmtnXttff3+PvvDVaj0Rw+Ze5RbEkfB/BJqj/DFkaaCp9Glj8ojZ3A3AvDd1Ga2+/R/Gp2oChMt3dz6J1y1VwduajppCH8L+RyPm0rP+XE9Xb3EP6/II0d72BOj98T+m8+1LJUhQ78ARDB35zCR6TMAAAAAElFTkSuQmCC"
          alt=""
        />
        <div class="lottery-message__name">很遗憾，您未中奖，谢谢参与</div>
        <!-- 中奖名单开关打开时显示 -->
        <div v-if="lotteryInfo.showResult" class="lottery-message__win-sub">
          点击查看<span @click="openWinnersHandler">中奖名单</span>
        </div>
      </template>
    </template>
  </div>
</template>

<script>
import CONFIG from '@/config'
import Bus from '@/utils/Bus'
import { getLotteryInfos, getUserRecord } from '@/api/modules/lottery'
import { setLotteryAddress } from '@/api/modules/records'
import { SESSION_STATUS, LOTTERY_MESSAGE_PRIZE_TYPE, LOTTERY_EXCHANGE_TYPE } from '@/utils/constant'

export default {
  name: 'Message',
  data() {
    return {
      SESSION_STATUS,
      LOTTERY_EXCHANGE_TYPE,
      LOTTERY_MESSAGE_PRIZE_TYPE,
      isLoading: true,
      lotteryInfo: this.lotteryInfoTranslator(),
      winInfo: this.winInfoTranslator(),
      connection: null,
      timer: null
    }
  },
  computed: {
    isInIframe() {
      return process.client ? window.self !== window.top : false
    }
  },
  mounted() {
    this.connectionInit()
    // 初始化事件中心
    this.eventHubInit()
    this.loadData()
  },
  destroyed() {
    Bus.$off('LotteryInfoUpdate')
    Bus.$off('LotteryStateUpdate')
  },
  methods: {
    connectionInit() {
      if (process.client) {
        const { ClientConnection } = require('@easy-messenger/client-connection/dist/clientConnection.cjs.js')
        this.connection = new ClientConnection()
        let counter = 0
        this.timer = setInterval(() => {
          this.connection.init()
          counter++
          if (this.connection.connected || counter > 60) {
            clearInterval(this.timer)
            this.connectionListener()
          }
        }, 1000)
      }
    },
    connectionListener() {
      this.connection.on('onSaveLotteryAddress', addressInfo => {
        const params = {
          tempId: this.winInfo?.tempId || '',
          uin: this.$route?.query?.uin || '',
          address: `${addressInfo?.province || ''}-${addressInfo?.city || ''}-${addressInfo?.area || ''}-${
            addressInfo?.detail
          }`,
          contactPhone: addressInfo?.mobile || '',
          name: addressInfo?.name || ''
        }
        setLotteryAddress(params).then(res => {
          const { code, errorCode, errorMessage } = res
          if (code === 200 && errorCode === 0) {
            this.$toast({
              message: '保存成功，具体详情请前往个人中心查看',
              duration: 3000,
              onClose: () => {
                this.connection.emit('onClose', { type: 'lottery' })
              }
            })
          } else {
            this.$toast(errorMessage)
          }
        })
      })
    },
    loadData() {
      this.isLoading = true
      const params = {
        id: this.$route?.query?.id || '',
        playId: this.$route?.query?.sessionId || '',
        uin: this.$route?.query?.uin || ''
      }
      getLotteryInfos(params).then(res => {
        const { code, errorCode, errorMessage, data } = res
        this.isLoading = false
        if (code === 200 && errorCode === 0) {
          this.lotteryInfo = this.lotteryInfoTranslator(data)
          if (this.lotteryInfo.status === SESSION_STATUS.end) {
            this.loadWinInfo()
          }
        } else {
          this.$toast(errorMessage)
        }
      })
    },
    loadWinInfo() {
      getUserRecord({
        id: this.$route?.query?.id || '',
        uin: this.$route?.query?.uin || '',
        nowPlay: this.lotteryInfo?.nowPlay
      }).then(res => {
        const { code, errorCode, errorMessage, data } = res
        if (code === 200 && errorCode === 0) {
          // console.log('winInfo', this.winInfo)
          this.winInfo = this.winInfoTranslator(data)
        } else {
          this.$toast(errorMessage)
        }
      })
    },
    // 一键复制口令及发送
    onCopyHandler(words) {
      if (this.isInIframe) {
        this.connection.emit('onCopyHandler', words)
        return
      }
      this.$copyText(words).then(
        () => {
          this.$toast('复制成功')
        },
        e => {
          this.$toast('当前浏览器暂时不支持复制')
        }
      )
    },
    openRecordHandler() {
      // 触发打开抽奖记录
      this.connection.emit('openRecordHandler', this.lotteryInfo)
    },
    openAddressHandler() {
      // 触发打开编辑地址
      this.connection.emit('openAddressHandler', this.lotteryInfo)
    },
    openWalletHandler() {
      // 触发前往钱包
      this.connection.emit('openWalletHandler')
    },
    openWinnersHandler() {
      // 触发打开中奖名单
      this.connection.emit('openWinnersHandler', this.lotteryInfo)
    },
    formatImg(url) {
      const img = url || CONFIG.defBanner
      return `${img}${CONFIG.ossImageServe}`
    },
    eventHubInit() {
      // 数据更新
      Bus.$on('LotteryInfoUpdate', data => {
        const { id } = data
        const { id: currentId } = this.$route.query
        if (parseInt(id, 10) === parseInt(currentId, 10)) {
          this.loadData()
        }
      })
      Bus.$on('LotteryStateUpdate', data => {
        const { id } = data
        const { id: currentId } = this.$route.query
        if (parseInt(id, 10) === parseInt(currentId, 10)) {
          this.loadData()
        }
      })
    },
    lotteryInfoTranslator(data) {
      const prizeItem = data?.prizeConfigs?.[0]
      return {
        ...data,
        status: +data?.status || '',
        showResult: !!data?.showResult || false,
        prizeName: prizeItem?.name || '',
        prizeIcon: prizeItem?.icon || '',
        prizeSum: prizeItem?.sum || '',
        winningInstructions: data?.winningInstructions || ''
      }
    },
    winInfoTranslator(data) {
      return {
        ...data,
        isWin: !!data?.prizeId,
        address: data?.address || '',
        exchangeType: +data?.exchangeType || LOTTERY_EXCHANGE_TYPE.offline
      }
    }
  }
}
</script>

<style lang="less" scoped>
.lottery-message {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 36px;
  background-color: #fff;
  &__img {
    width: 70px;
    height: 70px;
    border-radius: 50%;
    border: 2px solid #dddddd;
    img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
    }
  }
  &__name {
    font-size: 14px;
    font-weight: 500;
    height: 18px;
    line-height: 18px;
    margin: 6px 0;
  }
  &__num {
    font-size: 12px;
    font-weight: 400;
    height: 16px;
    line-height: 16px;
    color: #ff2a2a;
  }
  &__rules {
    width: 100%;
    margin-top: 20px;
    max-height: 100px;
    overflow: hidden;
    overflow-y: auto;
    background-color: #f7f7f7;
    border-radius: 5px;
    padding: 10px;
    font-size: 12px;
    color: #666;
  }
  &__rules-title {
    color: #333;
  }
  &__rules-content {
    margin-top: 5px;
    line-height: 16px;
  }
  &__keywords {
    color: #0091ff;
    font-size: 12px;
    font-weight: 500;
    margin: 0 10px;
  }
  &__copy-wrap {
    margin-top: 10px;
    display: flex;
    justify-content: center;
  }
  &__copy {
    color: #fff;
    background: linear-gradient(to bottom, #3388f7 0%, #256bfd 100%);
    border-radius: 6px;
    height: 24px;
    display: flex;
    justify-content: center;
    align-items: center;
    line-height: 1;
    padding: 0 6px;
  }
  &__win-text {
    color: #000;
    font-size: 14px;
    height: 18px;
    line-height: 18px;
    margin: 6px 0;
    span {
      font-weight: 500;
      &:nth-child(2) {
        margin: 0 5px;
      }
      &:last-child {
        color: #ff2a2a;
      }
    }
  }
  &__win-sub {
    font-size: 12px;
    margin-top: 10px;
    span {
      margin: 0 5px;
      color: #0091ff;
      font-size: 12px;
      font-weight: 500;
    }
  }
  &__lost {
    display: block;
    width: 40px;
    height: 40px;
    margin-bottom: 5px;
  }
}
</style>
