<template>
  <div class="login">
    <Header :descText="'Connect your Bitget Wallet and register'" />
    <h5>
      Register to win a share of the
      <span>45,000 $CEC</span> prize pool
    </h5>
    <div class="login-content">
      <li>
        <div class="left">
          <div>
            <span v-if="!token">1</span>
            <img v-else src="@/assets/icon_done.png" alt="">
          </div>
        </div>
        <div class="right">
          <h4>Bitget Wallet</h4>
          <div class="connect" v-if="!token" @click="walletLink">
            <span>Connect</span>
          </div>
          <div v-else class="address">{{ address }}</div>
          <div class="email" v-if="token && email">
              Game Account:
              <span>{{ email }}</span>
            </div>
        </div>
      </li>
      <li v-if="token && !email">
        <div class="left">
          <div>
            <span v-if="isEmailTips != 4">2</span>
            <img v-else src="@/assets/icon_done.png" alt="">
          </div>
        </div>
        <div class="right">
          <h4>Register a game account</h4>
          <!-- <div class="connect" @click="walletLink">Connect</div> -->
          <div class="email-input">
            <input type="text" placeholder="Email Address" v-model="userEmail" />
            <p v-if="isEmailTips == 1">*Cannot be empty</p>
            <p v-if="isEmailTips == 2">*Please enter the correct email format</p>
            <p v-if="isEmailTips == 3">*Already registered</p>
          </div>
          <div class="send">
            <span class="send-btn" v-if="isLogin" @click="getCode">Send</span>
            <span class="count-time" v-else>{{ countdown }}S</span>
          </div>
        </div>
      </li>
      <li v-if="isEmailTips == 4">
        <div class="left">
          <div>
            <span v-if="isCodeTips != 4">3</span>
            <img v-else src="@/assets/icon_done.png" alt="">
          </div>
        </div>
        <div class="right">
          <h4>Verification code</h4>
          <div class="email-input">
            <input type="text" placeholder="Code" v-model="userCode" />
            <!-- 不能为空 -->
            <p v-if="isCodeTips == 1">*Cannot be empty</p>
            <!-- 不正确-->
            <p v-if="isCodeTips == 2">*Please enter the correct code format</p>
            <!-- 验证码错误 -->
            <p v-if="isCodeTips == 3">*code not found</p>
          </div>
          <div class="send">
            <span class="send-btn" @click="confirmLogin">Confirm</span>
          </div>
        </div>
      </li>

    </div>
    <div class="dialog" v-if="isDownloadDialog">
      <h2>Task completed</h2>
      <div class="logo">
        <img src="@/assets/logo2.png" alt="">
      </div>
      <div class="user-info">
        <div class="user-info-label">Game Account:</div>
        <p>{{ email || userEmail }}</p>
        <div class="user-info-label">Bitget wallet:</div>
        <p class="cor">{{ address }}</p>
      </div>
      <div class="user-info-btn">
        <div class="left">
          <router-link to="/download">Download</router-link>
        </div>
        <div class="right" @click="isDownloadDialog = false">Close</div>
      </div>
    </div>
  </div>
</template>

<script>
import Header from "@/components/header.vue";
import { providers } from "ethers";
import { signLogin } from "@/wallet/utils";
import { BitgetWallet } from "@/wallet/BitgetWallet.js";
import { apiSend, isValiedCode, getEmail, isEmail, apiVerifyEmail } from "@/utils/request"
import { FirebaseUtil } from "@/utils/firebase.util";


export default {
  components: {
    Header
  },

  data() {
    return {
      address: localStorage.getItem('address'),
      userEmail: "",
      userCode: "",
      isDownloadDialog: false,
      token: localStorage.getItem('token'),
      isEmailTips: 0,
      isCodeTips: 0,
      pathName: '',
      countdown: 60,
      isLogin: true,
      email: '',
      isCheckWallet: null,
    };
  },
  computed: {
    
  },
  watch: {
  // 监听路由对象
    $route: {
      handler(val){
        this.pathName = val.params.name
      },
      // 深度观察监听
      immediate: true,
      deep: true
    }
  },

  mounted() {
    this.token = localStorage.getItem("token");
    this.address = localStorage.getItem("address");
    if (this.token) {
      this.email = getEmail(this.token);
      if (this.email) {
        this.isDownloadDialog = true;
      }
    }
  },
  methods: {
    async walletLink() {
      var isBitgetWallet = navigator.userAgent.indexOf('BitKeep') > 0
      if(!isBitgetWallet) {
        window.location.href = `https://bkcode.vip?action=dapp&url=${location.origin}/register`
      } else {
        setImmediate(() => {
          new FirebaseUtil().uploadEvent('connect_wallet', {})
        })
        try {
          let bitgetWallet = new BitgetWallet();
          let res = await bitgetWallet.getAccessToken()
          this.$store.commit('wallet/updateToken',res.token)
          localStorage.setItem('token', res.token)
          localStorage.setItem('address',res.accounts[0])
          this.token = res.token
          this.address = res.accounts[0]
          this.email = getEmail(this.token);
          if (this.email) {
            this.isDownloadDialog = true;
          }
        } catch (e) {
          console.log(e)
          new FirebaseUtil().uploadEvent('connect_wallet_err', {error: e.message || e})
        }
      }
    },

    // 获取验证码
    async getCode() {
      if(this.userEmail) {
        if(isEmail(this.userEmail)) {
          const {errcode,errmsg} = await apiSend(this.userEmail)
          if(errcode == 12) {
            this.isEmailTips = 3
          } else if(errcode == 13) {
            this.isEmailTips = 3
          } else if(errcode ==0) {
            this.countTime();
            this.isEmailTips = 4
          }
        } else {
          this.isEmailTips = 2
        }
      } else {
        this.isEmailTips = 1
      }
    },

    // 提交验证码
    async confirmLogin () {
      if(this.userCode) {
        if(isValiedCode(this.userCode)) {
          const {errcode,errmsg, data} = await apiVerifyEmail(this.userEmail, this.userCode)
          // console.log(data.token)
          // return
          if(errcode == 14) {
            this.isCodeTips = 3
          } else if(errcode ==0) {
            localStorage.setItem('token',data.token)
            this.$store.commit('wallet/updateToken',data.token)
            localStorage.setItem('email', this.userEmail)
            this.token = data.token
            this.isCodeTips = 4
            if(this.pathName) {
              this.$router.push(`/${this.pathName}`)
            } else {
              this.isDownloadDialog = true
            }
          }
          if (errcode) {
            new FirebaseUtil().uploadEvent('verify_email_err', {errcode, errmsg, mail: this.userEmail})
          }
        } else {
          this.isCodeTips = 2
        }
      } else {
        this.isCodeTips = 1
      }
      // this.isDownloadDialog = true
    },

    async logOut() {
      let _nativeProvider = window.bitkeep?.ethereum;
      // const { provider, accounts } =  new providers.Web3Provider(_nativeProvider);
      const { provider, accounts } = await _nativeProvider.request({
        method: "eth_requestAccounts"
      });
    },

    // 验证码倒计时
    countTime: function () {
      if(this.countdown == 0) {
        this.isLogin = true
      } else {
        this.isLogin = false
        this.countdown--
      }
      setTimeout(this.countTime, 1000)
    },

    getAddress() {

    }
  }
};
</script>

<style lang="scss" scoped>
.login {
  width: 100%;
  color: #fff;
  // position: relative;
  h5 {
    width: 320px;
    margin: 0 auto;
    font-family: "Poppins";
    font-weight: 400;
    font-size: 15px;
    // text-align: center;
    color: #ffffff;
    margin-top: 5px;
    span {
      color: #ffef67;
    }
  }
  .login-content {
    width: 370px;
    margin: 0 auto;
    // margin-left: 58.6px;
    margin-top: 35px;
    li {
      display: flex;
      min-height: 140px;
      position: relative;
      .left {
        width: 38px;
        height: 38px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #3c73ff;
        border-radius: 50%;
        span {
          font-family: "Anton";
          font-weight: 400;
          font-size: 20px;
          color: #000000;
        }
      }
      .right {
        // width: ;
        margin-left: 18.6px;
        position: relative;
        h4 {
          font-family: "Poppins";
          font-weight: 400;
          font-size: 20px;
          margin-bottom: 12px;
          color: #ffffff;
        }
        .connect {
          width: 370px;
          display: flex;
          align-items: center;
          justify-content: center;
          position: absolute;
          left: -40px;
          span {
            display: block;
            width: 218px;
            height: 61px;
            line-height: 61px;
            text-align: center;
            background: #4936d7;
            font-family: "Anton";
            font-weight: 400;
            font-size: 24px;
            border-radius: 30px;
          }
        }
        .address {
          position: absolute;
          padding: 5px 8px;
          border-radius: 15px;
          background: #211d26;
          font-size: 13px;
          color: #37ffff;
          font-family: "Poppins";
          font-weight: 400;
        }
        .email {
          position: absolute;
          top: 80px;
          width: 330px;
          height: 34px;
          line-height: 34px;
          padding: 0px 4px;
          padding-left: 15px;
          box-sizing: border-box;
          border-radius: 15px;
          background: #211d26;
          font-size: 12px;
          color: #fff;
          font-family: "Poppins";
          font-weight: 400;
          span {
            font-size: 13px;
            font-family: "Poppins";
            font-weight: bold;
          }
        }
        .email-input {
          width: 296px;
          height: 58px;
          background: #2f2a37;
          border-radius: 44px;
          input {
            width: 100%;
            height: 100%;
            background: #2f2a37;
            border: 0px;
            border-radius: 44px;
            padding-left: 10px;
            box-sizing: border-box;
            font-family: "Poppins-SemiBold";
            font-weight: bold;
            font-size: 21px;
            color: #fff;
          }
          input:focus {
            outline: none;
          }
          input::input-placeholder {
            color: #70697c;
          }
          input::-webkit-input-placeholder {
            //兼容WebKit browsers（Chrome的内核）
            color: #70697c;
          }
          input::-moz-placeholder {
            //Mozilla Firefox 4 to 18
            color: #70697c;
          }
          input::-moz-placeholder {
            //Mozilla Firefox 19+
            color: #70697c;
          }
          input::-ms-input-placeholder {
            //Internet Explorer 10+
            color: #70697c;
          }
        }
        p {
          font-family: "Poppins";
          font-weight: 400;
          font-size: 14px;
          color: #ff2222;
        }
        .send {
          display: flex;
          align-items: center;
          // text-align: center;
          span {
            display: inline-block;
            width: 218px;
            height: 61px;
            line-height: 61px;
            margin: 0 auto;
            margin-top: 28px;
            text-align: center;
            border-radius: 31px;
            font-family: "Anton";
            font-weight: 400;
            font-size: 24px;
            color: #ffffff;
          }
          .send-btn {
            background: #6f36d7;
          }
          .count-time {
            background: #2d2c2f;
          }
        }
      }
      &::after {
          content: "";
          position: absolute;
          top: 30px;
          left: 18px;
          width: 1px;
          height: calc(100% - 30px);
          background: #3CEEFE;
          z-index: 1;
        }
        &:last-child {
          &::after {
            display: none;
          }
        }
    }
  }
  .dialog {
    position: fixed;
    bottom: 0;
    width: 100%;
    height: 420px;
    background: #2D2738;
    border-radius: 66px 66px 0px 0px;
    border: 1px solid #B966FF;
    z-index: 9;
    // display: none;
    h2 {
      text-align: center;
      padding-top: 30px;
      font-family: 'Anton';
      font-weight: 400;
      font-size: 28px;
      color: #37FFFF;
    }
    .logo {
      width: 60px;
      height: 91px;
      margin: 0 auto;
      padding: 15px 0;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .user-info {
      // width: 400px;
      margin: 0 auto;
      .user-info-label {
        width: 370px;
        margin: 0 auto;
      }
      p {
        width: 370px;
        height: 34px;
        line-height: 34px;
        font-size: 14px;
        margin: 10px auto;
        padding: 0 20px;
        background: #211D26;
        border-radius: 26px;
      }
      .cor {
        color: #37FFFF;
      }
    }
    .user-info-btn {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 400px;
      margin: 0 auto;
      div {
        width: 190px;
        height: 61px;
        line-height: 61px;
        text-align: center;
        font-family: 'Anton';
        font-weight: 400;
        font-size: 24px;
        color: #FFFFFF;
      }
      .left {
        background: #6F36D7;
        border-radius: 46px;
        a {
          display: inline-block;
          width: 190px;
          height: 61px;
          line-height: 61px;
          text-align: center;
          font-family: 'Anton';
          font-weight: 400;
          font-size: 24px;
          color: #FFFFFF;
          text-decoration: none;
        }
      }
      .right {
        background: #57476C;
        border-radius: 46px;
      }
    }
  }
}
</style>