<template>
  <div class="login">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">

      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          type="text"
          name="username"
          auto-complete="off"
          placeholder="账号"
          tabindex="1"
          maxlength="20"
          @input="onUsernameChange"
        >
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon"/>
        </el-input>
      </el-form-item>

      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          auto-complete="off"
          placeholder="密码"
          tabindex="2"
          maxlength="20"
        >
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon"/>
        </el-input>
      </el-form-item>

      <el-form-item prop="verifyCode">
        <el-input
          v-model="loginForm.verifyCode"
          auto-complete="off"
          placeholder="4位验证码"
          style="width: 63%"
          tabindex="3"
          maxlength="4"
        >
          <svg-icon slot="prefix" icon-class="verifyCode" class="el-input__icon input-icon"/>
        </el-input>
        <div class="login-code">
          <img :src="captchaUrl" @click="updateCaptcha" class="login-code-img"/>
        </div>
      </el-form-item>

      <el-form-item prop="mailbox" v-if="useSendMail">
        <el-input
          v-model="loginForm.mailbox"
          auto-complete="off"
          placeholder="6位邮箱口令"
          style="width: 63%"
          tabindex="4"
          maxlength="6"
        >
          <svg-icon slot="prefix" icon-class="mailbox" class="el-input__icon input-icon"/>
        </el-input>
        <div class="mail-box">
          <el-button type="success" size="small" @click.prevent="sendMailCode" :disabled="isMailSend">
            {{ sendBtnText }}
          </el-button>
        </div>
      </el-form-item>
      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width:100%;"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>

import store from "@/store";
import {doEncrypt, doSign} from "@/utils/smutil";
import {debounce} from "lodash";

export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        // 用户名
        username: '',
        // 密码
        password: '',
        // 验证码
        verifyCode: '',
        // 邮箱验证码
        mailbox: ''
      },
      murmur: '',
      verifyuuid: '',
      // 是否使用邮箱口令
      useSendMail: true,
      // 是否已经发送了验证码
      isMailSend: false,
      // 计时器对象
      timer: null,
      // 倒数60秒
      counter: 60,
      // 文本
      sendBtnText: '点击发送邮箱',
      captchaUrl: this.getCaptcha,
      captchaText: '',
      loginRules: {
        /*  username: [{ required: true, trigger: 'blur', validator: validateUsername }],
          password: [{ required: true, trigger: 'blur', validator: validatePassword }]*/
        username: [{required: true, trigger: 'blur', message: '请输入用户名'}],
        password: [{required: true, trigger: 'blur', message: '请输入密码'}],
        verifyCode: [{required: true, trigger: 'blur', message: '请输入验证码'}, {
          min: 4,
          max: 4,
          message: '请输入4位验证码',
          trigger: 'blur'
        }],
        mailbox: [{required: true, trigger: 'blur', message: '请输入邮箱口令'}, {
          min: 6,
          max: 6,
          message: '请输入6位邮箱口令',
          trigger: 'blur'
        }]
      },
      loading: false,
      redirect: undefined
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    // 获取是否邮箱口令
    // this.$axios.get('/sysParameterController/getUseSendMail').then((res) => {
    //   this.useSendMail = JSON.parse(res.data)
    // }).catch((error) => {
    //   // 登录失败刷新验证码
    //   this.updateCaptcha()
    //   this.loginForm.verifyCode = ''
    //   this.loginForm.mailbox = ''
    //   this.reset()
    //   this.loading = false
    // })
    (async () => {
      const f = await this.getFinger()
      // 指纹
      this.murmur = f
      // 加载验证码
      this.getCaptcha()
    })();
  },
  mounted() {

  },
  methods: {
    getFinger() {
      const Fingerprint2 = require('fingerprintjs2')
      return new Promise(resolve => {
        if (window.requestIdleCallback) {
          requestIdleCallback(function () {
            Fingerprint2.getV18(function (result) {
              resolve(result)
            })
          })
        } else {
          setTimeout(function () {
            Fingerprint2.getV18(function (result) {
              resolve(result)
            })
          }, 500)
        }
      })
    },
    // 当账号变化时，重置发送按钮
    onUsernameChange() {
      this.reset()
    },
    /**
     * 重置倒计时
     */
    reset() {
      // 重置按钮可用
      this.isMailSend = false
      // 重置文本内容
      this.sendBtnText = '点击发送邮箱'
      if (this.timer) {
        // 存在计时器对象，则清除
        clearInterval(this.timer)
        // 重置秒数，防止下次混乱
        this.counter = 60
        // 计时器对象重置为空
        this.timer = null
      }
    },
    /**
     * 倒计时
     */
    countDown() {
      // 将setInterval()方法赋值给前面定义的timer计时器对象，等用clearInterval()方法时方便清空这个计时器对象
      this.timer = setInterval(() => {
        // 替换文本，用es6里面的``这个来创建字符串模板，让秒实时改变
        this.sendBtnText = `(${this.counter}秒)后重新发送`
        this.counter--
        if (this.counter < 0) {
          // 当计时小于零时，取消该计时器
          this.reset()
        }
      }, 1000)
    },
    /**
     * 发送邮箱验证码
     */
    sendMailCode: debounce(function () {
      // 判断账户是否已经输入
      if (!this.loginForm.username) {
        this.$message.error('请输入账号')
        return false
      }
      // 将按钮禁用，防止再次点击
      this.isMailSend = true
      // 开始倒计时，60s之后才能再次点击
      this.countDown()  // 这里实现倒计时的功能，文章下面开始介绍
      var searchParams = {
        username: this.loginForm.username
      }
      this.$axios.get(
        '/getMailCode', {params: searchParams}
      ).then((res) => {
        this.$message.success('邮件发送成功')
      })
    }, 1000),
    // 获取验证码
    getCaptcha: debounce(function () {
      var searchParams = {
        murmur: this.murmur
      }
      this.$axios.get('/getVerifyCode',
        {params: searchParams}).then((res) => {
        this.verifyuuid = res.data.uuid
        this.captchaUrl = 'data:image/gif;base64,' + res.data.imgBase64;
        this.captchaText = res.data.captchaText
      })
    }, 1000),
    updateCaptcha() {
      // 更新验证码
      this.getCaptcha()
    },
    handleLogin: debounce(function () {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          let verifycodetemp = this.loginForm.verifyCode
          if (this.captchaText.toLowerCase() != verifycodetemp.toLowerCase()) {
            this.$message.error('验证码录入错误!')
            this.updateCaptcha()
            this.loading = false
            return
          }
          // const param = new URLSearchParams()
          // param.append('username', this.loginForm.username)
          // param.append('password', this.loginForm.password)
          // param.append('code', this.loginForm.verifyCode)
          // param.append('verifyuuid', this.verifyuuid)
          // param.append('mailbox', this.loginForm.mailbox)
          const param = {
            username: this.loginForm.username,
            password: this.loginForm.password,
            code: this.loginForm.verifyCode,
            verifyuuid: this.verifyuuid,
            mailbox: this.loginForm.mailbox,
            murmur: this.murmur
          }
          this.$axios.post('/user/login', param).then((res) => {
            let tokenStr = doEncrypt(res.data)
            let sign = doSign(res.data)
            sessionStorage.setItem('jy', tokenStr + '&' + sign)
            // 清空路由菜单
            store.commit('SET_R', [])
            this.$router.push('/dashboard')
            this.loading = false
          }).catch((error) => {
            // 登录失败刷新验证码
            this.updateCaptcha()
            this.loginForm.verifyCode = ''
            this.loginForm.mailbox = ''
            this.reset()
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }, 1000)
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../../assets/images/login-background.jpg");
  background-size: cover;
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 33%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 38px;
  width: 105px;
}

.mail-box {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 36%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
</style>

