<template>
  <div>
    <el-dialog class="Explore-dialog" :visible.sync="helpDialogVisible" :modal="false" :before-close="helpDialog">
      <div class="top">
        <div class="top-title">Boosting Chest</div>
        <div class="top-close" @click="helpDialog">
          <img src="./../../assets/common/CloseButton.png" alt="">
        </div>
      </div>
      <div class="content">
        <div class="content-left">
          <div class="user-info">
            <div class="user-info-img">
              <img v-if="!boxData.avatar" src="@/assets/common/head_default.jpg" alt="" >
              <UserImg v-else :imgSrc="boxData.avatar" />
            </div>
            <div class="user-info-name" v-if="boxData.nickname">{{ boxData.nickname }}: <span>Thank you for your support! </span></div>
            <div class="user-info-name" v-else>UserName: <span>Thank you for your support! </span></div>
          </div>
          <div class="con">
            <img v-if="!boxData.level" src="./../../assets/box/Unlock .png" alt="">
            <img v-else :src="require(`./../../assets/box/box0${boxData.level}.png`)" alt="">
          </div>
          <div class="btn" v-if="!token" @click="linkWallet">Wallet Connect</div>
          <div class="btn" v-else>
            <div class="btn" @click="helpBtn">Boosting</div>
          </div>
        </div>
        <div class="content-right">
          <div class="content-right-title">
            Boosting Records
          </div>
          <div class="line"></div>
          <div class="box-boosting-no" v-if="helpLogList == undefined || helpLogList.length <= 0">
            <div>
              <p>None</p>
            </div>
          </div>
          <div class="box-boosting" v-else>
            <div>
              <li v-for="(item, index) in helpLogList" :key="index">
                <div class="left">
                  <div class="user-img" v-if="index == 0">
                    <div class="one-bg">
                      <img src="./../../assets/common/Picture frame.png" alt="">
                    </div>
                    <UserImg class="one-img" :imgSrc="item.avatar" />
                  </div>
                  <div class="user-img" v-else>
                    <UserImg :imgSrc="item.avatar" />
                  </div>
                  <div class="user-name">{{ item.nickname }}</div>
                </div>
                <div class="right">
                  <div class="records">+{{ item.score }}</div>
                  <div class="icon">
                    <img src="./../../assets/common/Icon_Points.png" alt="">
                  </div>
                </div>
              </li>
            </div>
          </div>
        </div>
      </div>
      
    </el-dialog>
    <Loading :Loading="isLoading" />
  </div>
</template>

<script>
import UserImg from '@/components/userImg.vue'
import Loading from '@/components/loading.vue'
import { getToken } from './../../utils/cookies.js'
import { sendToChain } from './../../utils/chainapi.js'
import {
  checkReCaptcha,
  apiUploadInviteCode,
  apiEnhanceBox
} from "./../../utils/webapi.js";

export default {
  components: {
    Loading,
    UserImg
  },
  props: {
    helpDialogVisible: Boolean,
    level1: Array,
    level2: Array,
    level3: Array,
    level4: Array,
    dialogTitle: String,
  },
  data() {
    return {
      boxData: {},
      token: null,
      helpLogList: [],
      boxCode: '',
      boxState: {},
      isNewUser: 0,
      awardData: {},
      isLoading: false,
    }
  },
  mounted() {
    this.token = getToken()
    if(this.$route.params.code) {
      if(this.$route.params.code.split("=")[0] == 'box') {
        this.boxCode = this.$route.params.code.split("=")[1];
        this.getBoxData()
        if(this.token) {
          this.getHelpBoxLog()
          this.initBoxState(this.boxCode)
        }
      }
    }
  },
  methods: {
    // 宝箱信息接口
    async getBoxData() {
      let res = await this.$axios.post(process.env.VUE_APP_API_URL+'/api/chest/enhance/state', {code: this.boxCode},{})
      if(res.data.errcode == 0) {
        this.boxData = res.data.data
      } else if(res.data.errcode == 14) {
        this.$showErr(res)
      }
    },

    // 获取帮助的宝箱助力记录
    async getHelpBoxLog() {
      if (this.$route.params.code != undefined) {
        let rtoken = await checkReCaptcha("chest_share");
        let res = await this.$axios.post(
          process.env.VUE_APP_API_URL+"/api/chest/enhance/list",
          { chestid: this.boxCode, rtoken: rtoken },
          {
            headers: { Authorization: `Bearer ${this.token}` }
          }
        );
        if (res.data.errcode == 0) {
          this.helpLogList = res.data.data;
        }
      }
    },

    // 宝箱助力
    async helpBtn() {
      let address = localStorage.getItem("myAddress")
      // 3、是否已经助力此宝箱
      if(this.boxState.enhanced == 0) {
        // 1、助力次数是否用完
        if(this.boxState.userCurrent < this.boxState.userMax) {
        // 2、宝箱助力次数是否上限
        if(this.boxState.chestCurrent < this.boxState.chestMax) {
            // 4、开始助力
            await this.sendEnhanceReq(this.boxCode)
        } else {
          this.$showErr('Boost limit reached.')
        }
      } else {
        this.$showErr('Not enough boosts available.')
      }
      } else {
        this.$showErr('Already boosted.')
      }
      
      
      
    },

    // 发送宝箱助力上链请求并领取奖励
    async sendEnhanceReq(boxCode) {
      let address = this.$store.state.user.address;
      if (!this.$store.state.wallet.connected || !address) {
        this.walletDialogVisible = true
        return
      }
      this.isLoading = true;
      let storeageKey
      try {
        storeageKey = await sendToChain('chest_enhance', address, boxCode)
      } catch (err) {
        this.isLoading = false;
        this.$showErr(err)
        return 
      }
      let serTimeId = setInterval(async () => {
        try {
          let { errcode, errmsg, data } = await apiEnhanceBox(boxCode)
          if (!errcode) {
            // alert(`助力成功, 获得积分: ${data.score}`)
            this.isLoading = false;
            if(this.isNewUser == 0) {
              // 8、关闭助力弹窗
              this.awardData = {...data, isNewUser: this.isNewUser}
              this.$emit('awardDialog', this.awardData)
              this.$emit('handleClose')
            } else {
              // 8、关闭助力弹窗
              this.awardData = {...data, isNewUser: this.isNewUser}
              this.$emit('awardDialog', this.awardData)
              this.$emit('handleClose')
            }
            await this.$store.dispatch('user/fetchUserState')
            localStorage.removeItem(storeageKey)
            clearInterval(serTimeId)
          } else if (errcode !== 14) {
            // 状态不是等待链上确认的, 都提示错误
            this.isLoading = false;
            this.$emit('handleClose')
            this.$message.error(errmsg)
            clearInterval(serTimeId)
          }
        } catch (err) {
          this.isLoading = false;
          this.$showErr(`claim task reward error: ${err}`)
        }
      }, 3000)
    },

    // 助力状态查询
    async initBoxState(boxCode) {
      let res = await this.$axios.post(process.env.VUE_APP_API_URL+'/api/chest/enhance/state',{code: boxCode, },{headers: { Authorization: `Bearer ${this.token}` }})
      this.boxState = res.data.data
    },

    // 关闭弹窗
    helpDialog() {
      this.$emit('handleClose')
    },

    // 打开登录弹窗
    linkWallet() {
      this.$emit('onWalletLogin')
    },
  },
}
</script>

<style lang="scss" scoped>
div {
  ::v-deep .el-dialog {
    border: 1px solid #924df2;
    // box-shadow: 0px 0px 20px #924df2;
    background: #1a1821;
    border-radius: 80px;
    padding: 0px 50px;
    .el-dialog__header {
      padding: 0;
    }
    .el-dialog__body {
      position: relative;
      color: #fff;
      .top {
        display: flex;
        
        .top-title {
          color: #fff;
          font-size: 28px;
          font-family: "Anton-Regular";
        }
        .top-close {
          position: absolute;
          top: -8%;
          right: -9%;
          width: 100px;
          height: 100px;
          cursor: pointer;
          img {
            width: 100%;
            height: 100%;
          }
        }
      }
      .content {
        display: flex;
        justify-content: space-between;
        margin-top: 20px;
        .content-left {
          width: 400px;
          height: 400px;
          background: url('./../../assets/box/Bg_chest.png') no-repeat;
          background-size: 100% 100%;
          position: relative;
          .user-info {
              display: flex;
              align-items: center;
              position: absolute;
              top: -10px;
              left: 0;
              .user-info-img {
                width: 40px;
                height: 40px;
                overflow: hidden;
                margin-right: 20px;
                background: url('@/assets/common/Picture frame .png') no-repeat;
                background-size: 100% 100%;
                padding: 3px;
                display: flex;
                align-items: center;
                justify-content: center;
                img {
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  width: 100%;
                  height: 100%;
                  border-radius: 50%;
                }
              }
              .user-info-name {
                font-size: 10px;
                span {
                  display: inline-block;
                  color: #90FF00;
                  margin-left: 20px;
                }
              }
          }
          .con {
              width: 240px;
              height: 180px;
              position: absolute;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
              img {
                width: 100%;
                height: 100%;
              }
          }
          .btn {
              width: 200px;
              height: 50px;
              line-height: 50px;
              position: absolute;
              bottom: 0;
              left: 50%;
              transform: translateX(-50%);
              color: #000;
              background: url('./../../assets/home/explore map button.png') no-repeat;
              background-size: 100% 100%;
              cursor: pointer;
          }
        }
        .content-right {
          width: 360px;
          background: url('./../../assets/box/Bg(1).png') no-repeat;
          background-size: 100% 100%;
          padding: 10px 20px;
          box-sizing: border-box;
          .content-right-title {
            font-size: 28px;
            font-weight: 700;
            font-family: "Anton-Regular";
            text-align: left;
          }
          .line {
            width: 100%;
            height: 2px;
            background: #3c2363;
          }
          .box-boosting {
            height: 400px;
            overflow-y: scroll;
            margin-top: 20px;
            li {
              display: flex;
              align-items: center;
              justify-content: space-between;
              padding: 0 20px;
              margin-top: 20px;
              .left {
                display: flex;
                align-items: center;
                .user-img {
                  
                }
                .user-name {
                  font-size: 16px;
                  margin-left: 20px;
                }
              }
              .right {
                display: flex;
                align-items: center;
                .records {
                  font-size: 12px;
                  color: #9950fd;
                }
                .icon {
                  width: 10px;
                  height: 12px;
                  margin-left: 5px;
                  display: flex;
                  align-items: center;
                  img {
                    width: 100%;
                    height: 100%;
                  }
                } 
              }
              &:nth-child(1) {
                .left {
                  .user-img {
                    width: 40px;
                    height: 40px;
                    position: relative;
                    .one-bg {
                      width: 60px;
                      height: 60px;
                      position: absolute;
                      top: 50%;
                      left: 50%;
                      transform: translate(-50%, -50%);
                      z-index: 9;
                      img {
                        width: 100%;
                        height: 100%;
                      }
                    }
                    .one-img {
                      width: 40px;
                      height: 40px;
                      position: absolute;
                      top: 50%;
                      left: 50%;
                      transform: translate(-50%, -50%);
                      border-radius: 50%;
                    } 
                  }
                }
              }
            }
          }
          .box-boosting::-webkit-scrollbar {
            width: 5px;
          }
          .box-boosting::-webkit-scrollbar-track{
            background: #171220;
            border-radius:2px;
          }
          .box-boosting::-webkit-scrollbar-corner{
            display: block;
          }
          .box-boosting::-webkit-scrollbar-thumb{
            height: 15px;
            background: #9950fd;
            border-radius:10px;
          }
          .box-boosting-no {
            height: 400px;
            margin-top: 20px;
            position: relative;
            div {
              position: absolute;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
              width: 200px;
              height: 140px;
              background: url('./../../assets/box/none01.png') no-repeat;
              background-size: 100% 100%;
              p {
                position: absolute;
                bottom: 8%;
                left: 50%;
                transform: translate(-50%, -50%);
                font-size: 14px;
              }
            }
          }
          
        }
      }
    }
  }
}
</style>