<template>
  <v-container class="invite-user" fluid>
    <div class="rule" @click="show = true">规则</div>
    <div class="box1">
      <div class="award-container">
        <div class="card" v-for="(item,index) in levelNameList" :key="index">
          <div class="card-name">{{ item.rewardGiveaways  }}</div>
          <div class="card-desc">{{ item.satisfyConditions  }}</div>
        </div>
      </div>
      <v-btn v-if="received" class="share-button" :style="{display: levelNameList.length ? 'block': 'none'}" rounded @click="share()">
        云机免费领取
      </v-btn>
      <v-btn v-else class="share-button" :style="{display: levelNameList.length ? 'block': 'none'}" rounded @click="share()">
        赶紧分享你的好友，购买云机
      </v-btn>
    </div>
    <div class="intr-container">
      <img src="~/assets/image/activity/invite-user/cybz-content-4@2x.png" alt="">
    </div>
    <div class="box3">
      <div v-if="myActivationCode.length" class="code-table">
        <div class="table-body">
          <div v-for="(item, index) in myActivationCode" :key="index" class="box-container">
            <div class="index-container">{{ index+1 }}</div>
            <div class="date-container">{{ item.createTime | formatDate('MM月DD日 HH:mm') }}</div>
            <div class="code-container">{{ item.activationCode | activationCodeMask }}</div>
            <div class="operation-container" v-if="!item.activationUse"><v-btn text small color="#FF9616" class="copy-btn" @click="copyCode(item)">复制</v-btn></div>
            <div class="operation-container" v-else><v-btn text small color="#999999" class="copy-btn">已使用</v-btn></div>
          </div>
          <div v-if="myActivationCode.length" v-intersect.quiet="codeLoadMoreIntersect" class="flex item-center justify-center">
            <v-btn :loading="codeIsLoading" text small>
              <template v-if="codeIsLoading">加载中</template>
              <template v-else-if="codeHasMore">加载更多</template>
              <template v-else>没有更多</template>
            </v-btn>
          </div>
        </div>
      </div>
      <div v-else class="fwc">
        <img src="~/assets/image/activity/invite-user/noReward@2x.png" alt="">
      </div>
    </div>
    <div class="income">
      <div class="first-line">
        <div class="accumulated-quantity">{{ accumulatedQuantity }}</div>
        <div class="quantity-today">{{ quantityObtainedToday }}</div>
      </div>
      <div class="second-line">
        <div class="thirty">{{ thirty }}</div>
        <div class="ninety">{{ ninety }}</div>
        <div class="oneHundredAndEighty">{{ oneHundredAndEighty }}</div>
        <div class="threeHundredAndSixtyFive">{{ threeHundredAndSixtyFive }}</div>
      </div>
    </div>
    <van-popup v-model="show" style="background: transparent;padding-bottom: 60px;width: 100%;">
      <activity-invite-user-box class="box4">
        <template #title>活动规则</template>
        <div class="text-sm" v-html="activityRules"></div>
      </activity-invite-user-box>
      <van-icon name="close" class="close1" color="#939393" @click="show = false;" />
    </van-popup>
  </v-container>
</template>

<script>

import { Toast, Dialog } from 'vant';
import NativeShare from 'nativeshare';
import { fileKeyToUrl } from '@/plugins/file-center.js';


export default {
  auth: false,
  name: 'Fission',
  filters: {
    activationCodeMask(value) {
      return value.replace(/(.{2})(.*)(.{2}$)/, '$1**$3');
    },
    timeStamp(StatusMinute) {
      const day = parseInt(StatusMinute / 60 / 60 / 24);
      const hour = parseInt((StatusMinute / 60 / 60) % 24);
      const min = parseInt(StatusMinute / 60 % 60);
      StatusMinute = '';
      if (day > 0) {
        StatusMinute = day + '天';
      }
      if (hour > 0) {
        StatusMinute += hour + '小时';
      }
      if (min > 0) {
        StatusMinute += parseFloat(min) + '分钟';
      }
      return StatusMinute;
    }
  },
  data() {
    return {
      show: false,
      current: 0,
      data: {
        todayIncomeStarCoin: 0,
        totalIncomeStarCoin: 0,
        todayBuyOrderCount: 0,
        totalBuyOrderCount: 0,
        todayBuyOrderSuccessCount: 0,
        totalBuyOrderSuccessCount: 0,
        withdrawStarCoinNum: 0,
        inviteUserName: null,
        activityId: null,
        status: 0,
        type: 2
      },
      level: {
        currentLevelName: '',
        activityId: '',
        levelAwardDetails: [],
        shareFriendCount: 0,
        boostValue: 0
      },
      activityRules: '',
      myActivationCode: [],
      levelAwardRankings: [],
      myCodeFrom: {
        activityId: null,
        pageNum: 1,
        pageSize: 8,
      },
      codeTotal: -1,
      codeIsLoading: false,
      client: 1,
      token: '',
      width: 0,
      boostValue: 0,
      currentEndTime: 0,
      currentRanking: 0,
      preRanking: 0,
      userType: 1,
      received: 0,
      shareInfo: {
        title: '双子星云手机',
        desc: `免费领取一台全能云手机！`,
        link: '',
        imgUrl: ''
      },
      showShare: false,
      accumulatedQuantity: 0,
      quantityObtainedToday: 0,
      thirty: 0,
      ninety: 0,
      oneHundredAndEighty: 0,
      threeHundredAndSixtyFive: 0,
      levelNameList: []
    };
  },
  async fetch() {
    // 页面初始化后触发
    try {
      this.token = this.$route.query.token;
      // await this.getActiveInfo();
      // await this.shareCanReceiveCloudPhone();
      await Promise.all([
        this.getActivityRules(),
        // this.type === 2 && this.getMyActivationCode(this.myCodeFrom),
        // this.myCodeFrom.activityId && this.getRanking({ activityId: this.myCodeFrom.activityId })
      ]);
    } catch (error) {
      Toast({
        message: error.message,
        duration: 4000
      });
    }
    if (this.$userAgent.isSzx && this.$userAgent.isAndroid) {
      this.client = 1;
    } else if (this.$userAgent.isSzx && this.$userAgent.isIos) {
      this.client = 2;
    } else if (this.$userAgent.isMiniProgram) {
      this.client = 5;
    } else {
      this.client = 7;
    }
  },
  head: {
    title: '邀请好友'
  },
  computed: {
    codeHasMore() {
      return (
        this.codeTotal < 0 ||
        this.myCodeFrom.pageNum * this.myCodeFrom.pageSize < this.codeTotal
      );
    },
    type() {
      return 2;
    },
  },
  mounted() {
    this.makePoint('activity_Share_PV')
    this.makePoint('activity_Share_UV')
    this.addUserVisit(12);
    this.receiveLevelAward()
  },
  methods: {
    // async shareCanReceiveCloudPhone() {
    //   try {
    //     const res = await this.$axios.$get('/resources/register/send/cloud/phone/shareCanReceiveCloudPhone', {}, { headers: { Authorization: this.token } });
    //     this.received = res.data.received
    //     this.shareInfo.title = res.data.title
    //     this.shareInfo.desc = res.data.content
    //     this.shareInfo.link = res.data.url
    //     this.shareInfo.imgUrl = fileKeyToUrl(res.data.imgUrl)
    //     this.$native.setShareInfo(this.shareInfo);
    //   } catch (err) {
    //     Toast({
    //       message: err.message,
    //       position: 'top'
    //     });
    //   }
    // },
    async shareReceiveCloudPhone() {
      try {
        const res = await this.$axios.$post('/resources/register/send/cloud/phone/shareReceiveCloudPhone', {}, { headers: { Authorization: this.token } });
        Dialog.alert({
          message: res.msg,
        }).then(() => {
          this.showShare = false
        });
        this.addUserVisit(7);
      } catch (err) {
        Toast({
          message: err.message,
          position: 'top'
        });
      }
    },
    receiveLevelAward() {
      this.$axios.$get('/activity/v4/fissionDistribution/getDetails', { headers: { Authorization: this.token } }).then(res => {
        console.log(res)
        this.accumulatedQuantity = res.data.accumulatedQuantity
        this.quantityObtainedToday = res.data.quantityObtainedToday
        this.thirty = res.data.thirty
        this.ninety = res.data.ninety
        this.oneHundredAndEighty = res.data.oneHundredAndEighty
        this.threeHundredAndSixtyFive = res.data.threeHundredAndSixtyFive
        this.shareInfo.title = res.data.title
        this.shareInfo.desc = res.data.content
        this.shareInfo.link = res.data.url
        this.shareInfo.imgUrl = fileKeyToUrl(res.data.imgUrl)
        this.$native.setShareInfo(this.shareInfo);
        this.myActivationCode = res.data.activationCodeList
        this.levelNameList = res.data.levelNameList
        // this.returnContent.forEach((item,index) => {
        //   item.content = res.data.levelNameList[index]
        // })
      }).catch(err => {
        console.log(err)
        Toast({
          message: err.message,
          position: 'top'
        });
      })
    },
    async myLevelAward() {
      const res = await this.$axios.$get(`/activity/v1/level/award/myLevelAward?activityId=${this.myCodeFrom.activityId}`, { headers: { Authorization: this.token } });
      this.level = res.data;
      if (this.level.levelAwardDetails) {
        this.width = 0;
        const levelLength = 280 / (this.level.levelAwardDetails.length - 1)
        this.level.levelAwardDetails.forEach((item, index) => {
          if (item.status > 0) {
            if (index > 0) {
              this.width += levelLength
            }
            if (index === 0 || index === this.level.levelAwardDetails.length - 1) {
              this.width += 14
            }
          }
        })
      }
    },
    // async getActiveInfo() {
    //   const res = await this.$axios.$get('/activity/v1/inviteUser/orderRelation/starCoinOverview', { headers: { Authorization: this.token } });
    //   this.data = res.data;
    //   this.myCodeFrom.activityId = res.data.activityId;
    //   if (this.myCodeFrom.activityId) {
    //     await this.myLevelAward();
    //   }
    // },
    // async getMyActivationCode(params) {
    //   try {
    //     this.codeIsLoading = true;
    //     const res = await this.$axios.$get('/activity/v1/inviteUser/orderRelation/myActivationCode', { params, headers: { Authorization: this.token } });
    //     this.codeTotal = res.data.total;

    //     this.myActivationCode.push(
    //       ...(res.data.list ?? [])
    //     );
    //     this.myCodeFrom = params;
    //   } finally {
    //     this.codeIsLoading = false;
    //   }
    // },
    // async getRanking(params) {
    //   try {
    //     this.codeIsLoading = true;
    //     const res = await this.$axios.$get('/activity/v1/level/award/ranking', { params, headers: { Authorization: this.token } });
    //     this.boostValue = res.data.boostValue
    //     this.currentEndTime = res.data.currentEndTime
    //     this.currentRanking = res.data.currentRanking
    //     this.preRanking = res.data.preRanking
    //     this.levelAwardRankings = res.data.levelAwardRankings;
    //     this.userType = res.data.userType;
    //   } finally {
    //     this.codeIsLoading = false;
    //   }
    // },
    share() {
      // if (this.data.status !== 1) {
      //   if (this.data.status === 0) {
      //     Toast({
      //       message: '当前活动已过期',
      //       position: 'top'
      //     });
      //     return
      //   }
      //   if (this.data.status === 2) {
      //     Toast({
      //       message: '当前活动未开启',
      //       position: 'top'
      //     });
      //     return
      //   }
      //   if (this.data.status === 3) {
      //     Toast({
      //       message: '当前活动已结束',
      //       position: 'top'
      //     });
      //     return
      //   }
      //   Toast({
      //     message: '未知活动状态',
      //     position: 'top'
      //   });
      //   return
      // }
      this.$tongji.trackEvent('活动', '分享', '', 0);
      if (this.received) {
        this.addUserVisit(13);
      }
      console.log('env',this.$userAgent.isSzx , this.$userAgent.isSzxBrowser)
      if (this.$userAgent.isSzx || this.$userAgent.isSzxBrowser) {
        // app环境
        this.$native.share(this.shareInfo);
        console.log(this.shareInfo,'xxxx');
        // this.makePoint('activity_Share_分享好友按钮');
      } else {
        // 浏览器环境
        const nativeShare = new NativeShare()
        nativeShare.setShareData({
          icon: this.shareInfo.imgUrl,
          link: this.shareInfo.link,
          title: this.shareInfo.content,
          desc: this.shareInfo.title,
          success: () => {
            this.shareReceiveCloudPhone()
          },
          fail: () => {
            Toast({
              message: '分享失败',
              position: 'center'
            })
          }
        })
        try {
          nativeShare.call('wechatTimeline')
        } catch (err) {
          Toast({
            message: '您的浏览器不支持分享功能，请下载app使用！',
            position: 'center',
            duration: 3000
          })
          setTimeout(() => {
            window.open('https://www.androidscloud.com/', '_self');
          }, 3000)
        }
      }
    },
    makePoint(positionButton) {
      this.$axios.$post('/public/v5/buriedPointRecord/reportRecords', [
        {
          client: this.client,
          eventCode: '28_分享活动',
          userName: this.$auth.user.username,
          positionButton,
          operationTime: this.getCurrentTime(),
          phoneNumber: this.$auth.user.phone,
          deviceId: ''
        },
      ]);
    },
    getCurrentTime() {
      const date = new Date(); // 当前时间
      const year = date.getFullYear() // 年
      const month = this.repair(date.getMonth() + 1); // 月
      const day = this.repair(date.getDate()); // 日
      const hour = this.repair(date.getHours()); // 时
      const minute = this.repair(date.getMinutes()); // 分
      const second = this.repair(date.getSeconds()); // 秒
      // 当前时间 
      const curTime = year + "-" + month + "-" + day +
        " " + hour + ":" + minute + ":" + second;
      return curTime;
    },
    repair(i) {
      if (i >= 0 && i <= 9) {
        return "0" + i;
      } else {
        return i;
      }
    },
    async getActivityRules() {
      const agreementCoding = {
        1: 'iuserrules01',
        2: 'iuserrules02',
        3: 'iuserrules03',
      }[this.type];
      if (agreementCoding) {
        const res = await this.$axios.$get(
          '/public/v4/agreement/content/getContentByType',
          {
            params: {
              agreementCoding,
              type: 1,
            },
          },
        );

        this.activityRules = res.data.content
          .replace(/[\d\D]*<body>([\d\D]+)<\/body>[\d\D]*/i, '$1')
          .replace(/<div class="phone-container">([\d\D]+)<\/div>/g, '$1');
      }
    },
    async copyCode(item) {
      await this.$native.clipboard.writeText(item.activationCode);
      Toast({
        message: '复制激活码，请在【我的-兑换中心】兑换'
      });
      this.makePoint('activity_Share_激活码复制')
    },
    codeLoadMoreIntersect(event) {
      if (event[0].isIntersecting && this.codeHasMore && !this.codeIsLoading) {
        this.getMyActivationCode({
          ...this.myCodeFrom,
          pageNum: this.myCodeFrom.pageNum + 1,
        });
      }
    },
    addUserVisit(accessType) {
      this.$axios.$post('/user/v5/operateApi/addUserVisit', {
        accessType,
        loginType: 1
      });
    }
  }
};
</script>

<style lang="scss" scoped>


.rule {
  width: 24px;
  height: 56px;
  line-height: 28px;
  background: rgba(0, 0, 0, 0.19);
  border-radius: 6px 0px 0px 6px;
  font-size: 15px;
  font-weight: 400;
  color: #FFFFFF;
  position: absolute;
  right: 0;
  top: 28px;
  text-align: center;
}

.close1 {
  font-size: 30px;
  text-align: center;
  display: block;
}

.fwc {
  text-align: center;

  img {
    width: 75px;
    height: 83px;
    margin-top: 120px;
  }
}

.invite-user {
  color: #333;
  background-size: 100% auto;
  overflow: hidden;
  padding: 0;
  padding-bottom: env(safe-area-inset-bottom, 30px);
  background-color: #F67350;
  background-image: url('~/assets/image/activity/invite-user/bg-7@2x.png');

}

.box1 {
  margin: 240px auto 0;
  width: 373px;
  height: 442px;
  background: url('~/assets/image/activity/invite-user/box3@2x.png');
  background-size: 100% 100%;
  overflow: hidden;
  .share-button {
    display: block;
    margin: auto;
    width: 302px !important;
    height: 62px !important;
    background-image: url('~/assets/image/activity/invite-user/share-button@2x.png');
    background-size: 100% 100%;
    margin-top: 24px;
    color: #dd1b0d;
    font-size: 18px;
    font-weight: bold;
  }
}

.intr-container{
  width: 100%;
  img{
    width: 100%;
  }
}
.box3 {
  width: 345px;
  height: 517px;
  margin: 25px auto 0;
  background: url('~/assets/image/activity/invite-user/box4@2x.png');
  background-size: 100% 100%;
  padding: 80px 4px 0;
  box-sizing: border-box;

}
.code-table {
  .table-body {
    max-height: 430px;
    overflow-y: auto;
  }


  tr {
    height: 40px;
    color: #8F8F8F;
  }

  td {
    height: 40px;
    color: #333;
  }

  .copy-btn {
    min-width: 0 !important;
    height: auto !important;
    padding: 0 !important;
  }
}

.box4::v-deep .box-main {
  padding-left: 10px;
  padding-right: 10px;
}

.box-container{
  display: flex;
  height: 48px;
  align-items: center;
  font-size: 12px;
  color: #333;
  text-align: center;
  .index-container{
    width: 50px;
  }
  .date-container{
    width: 120px;
  }
  .code-container{
    width: 90px;
  }
  .operation-container{
    width: 50px;
    margin-left: 25px;
  }
}
.award-container{
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  width: 272px;
  margin: 38px auto 0;
  .card{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 119px;
    height: 114px;
    margin-top: 26px;
    background-image: url('~/assets/image/activity/invite-user/card.png');
    background-size: 100% 100%;
  }
  .card-name{
    color: #F75921;
    font-size: 16px;
    line-height: 22px;
    font-weight: bold;
    margin-top: 30px;
  }
  .card-desc{
    margin-top: 4px;
    color: #F75921;
    font-size: 12px;
    line-height: 17px;
  }
}
.income{
  position: relative;
  width: 373px;
  height: 240px;
  margin-top: 20px;
  margin-bottom: 60px;
  background-image: url('~/assets/image/activity/invite-user/income-bg.png');
  background-size: contain;
  .accumulated-quantity{
    position: absolute;
    top: 83px;
    left: 35px;
    font-size: 30px;
    color: #FF4C59;
    font-weight: bold;
  }
  .quantity-today{
    position: absolute;
    top: 83px;
    left: 197px;
    font-size: 30px;
    color: #FF4C59;
    font-weight: bold;
  }
  .thirty{
    position: absolute;
    top: 172px;
    left: 35px;
    color: #333333;
    font-size: 18px;
    font-weight: bold;
  }
  .ninety{
    position: absolute;
    top: 172px;
    left: 116px;
    color: #333333;
    font-size: 18px;
    font-weight: bold;
  }
  .oneHundredAndEighty{
    position: absolute;
    top: 172px;
    left: 197px;
    color: #333333;
    font-size: 18px;
    font-weight: bold;
  }
  .threeHundredAndSixtyFive{
    position: absolute;
    top: 172px;
    left: 283px;
    color: #333333;
    font-size: 18px;
    font-weight: bold;
  }
}
</style>
