<template>
  <div class="bg101010">
    <div v-for="item in list" :key="item.id" class="m15">
      <div style="display: flex;align-items: center;">
        <div class="wh60">
          <img class="wh56" :src="iconURL(item.giftBagFileKey)" alt="" />
        </div>
        <div class="ml12">
          <div class="txt1">{{ item.giftBagName.length > 8 ? item.giftBagName.slice(0, 8) + '...' : item.giftBagName }}</div>
          <div class="txt2">{{ item.giftBagDetailed }}</div>
        </div>
      </div>
      <div :class="item.availableStatus === 1 ? 'gift-btn disabled' : 'gift-btn'" @click="receive(item)">{{ ['领取', '已领完', '查看'][item.availableStatus] }}</div>
    </div>
    <img class="w80h67" src="~/assets/image/activity/welfare-community/return.png" alt="" @click="returnUp">
    <van-popup v-model="showVideoSuccess" position="top" style="background: transparent;color: #999;" :close-on-click-overlay="false">
      <div class="w290h215 dialog-view">
        <div class="txt3">恭喜您获得礼包</div>
        <van-icon name="cross" color="#999999" size="15" class="icon-close" @click="showVideoSuccess=false" />
        <div class="txt4">请在游戏中兑换<br />激活码为：{{ gameActivationCode | activationCodeMask }}。<span class="c3B86FF" @click="copyCode()">复制</span></div>
        <div class="buy-btn" @click="order('showVideoSuccess')">购买云机</div>
      </div>
    </van-popup>
    <van-popup v-model="showAd" position="top" style="background: transparent;color: #999;" :close-on-click-overlay="false" @close="closeShowAd">
      <div v-for="(item, index) in adlist" :key="item.id" class="m114">
        <div v-if="index === 0" class="fwc">
          <div v-if="time" class="countdown">{{ time }}s后关闭广告</div>
          <video ref="videoPlayer" class="w290h330" :src="item.adVideoBase.videoUrl" x5-video-orientation="landscape" x5-video-player-type="h5" :x5-video-player-fullscreen="false" :controls="false" :webkit-playsinline="true" :playsinline="true" :autoplay="true" play-btn-position="center" :show-fullscreen-btn="false" :muted="true" @ended="ended" />
          <van-icon name="close" color="#999999" size="34" style="margin:15px auto 0;" @click="closeAd" />
        </div>
      </div>
    </van-popup>
    <van-popup v-model="showBuy" style="background: transparent;color: #999;" position="top" :close-on-click-overlay="false">
      <div class="w290h276 dialog-view">
        <div class="txt3">平台内下1单，立得惊喜礼包</div>
        <van-icon name="cross" color="#999999" size="15" class="icon-close" @click="showBuy=false" />
        <img class="w100h107" src="~/assets/image/activity/welfare-community/gift.png" alt="">
        <div class="buy-btn" style="margin:15px auto 0;" @click="order('showBuy')">下单得惊喜礼包</div>
      </div>
    </van-popup>
    <van-popup v-model="showBuySuccess" style="background: transparent;color: #999;" position="top" :close-on-click-overlay="false">
      <div class="w290h233 dialog-view">
        <div class="txt3">恭喜您获得礼包</div>
        <van-icon name="cross" color="#999999" size="15" class="icon-close" @click="showBuySuccess         =         false" />
        <div class="txt4">请在游戏中兑换<br />激活码为：{{ gameActivationCode | activationCodeMask }}。<span class="c3B86FF" @click="copyCode()">复制</span></div>
        <div class="fsc mt20">
          <div class="fcc">
            <img class="wh40" src="~/assets/image/activity/welfare-community/icon_iphone@2x.png" alt="" />
            <span class="txt5">进入云机</span>
          </div>
          <img class="w12h10 ml10 mt15" src="~/assets/image/activity/welfare-community/arrow@2x.png" alt="">
          <div class="fcc">
            <img class="wh40" src="~/assets/image/activity/welfare-community/icon_yingyongshichang@2x.png" alt="">
            <span class="txt5">打开应用市场</span>
          </div>
          <img class="w12h10 mt15" src="~/assets/image/activity/welfare-community/arrow@2x.png" alt="">
          <div class="fcc">
            <img class="wh40" src="~/assets/image/activity/welfare-community/icon_xiazai@2x.png" alt="">
            <span class="txt5">下载游戏</span>
          </div>
        </div>
      </div>
    </van-popup>
    <van-popup v-model="showLogin" style="background: transparent;color: #999;" position="top" :close-on-click-overlay="false" @click-close-icon="returnUp">
      <div class="w580h582">
        <img class="w412h238" src="~/assets/image/activity/welfare-community/tip.png" />
        <van-icon name="cross" color="#999999" size="15" class="icon-close" @click="returnUp" />
        <div class="txt6">领取礼包，请先绑定手机号</div>
        <img class="buy-btn-2" src="~/assets/image/activity/welfare-community/btn.png" @click="login" />
      </div>
    </van-popup>
  </div>
</template>

<script>
import { Toast } from 'vant';
import { fileKeyToUrl } from '@/plugins/file-center.js';

export default {
  auth: false,
  data() {
    return {
      showVideoSuccess: false,
      showAd: false,
      showBuy: false,
      showBuySuccess: false,
      showLogin: false,
      list: [],
      id: '',
      token: '',
      giftBagId: '',
      gameActivationCode: '',
      adlist: [],
      time: 30,
      timer: null
    }
  },
  head: {
    title: '福利社区',
  },
  filters: {
    activationCodeMask(value) {
      // 微信环境不支持零宽断言
      // return value.replace(/(?<=^.{4})(.*)(?=.{4}$)/, '***');

      return value.replace(/(.{4})(.*)(.{4}$)/, '$1***$3');
    },
  },
  computed: {
    iconURL() {
      return (key) => {
        return fileKeyToUrl(key)
      }
    }
  },
  created() {
    this.token = this.$route.query.token;
    this.id = this.$route.query.id;
    this.user = this.$route.query.user;
    this.gameName = this.$route.query.gameName;
    this.getAppGameGiftActivityDetailsList();
  },
  mounted() {
    document.addEventListener('visibilitychange', this.handleVisiable)
  },
  destroyed() {
    document.removeEventListener('visibilitychange', this.handleVisiable)
  },
  methods: {
    handleVisiable(e) {
      if (e.target.visibilityState === 'visible') {
        this.getAppGameGiftActivityDetailsList();
      }
    },
    closeShowAd() {
      this.showAd = false;
      clearInterval(this.timer);
    },
    closeAd() {
      this.showAd = false;
      clearInterval(this.timer);
      if (this.time === 0) {
        this.videoSuccess()
      }
    },
    async copyCode() {
      await this.$native.clipboard.writeText(this.gameActivationCode);
      this.$toast.success('复制成功');
    },
    order(key) {
      if (key === 'showBuy') {
        this.showBuy = false
      }
      if (key === 'showVideoSuccess') {
        this.showVideoSuccess = false
      }
      if (this.$userAgent.isSzx && this.$userAgent.isIos) {
        window.webkit.messageHandlers.order.postMessage({});
      }
      if (this.$userAgent.isSzx && this.$userAgent.isAndroid) {
        window.native.startPurchase();
      }
    },
    login() {
      this.showLogin = false
      if (this.$userAgent.isSzx && this.$userAgent.isIos) {
        window.webkit.messageHandlers.showLogin.postMessage({});
      }
      if (this.$userAgent.isSzx && this.$userAgent.isAndroid) {
        window.native.startBindPhone();
      }
    },
    ended() {
      this.showAd = false;
      clearInterval(this.timer);
      this.videoSuccess();
    },
    returnUp() {
      this.$router.push({ path: '/welfare-community', query: { token: this.$route.query.token, user: this.user } })
    },
    async receive(item) {
      if (item.availableStatus === 2) {
        this.gameActivationCode = item.gameActivationCode
        if (item.buy === 1) {
          this.showBuySuccess = true;
        }
        if (item.buy === 0) {
          this.showVideoSuccess = true;
        }
        return
      }
      if (item.availableStatus === 1) {
        return
      }
      this.giftBagId = item.id;
      if (this.$route.query.user === '2') {
        if (item.taskType === 2) {
          this.buySuccess(item);
        }
        if (item.taskType === 1) {
          const res = await this.$axios.$post('/public/v5/advertising/getAdInfoByAdPlace', { id: 1, adPlace: 24, os: this.$userAgent.isAndroid ? 1 : 2 }, { headers: { Authorization: this.token } });
          this.adlist = res.data
          if (!this.adlist.length) {
            return
          }
          this.adlist = this.adlist.length > 1 ? this.randomSort(this.adlist) : this.adlist;
          this.showAd = true
          setTimeout(() => {
            this.time = this.$refs.videoPlayer[0].duration > 30 ? 30 : parseInt(this.$refs.videoPlayer[0].duration);
            this.timer = setInterval(
              () => --this.time <= 0 && clearInterval(this.timer),
              1000);
          }, 800)
        }
      } else {
        if (this.$userAgent.isSzx && this.$userAgent.isAndroid) {
          this.showLogin = true
        }
        if (this.$userAgent.isSzx && this.$userAgent.isIos) {
          window.webkit.messageHandlers.showLogin.postMessage({});
        }
      }
    },
    randomSort(array) {
      const length = array.length;
      if (!Array.isArray(array) || length <= 1) return;
      for (let index = 0; index < length - 1; index++) {
        const randomIndex = Math.floor(Math.random() * (length - index)) + index;
        [array[index], array[randomIndex]] = [array[randomIndex], array[index]];
      }
      return array;
    },
    async getAppGameGiftActivityDetailsList() {
      try {
        const res = await this.$axios.$get('/activity/game/giftActivity/getAppGameGiftActivityDetailsList?giftActivityId=' + this.id, { headers: { Authorization: this.token } });
        this.list = res.data;
      } catch (err) {
        Toast({
          message: err.message,
          duration: 3000
        });
      }
    },
    async buySuccess(item) {
      try {
        const res = await this.$axios.$get('/activity/game/giftActivity/receiveGameGift?giftBagId=' + item.id, { headers: { Authorization: this.token } });
        this.gameActivationCode = res.data.gameActivationCode;
        if (res.data.buy === 1) {
          this.showBuySuccess = true;
        }
        if (res.data.buy === 0) {
          this.showVideoSuccess = true;
        }
      } catch (err) {
        if (err.response.data.status === 8500) {
          this.showBuy = true;
        } else {
          Toast({
            message: err.message,
            duration: 3000
          });
        }
      }
    },
    async videoSuccess() {
      try {
        const res = await this.$axios.$get('/activity/game/giftActivity/receiveGameGift?giftBagId=' + this.giftBagId, { headers: { Authorization: this.token } });
        this.gameActivationCode = res.data.gameActivationCode;
        this.getAppGameGiftActivityDetailsList();
        if (res.data.buy === 1) {
          this.showBuySuccess = true;
        }
        if (res.data.buy === 0) {
          this.showVideoSuccess = true;
        }
      } catch (err) {
        Toast({
          message: err.message,
          duration: 3000
        });
      }
    }
  }
}
</script>

<style scoped>
.w80h67 {
  width: 80px;
  height: 67px;
  position: fixed;
  left: 0;
  bottom: 70px;
}

.buy-btn-2 {
  width: 207px;
  height: 40px;
  display: block;
  margin: 27px auto 0;
}
.w580h582 {
  width: 290px;
  height: 291px;
  background-color: #ffffff;
  border-radius: 8px;
  overflow: hidden;
  margin: 0 auto;
  position: relative;
}

.w412h238 {
  width: 206px;
  height: 119px;
  display: block;
  margin: 40px auto 17px;
}

.disabled {
  background: #2b3c5c !important;
  color: #999999 !important;
}

.txt6 {
  height: 22px;
  font-size: 16px;
  font-weight: 500;
  color: #363636;
  line-height: 22px;
  text-align: center;
}

.wh40 {
  width: 40px;
  height: 40px;
}

.mt20 {
  margin-top: 20px;
}

.fsc {
  display: flex;
  align-items: flex-start;
  justify-content: center;
}

.ml10 {
  margin-left: 10px;
}

.w12h10 {
  width: 12px;
  height: 10px;
}

.txt5 {
  font-size: 12px;
  color: #666666;
  margin-top: 3px;
}

.fcc {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-width: 72px;
}

.w100h107 {
  width: 100px;
  height: 107px;
  display: block;
  margin: 17px auto 0;
}

.w290h233 {
  width: 290px;
  height: 233px;
  margin: 0 auto;
}

.w290h276 {
  width: 290px;
  height: 276px;
  margin: 0 auto;
}

.dialog-view {
  background: linear-gradient(360deg, #ffffff 0%, #dfefff 100%);
  box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.5);
  border-radius: 8px;
  position: relative;
  overflow: hidden;
}

.countdown {
  width: 92px;
  height: 25px;
  background: rgba(6, 6, 6, 0.5);
  border-radius: 13px;
  position: absolute;
  top: 10px;
  right: 10px;
  font-size: 11px;
  text-align: center;
  line-height: 25px;
  color: #cccccc;
}

.mt15 {
  margin-top: 15px;
}

.fwc {
  display: flex;
  flex-direction: column;
  justify-content: center;
  position: relative;
}

.w290h330 {
  width: 290px;
  height: 330px;
  background: #000000;
}

.buy-btn {
  width: 207px;
  height: 40px;
  background: linear-gradient(90deg, #38aefc 0%, #3b7fff 100%);
  border-radius: 20px;
  line-height: 40px;
  text-align: center;
  font-weight: 500;
  color: #ffffff;
  font-size: 16px;
  margin: 20px auto 0;
}

.c3B86FF {
  color: #3b86ff;
}

.txt4 {
  width: 290px;
  font-size: 14px;
  color: #666666;
  line-height: 20px;
  margin-top: 12px;
  text-align: center;
}

.txt3 {
  width: 290px;
  font-size: 18px;
  font-weight: 500;
  color: #363636;
  line-height: 25px;
  text-align: center;
  margin-top: 47px;
}

.w290h215 {
  width: 290px;
  height: 215px;
  margin: 0 auto;
  position: relative;
}

.m114 {
  margin: 0 auto;
  width: 290px;
}

.icon-close {
  position: absolute;
  top: 20px;
  right: 20px;
}

.gift-btn {
  width: 78px;
  height: 28px;
  background: #3b7fff;
  border-radius: 4px;
  font-size: 14px;
  color: #ffffff;
  line-height: 28px;
  text-align: center;
  justify-self: end;
}

.ml12 {
  margin-left: 12px;
}

.txt2 {
  font-size: 14px;
  color: #cfd1d4;
  line-height: 20px;
  margin-top: 5px;
}

.txt1 {
  font-size: 18px;
  font-weight: 500;
  color: #cfd1d4;
  line-height: 25px;
}

.wh60 {
  width: 60px;
  height: 60px;
  border: 1px solid #eaeaea;
  border-radius: 50%;
  padding: 2px;
  box-sizing: border-box;
}

.wh56 {
  width: 56px;
  height: 56px;
  border-radius: 50%;
}

.bg101010 {
  background: #101010;
  min-height: 100vh;
  overflow: hidden;
}

.m15 {
  margin: 15px;
  height: 83px;
  background: #1e2022;
  box-shadow: 0px 3px 7px 0px #1e2022;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 15px 12px;
  box-sizing: border-box;
}
</style>