<!--登陆主页-->
<template>
  <div :style="{backgroundImage:'url('+bgUrl+')'}" class="login-container">
    <div class="login-div">
      <div ref="element" class="right-div">
        <h5 class="login-title">用户登录</h5>

        <el-tabs v-model="loginType" @tab-click="handleChangeLoginType">
          <el-tab-pane label="密码登录" name="password">
            <el-form id= "login-form" ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="right">
              <el-form-item prop="username">
                <span class="svg-container">
                  <svg-icon icon-class="user" />
                </span>
                <el-input v-model.trim="loginForm.username" name="username" type="text" auto-complete="on" placeholder="用户名" />
              </el-form-item>
              <el-form-item prop="password">
                <span class="svg-container">
                  <svg-icon icon-class="password" />
                </span>
                <el-input
                  :type="pwdType"
                  v-model.trim="loginForm.password"
                  name="password"
                  auto-complete="on"
                  placeholder="密码"
                  @keyup.enter.native="handleLogin" />
                <span class="show-pwd" @click="showPwd">
                  <svg-icon :icon-class="pwdType === 'password' ? 'eye' : 'eye-open'" />
                </span>
              </el-form-item>

              <kaptcha-comp v-if="showKaptcha" ref="kaptcha" @passKaptcha="passKaptcha"/>

              <el-form-item>
                <el-button :loading="loading" class="login-btn" type="primary" style="width:100%;" @click.native.prevent="handleLogin">
                  登录
                </el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>

          <el-tab-pane label="人脸登录" name="face">
            <face-login ref="faceCapture" @cameraReady="handleCameraReady" @captured="handleFaceCaptured" />
          </el-tab-pane>

          <el-tab-pane label="扫码登录" name="qrcode">
            <qr-code-login ref="qrcode" @qrcodeError="handleQrCodeError" @qrcodeLogin="handleQrCodeLogin" />
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="clear-div"/>
    </div>
    <div class="system-title">
      <img :src="logo" style="margin-right:10px;float:left;height:40px;">
      <!--<svg-icon icon-class="logo" style="margin-right:20px;float:left"/>-->
      <div class="title-img">
        <el-image fit="contain" style="height:100%" src="./static/images/login_images/title.png"/>
      </div>
    </div>
  </div>
</template>

<script>
import { RSAencrypt } from '@/utils/security'
import kaptchaComp from '@/views/login/kaptcha/kaptcha'
import FaceLogin from '@/views/login/faceLogin'
import QrCodeLogin from '@/views/login/qrcodeLogin'
import { removeCurrentSys, setToken } from '@/utils/auth'
import { faceLogin } from '@/api/login'

export default {
  name: 'Login',
  components: {
    // 注册组件
    FaceLogin,
    QrCodeLogin,
    kaptchaComp: kaptchaComp
  },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value.length < 1) {
        callback(new Error('用户名不能为空'))
      } else {
        callback()
      }
    }
    const validatePass = (rule, value, callback) => {
      if (value.length < 1) {
        callback(new Error('密码不能为空'))
      } else {
        callback()
      }
    }
    const validateKaptcha = (rule, value, callback) => {
      console.log('验证验证码')
      if (this.showKaptcha) { // 如果开启了验证码判断，否则不判断
        if (value.length < 1) {
          callback(new Error('验证码不能为空'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: '',
        password: '',
        kaptcha: ''
      },
      loginRules: {
        username: [{ required: true, trigger: ['blur', 'change'], validator: validateUsername }],
        password: [{ required: true, trigger: ['blur', 'change'], validator: validatePass }],
        kaptcha: [{ required: false, trigger: ['blur', 'change'], validator: validateKaptcha }]
      },
      loading: false,
      pwdType: 'password',
      redirect: '/',
      showKaptcha: false, // 是否显示验证码
      bgUrl: require('@/assets/login_images/bg1.png'), // 背景图片
      logo: require('@/assets/login_images/logo.png'),
      loginType: 'password',
      faceList: [],
      tryFaceLogin: false, // 尝试人脸登录
      tryCount: 0 // 尝试次数
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  beforeCreate: function() { // 从后台获取系统配置，根据配置判断是否加载验证码控件
    this.loading = true
    this.$store.dispatch('GetConfig').then(() => {
      this.showKaptcha = this.$store.getters.kaptcha
      this.loading = false
      this.$message.success('连接服务器成功')
    }).catch((e) => {
      this.$message.error('连接服务器失败')
      this.loading = false
    })
  },
  methods: {
    showPwd() { // 明文显示密码
      if (this.pwdType === 'password') {
        this.pwdType = ''
      } else {
        this.pwdType = 'password'
      }
    },
    passKaptcha() { // 从子组件获取验证码的数据
      this.loginForm.kaptcha = this.$refs.kaptcha.kaptcha
      console.log(this.loginForm.kaptcha)
    },
    handleLogin() { // 点击登录按钮
      // if (!this.showKaptcha) { // 如果未开启验证码，将验证码字段从提交字段中移除
      //   delete this.loginForm['kaptcha']
      //   delete this.loginRules['kaptcha']
      // }
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          // 密码加密
          const loginForm = {
            sid: this.$store.getters.sid,
            username: this.loginForm.username,
            password: RSAencrypt(this.loginForm.password),
            kaptcha: this.loginForm.kaptcha
          }
          this.$store.dispatch('Login', loginForm).then(() => {
            this.loading = false
            this.$message.success('登录成功')
            removeCurrentSys()
            this.$router.push({ path: '/' })
          }).catch(() => {
            this.loading = false
            if (this.showKaptcha) {
              this.$refs.kaptcha.refreshCode()
            }
          })
        } else {
          return false
        }
      })
    },
    handleChangeLoginType() {
      // 关闭扫码登录的定时器
      this.$refs.qrcode.tryLoginCount = -1

      // 如果是人脸登录方式则打开摄像头
      if (this.loginType === 'face') {
        // 进入人脸登录页，打开摄像头
        this.tryFaceLogin = true
        this.$refs.faceCapture.getCompetence()
      } else {
        // 离开人脸登录页，关闭摄像头
        this.$refs.faceCapture.stopNavigator()

        // 清除变量值
        this.tryFaceLogin = false
        this.tryCount = 0
        this.faceList = []
        if (this.loginType === 'qrcode') {
          // 二维码扫码登录
          this.$refs.qrcode.initQrCode()
        }
      }
    },
    handleCameraReady() {
      // 摄像头已打开，可以开始采图
      this.$refs.faceCapture.setImage()
    },
    handleFaceCaptured(image) {
      this.faceList.push(image)
      console.log(this.faceList.length)

      if (this.tryFaceLogin === false) {
        return ''
      }

      if (this.tryCount < 5) {
        // 如果拍到照片，调用接口进行登录，同时停止拍照
        if (this.faceList.length > this.tryCount) {
          faceLogin({
            image: this.faceList[this.tryCount] // 取一张图进行尝试
          }).then(response => {
            console.log(response)
            if (response.code === 200) {
              if (response.success === true) {
                // 设置token
                const data = response.data
                setToken(data.token)
                this.$store.commit('SET_TOKEN', data.token)

                // 关闭摄像头
                this.$refs.faceCapture.stopNavigator()

                // 跳转页面
                this.$message.success('登录成功')
                removeCurrentSys()
                this.$router.push({ path: '/' })
              } else {
                // 登录失败，重新触发拍照并识别
                if (response.message === '') {
                  response.message = '人脸匹配失败'
                }
                this.$message.warning(response.message + '，已尝试' + this.tryCount + '次')

                const that = this
                setTimeout(function() {
                  that.$refs.faceCapture.setImage()
                }, 1000)
              }
            }
          })
          this.tryCount++
        }
      } else {
        this.$message.error('人脸登录失败，请重试或联系管理员')
        this.loginType = 'password' // 切换回密码登录
        this.handleChangeLoginType()
      }
    },
    handleQrCodeError() {
      this.$message.error('二维码获取失败，请重试或联系管理员')
      this.loginType = 'password' // 切换回密码登录
      this.handleChangeLoginType()
    },
    handleQrCodeLogin(token) {
      // 设置token
      setToken(token)
      this.$store.commit('SET_TOKEN', token)

      // 跳转页面
      this.$message.success('登录成功')
      removeCurrentSys()
      this.$router.push({ path: '/' })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
  $bg:#FFFFFF;
  $light_gray:#ffffff;
  $dark_gray:#889aa4;

/* reset element-ui css */
.login-container {
  .face-outer {
    border: 2px solid #007eff;
    width: 400px;
    height: 301px;
  }
  .el-input {
    display: inline-block;
    height: 40px;
    width: 85%;
    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 8px 5px 8px 8px;
      color: $dark_gray;
      height: 40px;
      &:-webkit-autofill {
        -webkit-box-shadow: 0 0 0px 1000px $light_gray inset !important;
        -webkit-text-fill-color: $dark_gray !important;
      }
    }
  }
  .el-form-item {
    border: 1px solid #c5c5c5;
    background: #ffffff;
    border-radius: 5px;
    color: #000000;
    margin-bottom: 35px;
    .el-form-item__error{
      line-height: 2 !important;
    }
  }
  .el-button {
    line-height:1.2;
  }
}

</style>

<style rel="stylesheet/scss" lang="scss" scoped>
$bg:#FFFFFF;
$dark_gray:#889aa4;
$light_gray:#fff;
.login-container {
  position: relative;
  height: 100%;
  width: 100%;
  background-color: #000000;
  background-repeat: no-repeat;
  -webkit-background-size: 100% 100%;
  background-size: 100% 100%;
  background-color: $bg;
  .system-title{
    font-size: 30px;
    color: white;
    width:80%;
    position: fixed;
    top:40px;
    left:50px;
    .title-img{
      height:38px;
      display: inline-block;
      float: left;
      .el-image{
        el-image__inner{
          object-position: left !important;
        }
      }

    }
  }
  .login-div{
    width:500px;
    position:absolute;
    overflow:hidden;
    left:60%;
    top:50%;
    margin-top:-220px;
  }
  .left-div{
    width:60%;
    float:left;
    background: #ffffff url("/static/images/login_images/left.jpg");
  }
  .title-div{
    margin:20px 30px 30px 30px;
  }
  .title{
    color:$light_gray;
    font-size: 26px;
    font-weight: 400;
  }
  .right-div{
    width:100%;
    padding: 20px 50px;
    float:left;
  }
  .clear-div{
    clear:both;
  }
  .login-form {
    max-width: 100%;
    padding: 15px 0px;
    margin: auto;
    overflow:hidden;
    .el-form-item{
      margin-bottom: 35px;
      .el-form-item__error{
        line-height: 1.5 !important;
      }
    }
  }
  .tips {
    font-size: 14px;
    /*color: #fff;*/
    margin-bottom: 10px;
    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }
  .svg-container {
    padding: 0px 3px 0px 10px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }
  .login-title {
    font-size: 25px;
    font-weight: 500;
    color: #0e3877;
    margin: 10px auto 10px auto;
  }
  .login-subtitle {
    font-size: 18px;
    font-weight: 400;
    color: #9c9c9c;
    margin: 10px auto 30px auto;
  }
  .login-btn {
    background-color: #3948d5;
    font-size: 17px;
    border-color: #3948d5;
  }
  .login-btn:hover {
    background-color: #5863f6;
    border-color: #5863f6;
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
