<script lang="ts">
import Vue from 'vue'
import countryCode from '@/lib/countryCode.json'
import { sendSmsCode, sentEmailCode, register, confirmEmail, getGoogleStatus, getLinkedinStatus } from '@/api/user'
import { getExpoInfo } from '@/api/expo'
import thirdLogin from '@/views/login/third-login.vue'
export default Vue.extend({
  name: 'Index',
  components: {
    thirdLogin
  },
  data() {
    return {
      regWay: 0, // 0:手机注册 1:邮箱注册
      countryCode,
      loginInfo: {
        phone: '',
        countryCode: '86',
        password: '',
        password_2: '',
        smsCode: '',
        email: '',
        emailCode: '',
        pre_register_key: '',
        showPasswordDialog: false
      },
      emailCounter: 0,
      emailTimer: null,
      smsCounter: 0,
      smsTimer: null,
      expoData: {},
      expo_key: '',
      subTimer: '',
      subTime: '',
      isLogin: false,

      third_login: '',
      third_token: '',
      need_bind: false,
      is_back: false
    }
  },
  computed: {
    user() { return this.$store.state.user.user }
  },
  mounted() {
    this.init()
  },
  beforeDestroy() {
    clearInterval(this.subTimer)
  },
  methods: {
    init() {
      if (this.$route.query.expo_key) {
        this.expo_key = this.$route.query.expo_key
        getExpoInfo(this.expo_key).then(res => {
          this.expoData = res.data
          this.subTimer = setInterval(() => {
            this.subTime = Date.parse(res.data.end_date) - Date.now()
          }, 1000)
        }).catch(err => {
          this.$notify({
            title: '提示',
            message: '展会信息获取失败：'+err,
            type: 'error'
          })
        })
      } else {
        this.$router.push({
          name: 'login'
        })
      }
    },
    tokenLogin(token) {
      this.$store.dispatch('tokenLogin', { token: token }).then(res => {
        this.gotoForm()
      }).catch(err => {
        this.$notify({
          title: '提示',
          message: '使用本地令牌登录失败'+err,
          type: 'error'
        })
        this.$message.error(err.message)
      })
    },
    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 = ''
    },
    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 => {
          this.$notify({
            title: '提示',
            message: '领英授权登录失败'+err,
            type: 'error'
          })
          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 => {
          this.$notify({
            title: '提示',
            message: '谷歌授权登录失败'+err,
            type: 'error'
          })
          showError()
        })
      }
    },
    sentSms() {
      if (this.loginInfo.phone === '') {
        this.$message.error('请填写电话号码！')
        return
      }
      if (this.smsTimer) {
        return
      } else {
        sendSmsCode(this.loginInfo.phone, this.loginInfo.countryCode).then(res => {
          this.$message.success('发送成功！')
          this.smsCounter = 60
          this.smsTimer = setInterval(() => {
            this.smsCounter--
            if (this.smsCounter <= 0) {
              clearInterval(this.smsTimer)
              this.smsTimer = null
            }
          }, 1000)
        }).catch(err => {
          this.$notify({
            title: '提示',
            message: '验证码发送失败：'+err,
            type: 'error'
          })
        })
      }
    },
    sentEmail() {
      if (this.loginInfo.email === '') {
        this.$message.error('请填写邮箱！')
        return
      }
      if (this.emailTimer) {
        return
      } else {
        sentEmailCode(this.loginInfo.email).then(res => {
          this.$message.success('发送成功！')
          this.emailCounter = 60
          this.emailTimer = setInterval(() => {
            this.emailCounter--
            if (this.emailCounter <= 0) {
              clearInterval(this.emailTimer)
              this.emailTimer = null
            }
          }, 1000)
        }).catch(err => {
          this.$notify({
            title: '提示',
            message: '验证码发送失败'+err,
            type: 'error'
          })
        })
      }
    },
    submitLogin() {
      let username = ''
      let password = ''
      if (this.regWay) {
        if (this.loginInfo.email === '' || this.loginInfo.password === '') {
          this.$message.error('请填写账号与密码！')
          return
        }
        username = this.loginInfo.email
        password = this.loginInfo.password
      } else {
        if (this.loginInfo.smsCode === '' || this.loginInfo.phone === '') {
          this.$message.error('请填写手机号码与验证码！')
          return
        }
        username = this.loginInfo.phone
        password = this.loginInfo.smsCode
      }
      this.$store.dispatch('login', {
        username: username,
        password: password,
        phone: username,
        vaild_code: password,
        login_type: this.regWay ? '0' : '1',
        login_portal: 0
      }).then(res => {
        this.gotoForm()
      }).catch(err => {
        this.$notify({
          title: '提示',
          message: '登录失败：'+err,
          type: 'error'
        })

      })
    },
    gotoForm() {
      if (this.expo_key) {
        this.$router.push({
          name: 'userForm',
          params: {
            url: this.expo_key
          }
        })
      }
    },
    register() {
      if (this.regWay) {
        if (this.loginInfo.email === '' || this.loginInfo.emailCode === '') {
          this.$message.error('请填写邮箱与验证码！')
          return
        }
        register(this.loginInfo.email, '', this.loginInfo.emailCode, 1, '').then(res => {
          this.loginInfo.pre_register_key = res.data.pre_register_key
          this.loginInfo.showPasswordDialog = true
        }).catch(err => {
          this.$notify({
            title: '提示',
            message: '注册失败：'+err,
            type: 'error'
          })
        })
      } else {
        if (this.loginInfo.phone === '' || this.loginInfo.smsCode === '') {
          this.$message.error('请填写手机号码与验证码！')
          return
        }
        register('', this.loginInfo.phone, this.loginInfo.smsCode, 0, this.loginInfo.countryCode).then(res => {
          this.isLogin = true
          this.$message.success('注册成功！请前往登录')
        }).catch(err => {
          this.$notify({
            title: '提示',
            message: '注册失败：'+err,
            type: 'error'
          })
        })
      }
    },
    checkPassword() {
      if (this.loginInfo.password !== this.loginInfo.password_2) {
        this.$message.error('两次密码输入不一致！')
        return false
      }
      this.loginInfo.showPasswordDialog = false
      confirmEmail(this.loginInfo.pre_register_key, this.loginInfo.password, this.loginInfo.password_2).then(res => {
        this.isLogin = true
        this.$message.success('注册成功！请前往登录')
      }).catch(err => {
        this.$notify({
          title: '提示',
          message: '注册失败：'+err,
          type: 'error'
        })
      })
    }
  }
})
</script>
<template>
  <div class="body">
    <div class="head">
      <div class="title">
        {{ isLogin?'登录账号':'注册账号' }}
      </div>
      <div class="desc">
        中国大陆观众建议使用手机号码进行注册登录。
      </div>
    </div>
    <div v-if="expo_key" class="time-counter">
      <div class="title">距离展览开幕时间</div>
      <div class="counter-list">
        <div class="counter-item">
          <div class="num">{{ new Date(subTime).getDate() || '0' }}</div>
          <div class="unit">天</div>
        </div>
        <div class="counter-item">
          <div class="num">{{ new Date(subTime).getHours() || '0' }}</div>
          <div class="unit">时</div>
        </div>
        <div class="counter-item">
          <div class="num">{{ new Date(subTime).getMinutes() || '0' }}</div>
          <div class="unit">分</div>
        </div>
        <div class="counter-item">
          <div class="num">{{ new Date(subTime).getSeconds() || '0' }}</div>
          <div class="unit">秒</div>
        </div>
      </div>
    </div>
    <div v-if="isLogin" class="register-body">
      <div class="tab">
        <div class="tab-item" :class="regWay?'':'active'" @click="regWay=0">验证码登录</div>
        <div class="tab-item" :class="regWay?'active':''" @click="regWay=1">账号密码登录</div>
      </div>
      <template v-if="regWay">
        <div class="form-item">
          <div class="label">账号</div>
          <el-input v-model="loginInfo.email" placeholder="请输入账号" />
        </div>
        <div class="form-item">
          <div class="label">密码</div>
          <div class="sms-cont">
            <el-input v-model="loginInfo.password" show-password placeholder="请输入密码" />
          </div>
        </div>
      </template>
      <template v-else>
        <div class="form-item">
          <div class="label">
            国家/地区
          </div>
          <el-select v-model="loginInfo.countryCode" 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>
        </div>
        <div class="form-item">
          <div class="label">手机号码</div>
          <el-input v-model="loginInfo.phone" placeholder="请输入手机号码" />
        </div>
        <div class="form-item">
          <div class="label">验证码</div>
          <div class="sms-cont">
            <el-input v-model="loginInfo.smsCode" placeholder="请输入验证码" />
            <el-button :disabled="!!smsTimer" type="primary" @click="sentSms()">{{ smsTimer?smsCounter+'秒后重新获取':'获取验证码' }}</el-button>
          </div>
        </div>
      </template>
      <div class="piracy">
        登录即表示同意
        <span>《隐私政策》</span>
        、
        <span>《用户协议》</span>
      </div>
      <el-button type="primary" @click="submitLogin()">登录</el-button>
      <el-button type="text" @click="isLogin=false">没有账号？去注册。</el-button>
      <div class="third-login">
        <div @click="openThirdLogin('wechat')" class="button wechat">
          <img class="icon" src="/static/image/icon/wechat.png">
          微信扫码登录
        </div>
        <div @click="openThirdLogin('google')" class="button google">
          <img class="icon" src="/static/image/icon/google.png">
          谷歌授权登录
        </div>
        <div @click="openThirdLogin('linkin')" class="button linkin">
          <img class="icon" src="/static/image/icon/linkin.png">
          领英授权登录
        </div>
      </div>
    </div>
    <div v-else class="register-body">
      <div class="tab">
        <div class="tab-item" :class="regWay?'':'active'" @click="regWay=0">手机注册</div>
        <div class="tab-item" :class="regWay?'active':''" @click="regWay=1">邮箱注册</div>
      </div>
      <template v-if="regWay">
        <div class="form-item">
          <div class="label">账号</div>
          <el-input v-model="loginInfo.email" placeholder="请输入电子邮箱地址" />
        </div>
        <div class="form-item">
          <div class="label">密码</div>
          <div class="sms-cont">
            <el-input v-model="loginInfo.emailCode" placeholder="请输入验证码" />
            <el-button :disabled="emailTimer" type="primary" @click="sentEmail()">{{ emailTimer?emailCounter+'秒后重新获取':'获取验证码' }}</el-button>
          </div>
        </div>
      </template>
      <template v-else>
        <div class="form-item">
          <div class="label">
            国家/地区
          </div>
          <el-select v-model="loginInfo.countryCode" 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>
        </div>
        <div class="form-item">
          <div class="label">手机号码</div>
          <el-input v-model="loginInfo.phone" placeholder="请输入手机号码" />
        </div>
        <div class="form-item">
          <div class="label">验证码</div>
          <div class="sms-cont">
            <el-input v-model="loginInfo.smsCode" placeholder="请输入验证码" />
            <el-button :disabled="!!smsTimer" type="primary" @click="sentSms()">{{ smsTimer?smsCounter+'秒后重新获取':'获取验证码' }}</el-button>
          </div>
        </div>
      </template>
      <div class="piracy">
        注册即表示同意
        <span>《隐私政策》</span>
        、
        <span>《用户协议》</span>
      </div>
      <el-button type="primary" @click="register()">注册</el-button>
      <el-button type="text" @click="isLogin=true">已有账号？去登陆。</el-button>
      <div class="third-login">
        <div @click="openThirdLogin('wechat')" class="button wechat">
          <img class="icon" src="/static/image/icon/wechat.png">
          微信扫码登录
        </div>
        <div @click="openThirdLogin('google')" class="button google">
          <img class="icon" src="/static/image/icon/google.png">
          谷歌授权登录
        </div>
        <div @click="openThirdLogin('linkin')" class="button linkin">
          <img class="icon" src="/static/image/icon/linkin.png">
          领英授权登录
        </div>
      </div>
    </div>
    <el-dialog
      title="设置初始密码"
      custom-class="password-dialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      :visible.sync="loginInfo.showPasswordDialog"
      width="30%"
    >
      <div class="dialog-body">
        <div class="label">请设置密码</div>
        <el-input v-model="loginInfo.password" placeholder="请设置密码" show-password />
        <div class="label">请再次输入密码</div>
        <el-input v-model="loginInfo.password_2" placeholder="请再次输入密码" show-password />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="checkPassword()">确 定</el-button>
      </span>
    </el-dialog>
    <div :class="['mask',third_login?'show':'']">
      <div class="third-body">
        <span class="el-icon-close" @click="closeThirdLogin()" />
        <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>
</template>
<style scoped lang="scss">
.body{
  width: 100%;
  height: 100%;
  overflow: hidden;
  overflow-y: auto;
  width: 100%;
  .mask{
    transition-duration: 300ms;
    width: 100%;
    height: 100%;
    background-color: #00000044;
    left: 0;
    top: 0;
    position: fixed;
    display: flex;
    justify-content: center;
    align-items: center;
    pointer-events: none;
    opacity: 0;
    .third-body{
      position: relative;
      transition-duration: 300ms;
      background-color: white;
      transform: translateY(40px);
      width: 460px;
      height: 600px;
      .el-icon-close{
        position: absolute;
        right: 8px;
        top: 8px;
        border-radius: 4px;
        padding: 8px;
        transition-duration: 300ms;
        cursor: pointer;
        &:hover{
          background-color: #00000011;
        }
      }
    }
    &.show{
      pointer-events: all;
      opacity: 1;
      .third-body{
        transform: translateY(0);
      }
    }
  }
  .register-body{
    margin: 48px auto 64px;
    max-width: 800px;
    display: flex;
    flex-direction: column;
    gap: 16px;
    padding: 40px 50px;
    border-radius: 4px;
    box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.05);
    background: white;
    .third-login{
      display: grid;
      grid-gap: 16px;
      grid-template-columns: 1fr 1fr 1fr;
      .button{
        transition-duration: 300ms;
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 8px;
        justify-content: center;
        padding: 8px 16px;
        font-size: 16px;
        color: black;
        background-color: #FFFFFF;
        .icon{
          transition-duration: 300ms;
          width: 20px;
          height: 20px;
          object-fit: contain;
          filter: brightness(1);
        }
        &:hover{
          color: white;
          .icon{
            filter: brightness(100);
          }
          &.wechat{
            background: #0E932E;
          }
          &.google{
            background: #EA4335;
          }
          &.linkin{
            background: #0B66C1;
          }
        }
      }
    }
    .piracy{
      color: #6B7280;
      display: flex;
      font-size: 16px;
      span{
        color: #0052CC;
      }
    }
    .form-item{
      .label{
        color: #374151;
        font-size: 16px;
        margin-bottom: 8px;
      }
      .el-select{
        width: 100%;
      }
      .sms-cont{
        display: flex;
        gap: 12px;
      }
    }
    .tab{
      display: flex;
      border-bottom: 3px solid #E5E7EB;
      .tab-item{
        cursor: pointer;
        padding: 8px 16px;
        color: #6B7280;
        transform: translateY(3px);
        border-bottom: 3px solid transparent;
        &.active{
          color: #0052CC;
          border-bottom: 3px solid #0052CC;
        }
      }
    }
  }
  .time-counter{
    max-width: 800px;
    margin: 32px auto 0;
    background: #4DA9FF22;
    padding: 24px;
    border-radius: 8px;
    .counter-list{
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 16px;
      .counter-item{
        background: white;
        padding: 16px 0;
        border-radius: 4px;
        text-align: center;
        .num{
          color: #4D7CFF;
          font-size: 30px;
          font-weight: bold;
        }
        .unit{
          font-size: 14px;
          color: #6B7280;
        }
      }
    }
    .title{
      font-size: 18px;
      margin-bottom: 12px;
    }
  }
  .head{
    margin: 48px auto 0;
    max-width: 800px;
    .title{
      text-align: center;
      font-size: 24px;
      font-weight: bold;
    }
    .desc{
      margin-top: 8px;
      text-align: center;
      color: #4B5563;
    }
  }
}
</style>
<style>
body{
  background: #F9FAFB;
  .password-dialog{
    .dialog-body{
      .label{
        margin: 6px 0;
      }
    }
  }
}
</style>
