<script>
import Vue from 'vue'
import countryCode from '@/lib/countryCode.json'
import thirdLogin from './third-login.vue'
import { sendSmsCode, sentEmailCode, register, confirmEmail, getGoogleStatus, getLinkedinStatus } from '@/api/user'
export default Vue.extend({
  name: 'Index',
  components: {
    thirdLogin
  },
  data() {
    return {
      countryCode,
      username: '',
      password: '',
      confirmPassword: '',
      confirmCode: '',
      savePassword: false,
      loading: false,
      isLogin: true,
      isPhone: true,
      phone: '',
      country_code: '86',
      email: '',
      code: '',
      timer: null,
      count: 0,
      pre_register_key: '',

      third_login: '',
      third_token: '',
      need_bind: false,
      is_back: false,

      env: process.env.NODE_ENV
    }
  },
  mounted() {
    this.getSavedAccount()
    this.parseQuery()
  },
  methods: {
    parseQuery() {
      const url = new URL(window.location.href.replace('#', '?'))
      function showError() {
        this.$notify({
          title: '登录失败',
          message: '登录失败，请稍后重试。',
          type: 'error'
        })
        this.third_login = ''
        this.is_back = false
      }
      if (url.searchParams.get('code')) {
        this.is_back = true
        this.third_login = 'linkin'
        getLinkedinStatus(
          url.searchParams.get('state'),
          url.searchParams.get('code')
        ).then(res => {
          if (res.data.api_token) {
            this.tokenLogin(res.data.api_token)
          } else if (res.data.third_token) {
            this.third_token = res.data.third_token
            this.need_bind = true
          } else {
            showError()
          }
        }).catch(err => {
          showError()
        })
      }
      if (url.searchParams.get('access_token')) {
        this.is_back = true
        this.third_login = 'google'
        getGoogleStatus(
          url.searchParams.get('state'),
          url.searchParams.get('access_token')
        ).then(res => {
          if (res.data.api_token) {
            this.tokenLogin(res.data.api_token)
          } else if (res.data.third_token) {
            this.third_token = res.data.third_token
            this.need_bind = true
          } else {
            showError()
          }
        }).catch(err => {
          showError()
        })
      }
    },
    openThirdLogin(type) {
      this.is_back = false
      this.third_login = type
    },
    closeThirdLogin() {
      this.is_back = false
      this.need_bind = false
      this.third_login = ''
      this.third_token = ''
    },
    sentSMSCode() {
      if (this.loading || this.timer) {
        return
      }
      this.loading = true
      sendSmsCode(this.phone, this.country_code).then(res => {
        this.$notify({
          title: '发送成功',
          message: '短信验证码已发送，请注意查收',
          type: 'success'
        })
        this.count = 60
        this.timer = setInterval(() => {
          if (this.count > 0) {
            this.count--
          } else {
            clearInterval(this.timer)
            this.timer = null
          }
        }, 1000)
        this.loading = false
      }).catch(err => {
        this.loading = false
      })
    },
    sentMailCode() {
      if (this.loading || this.timer) {
        return
      }
      this.loading = true
      sentEmailCode(this.email).then(res => {
        this.$notify({
          title: '发送成功',
          message: '邮件已发送，请注意查收',
          type: 'success'
        })
        this.count = 60
        this.timer = setInterval(() => {
          if (this.count > 0) {
            this.count--
          } else {
            clearInterval(this.timer)
            this.timer = null
          }
        }, 1000)
        this.loading = false
      }).catch(err => {
        this.loading = false
      })
    },
    emailRegister() {
      if (this.loading) {
        return
      }
      if (this.email === '' || this.code === '' || this.password === '' || this.confirmPassword === '') {
        this.$notify({
          title: '提示',
          message: '请填写邮箱和验证码！',
          type: 'warning'
        })
      }
      if (this.password !== this.confirmPassword) {
        this.$notify({
          title: '提示',
          message: '密码不一致！',
          type: 'warning'
        })
      }
      this.loading = true
      register(this.email, '', this.code, 1, 0).then(res => {
        this.pre_register_key = res.data.pre_register_key
        confirmEmail(this.pre_register_key, this.password, this.confirmPassword).then(res => {
          this.isLogin = true
          this.$notify({
            title: '注册成功',
            message: '即将跳转至登录页。',
            type: 'success'
          })
        }).catch(err => {
          this.loading = false
        })
      }).catch(err => {
        this.loading = false
      })
    },
    phoneRegister() {
      if (this.loading) {
        return
      }
      if (this.phone === '' || this.code === '') {
        this.$notify({
          title: '提示',
          message: '请填写电话号码和验证码！',
          type: 'warning'
        })
        return
      }
      register(this.phone, this.country_code, this.code, 0, 0).then(res => {
        this.isLogin = true
        this.$notify({
          title: '注册成功',
          message: '即将跳转至登录页。',
          type: 'success'
        })
      }).catch(err => {
        this.$notify({
          title: '注册失败',
          message: '注册失败，请稍后重试。',
          type: 'error'
        })
      })
    },
    getSavedAccount() {
      const account = localStorage.getItem('savedAccount')
      if (account) {
        this.username = account.username
        this.password = account.password
        this.savePassword = true
      }
    },
    tokenLogin(token) {
      this.$store.dispatch('tokenLogin', { token: token }).then(res => {
        this.$router.push('/dashboard')
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    login() {
      if (!this.username) {
        this.$message.error('请输入用户名')
        return
      }
      if (!this.password) {
        this.$message.error('请输入密码')
        return
      }
      if (this.loading) {
        return
      }
      this.loading = true
      this.$store.dispatch('login', {
        username: this.username,
        password: this.password,
        login_type: 0,
        login_portal: 0,
        savePassword: this.savePassword
      }).then(res => {
        this.loading = false
        this.$router.push('/dashboard')
      }).catch(err => {
        this.loading = false
        this.$message.error(err.message)
      })
    }
  }
})
</script>

<template>
  <div class="body">
    <div class="footer">
      <div class="item">
        <span>Copyright © what can i say</span>
      </div>
      <a class="item" href="https://beian.miit.gov.cn/" target="_blank">
        <span>闽ICP备1145141919号</span>
      </a>
      <a class="item" href="https://beian.miit.gov.cn/" target="_blank">
        <img class="gongan" src="/static/image/beian.png" alt="" />
        <span>闽公网安备1145141919号</span>
      </a>
    </div>
    <div class="bg-cont">
      <div class="text-cont">
        <img src="/static/image/logo_big_white.png" class="logo" />
        <div class="title">10分钟创建海外观众预登记服务平台</div>
        <div class="desc">展会活动观众预登记的数字展会工具</div>
      </div>
      <img class="bg-image" src="/static/image/login2.webp" alt="">
    </div>
    <div :style="{height:third_login?'64vh':'auto'}" class="login-cont">
<!--      <div class="image-left">-->
<!--        <img class="image" src="/static/image/login.webp" alt="">-->
<!--        <div class="title">展会服务系统</div>-->
<!--      </div>-->
      <div class="cont-right">
        <div class="title">
          <div :class="['item',isLogin?'active':'']" @click="isLogin=true">登录</div>
          <div :class="['item',isLogin?'':'active']" @click="isLogin=false">注册</div>
        </div>
        <template v-if="isLogin">
          <el-input v-model="username" prefix-icon="el-icon-user" placeholder="请输入用户名" class="input" />
          <el-input v-model="password" prefix-icon="el-icon-unlock" placeholder="请输入密码" show-password class="input" />
          <el-checkbox v-model="savePassword">记住密码</el-checkbox>
          <el-button type="primary" class="button" @click="login">
            <span>登录</span>
            <span v-if="loading" class="el-icon-loading" />
          </el-button>
        </template>
        <template v-else>
          <template v-if="isPhone">
            <el-select v-model="country_code" placeholder="请选择国家">
              <el-option v-for="(item,index) in countryCode" :key="item.country_code+index" :label="'+'+item.phone_code+'('+item.chinese_name+')'" :value="item.phone_code" />
            </el-select>
            <el-input v-model="phone" prefix-icon="el-icon-mobile-phone" placeholder="请输入手机号码" class="input" />
            <el-input v-model="code" prefix-icon="el-icon-key" placeholder="请输入验证码" class="input">
              <el-button slot="append" :disabled="!!timer" :loading="loading" @click="sentSMSCode()">{{ timer?count+'s':'发送验证码' }}</el-button>
            </el-input>
            <div class="change-way" @click="isPhone=false">使用邮箱注册</div>
            <el-button type="primary" class="button" @click="phoneRegister()">
              <span>注册</span>
              <span v-if="loading" class="el-icon-loading" />
            </el-button>
          </template>
          <template v-else>
            <el-input v-model="email" prefix-icon="el-icon-message" placeholder="请输入电子邮箱地址" class="input" />
            <el-input v-model="code" prefix-icon="el-icon-key" placeholder="请输入验证码" class="input">
              <el-button slot="append" :disabled="!!timer" :loading="loading" @click="sentMailCode()">{{ timer?count+'s':'发送验证码' }}</el-button>
            </el-input>
            <el-input v-model="password" prefix-icon="el-icon-unlock" placeholder="请输入密码" show-password class="input" />
            <el-input v-model="confirmPassword" prefix-icon="el-icon-unlock" placeholder="请再次输入密码" show-password class="input" />
            <div class="change-way" @click="isPhone=true">使用手机注册</div>
            <el-button type="primary" class="button" @click="emailRegister()">
              <span>注册</span>
              <span v-if="loading" class="el-icon-loading" />
            </el-button>
          </template>
        </template>
        <div class="third-login">
          <div class="third-title">第三方登录/注册：</div>
          <div class="button-list">
            <div class="third-button" @click="openThirdLogin('wechat')">
              <img class="icon" src="/static/image/icon/wechat.png">
            </div>
            <div class="third-button" @click="openThirdLogin('google')">
              <img class="icon" src="/static/image/icon/google.png">
            </div>
            <div class="third-button" @click="openThirdLogin('linkin')">
              <img class="icon" src="/static/image/icon/linkin.png">
            </div>
          </div>
        </div>
        <div :class="['third-window',third_login?'active':'']">
          <div class="third-head">
            <span class="third-title">第三方登录</span>
            <span class="el-icon-close" @click="closeThirdLogin()" />
          </div>
          <div class="third-body">
            <third-login
              v-if="third_login"
              :is_back="is_back"
              :need_bind.sync="need_bind"
              :third_token.sync="third_token"
              :login_type="third_login"
              @tokenLogin="tokenLogin"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
  .body{
    padding: 0 240px;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    background-image: linear-gradient(120deg,#F7FAFF,#A6C5FE);
    .footer{
      z-index: 2;
      position: absolute;
      left: 0;
      gap: 12px;
      bottom: 16px;
      width: 100%;
      display: flex;
      justify-content: center;
      .item{
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 4px;
        font-size: 16px;
        color: grey;
        text-decoration: none;
        .gongan{
          height: 1.2em;
        }
      }
    }
    .bg-cont{
      position: absolute;
      left: 0;
      top: 0;
      width: 52%;
      height: 100%;
      .text-cont{
        position: absolute;
        left: 48px;
        top: 64px;
        color: #ffffff;
        .logo{
          height: 52px;
        }
        .title{
          margin-top: 50px;
          padding-left: 8px;
          border-left: 3px solid #ffffff;
          font-size: 36px;
          font-weight: bold;
        }
        .desc{
          font-size: 20px;
          margin-top: 16px;
        }
      }
      .bg-image{
        width: 100%;
      }
    }
    .login-cont{
      background: white;
      overflow: hidden;
      display: grid;
      border-radius: 12px;
      box-shadow: 0 0 12px #00000011;
      grid-template-columns: 1fr;
      .image-left{
        display: none;
        padding: 40px;
        background: #123068;
        position: relative;
        .image{
          position: absolute;
          object-fit: cover;
          left: 0;
          top: 0;
          width: 100%;
          height: 100%;
        }
        .title{
          position: relative;
          color: white;
          font-size: 28px;
          font-weight: bold;
        }
      }
      .cont-right{
        position: relative;
        padding: 40px;
        display: flex;
        flex-direction: column;
        grid-gap: 16px;
        .third-window{
          position: absolute;
          top: 0;
          right: 0;
          width: 100%;
          height: 100%;
          background-color: white;
          transition-duration: 300ms;
          transform: translateX(100%);
          z-index: 10;
          display: grid;
          grid-template-rows: auto 1fr;
          &.active{
            transform: translateX(0);
          }
          .third-body{
            position: relative;
            iframe{
              border: none;
              width: 100%;
              height: 100%;
            }
          }
          .third-head{
            color: grey;
            padding: 8px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            .third-title{
              padding-left: 8px;
            }
            .el-icon-close{
              border-radius: 8px;
              width: 32px;
              height: 32px;
              display: flex;
              align-items: center;
              justify-content: center;
              cursor: pointer;
              &:hover{
                background-color: #eeeeee;
              }
            }
          }
        }
        .third-login{
          padding-top: 16px;
          border-top: 1px solid #ececec;
          .third-title{
            font-size: 16px;
            color: grey;
            margin-bottom: 16px;
          }
          .button-list{
            display: flex;
            gap: 16px;
            .third-button{
              cursor: pointer;
              width: 46px;
              height: 46px;
              border-radius: 50%;
              background-color: #eeeeee;
              display: flex;
              align-items: center;
              justify-content: center;
              .icon{
                transition-duration: 300ms;
                filter: brightness(0) opacity(0.5);
                width: 22px;
                height: 22px;
                object-fit: contain;
              }
              &:hover{
                background-color: #f4f4f4;
                .icon{
                  scale: 1.04;
                  filter: brightness(1) opacity(1);
                }
              }
            }
          }
        }
        .title{
          height: 36px;
          font-weight: bold;
          margin-bottom: 26px;
          display: flex;
          align-items: flex-end;
          gap: 20px;
          .item{
            line-height: 1.3;
            transition-duration: 300ms;
            font-size: 27px;
            cursor: pointer;
            display: flex;
            flex-direction: column;
            align-items: center;
            color: gray;
            &::after{
              transition-duration: 300ms;
              width: 40%;
              content: '';
              display: block;
              height: 4px;
              border-radius: 2px;
              background-color: lightgray;
            }
            &.active{
              font-size: 28px;
              color: black;
              &::after{
                width: 80%;
                background-color: #2563EB;
              }
            }
          }
        }
        .button{
          font-size: 18px;
          margin-top: 48px;
          width: 400px;
        }
        .test-button{
          margin-left: unset;
          font-size: 18px;
          width: 400px;
        }
        .input{
          font-size: 16px;
          width: 400px;
        }
        .change-way {
          font-weight: 500;
          line-height: 19px;
          font-size: 15px;
          color: #409EFF;
          cursor: pointer;
          width: fit-content;
        }
      }
    }
  }
</style>
