<template>
  <div class="login-container">
    <div class="image"/>
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="off">
      <div class="title">{{ title }}</div>
      <div>
        <el-form-item prop="username">
          <el-input
              ref="username"
              v-model.number.trim="loginForm.username"
              placeholder="请输入用户名"
              name="username"
              type="text"
              tabindex="1"
              size="normal"
              auto-complete="on">
            <template slot="prepend">
              <svg-icon icon-class="user"/>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
              :key="passwordType"
              ref="password"
              v-model.trim="loginForm.password"
              :type="passwordType"
              placeholder="请输入密码"
              name="password"
              tabindex="2"
              size="normal"
              auto-complete="off">
            <template slot="prepend">
              <svg-icon icon-class="password"/>
            </template>
            <template slot="append">
                             <span @click="showPwd">
                                <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"/>
                             </span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="identify">
          <div class="identify-container">
            <el-input
                class="identify el-form-item"
                v-model.trim="loginForm.identify"
                maxlength="4"
                placeholder="请输入验证码"
                tabindex="3"
                size="normal"
                @keyup.enter.native="handleLogin">
            </el-input>

            <identify class="code" :contentHeight="40" :identifyCode="identify" @onClick="randomCode"/>
          </div>
        </el-form-item>

        <el-button :loading="loading" type="primary" class="button" size="normal" @click.native.prevent="handleLogin">
          登录
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import identify from '@/components/Identify'
import config from '@/config'
import md5 from "js-md5";
import {validatePassword} from "@/utils/validate";

export default {
  name: 'LoginApp',
  components: {
    identify
  },
  data() {
    let validateIdentify = (rule, value, callback) => {
      if (this.identify !== value) {
        callback(new Error('验证码错误'));
      } else {
        callback();
      }
    };
    return {
      loginForm: {
        username: '',
        password: '',
        identify: ''
      },
      loginRules: {
        password: [{validator: validatePassword, trigger: 'blur'}],
        identify: [{validator: validateIdentify, trigger: 'blur'}]
      },
      title: config.loginTitle,
      identify: '', // 生成的验证码
      loading: false, // 登录中
      passwordType: 'password', // 密码显示方式
      redirect: undefined, // 转发地址
      query: undefined, // 转发的参数
    }
  },
  mounted() {
    this.randomCode();
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
        delete route.query.redirect;
        this.query = route.query;
      },
      immediate: true
    }
  },
  methods: {
    // 密码明文
    showPwd() {
      this.passwordType = this.passwordType === 'password' ? '' : 'password';
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },

    // 生成一个验证码
    randomCode() {
      let code = '';
      for (let i = 0; i < 4; i++) {
        code += Math.floor(Math.random() * 10);
      }
      this.identify = code;
      if (process.env.NODE_ENV === 'development') {
        this.loginForm.identify = code;
      }
    },

    // 登录
    handleLogin() {
      this.$refs['loginForm'].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$axios.post('/v1/system/user/login', {
            username: this.loginForm.username,
            password: md5(this.loginForm.password)
          }).then((response) => {
            // 开发环境默认添加开发者权限
            if (process.env.NODE_ENV === 'development') {
              if (response.permissions) {
                response.permissions.push("developer");
              } else {
                response.permissions = ["developer"];
              }
            }
            this.$store.commit("user/SET_USER_INFO", response);
            this.$router.push({path: this.redirect || '/', query: this.query});
            this.loading = false;
          }).catch(() => {
            this.randomCode();
            this.loading = false;
          })
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  width: 100%;
  min-width: 980px;
  height: 100%;
  background: rgb(33, 36, 46) url("./assets/login_bg.png") no-repeat;
  background-size: 100%;
  display: flex;
  align-items: center;
  justify-content: space-around;

  .image {
    background: rgb(33, 36, 46) url("./assets/menu-logo.png") no-repeat;
    background-size: 100%;
    width: 484px;
    height: 400px;
  }

  .login-form {
    min-width: 360px;
    padding: 50px;
    border-radius: 4px;
    background-color: white;
    text-align: center;

    .title {
      font-size: 30px;
      color: #000;
      margin-bottom: 36px;
      background: url('./assets/menu-logo.png') no-repeat left center;
      background-size: 30px 30px;
      padding-left: 40px;
      text-align: center;
      display: inline-block;
    }

    .identify-container {
      display: flex;
      align-items: center;

      .identify {
        flex: 1;
      }

      .code {
        margin: -1px -1px -1px 0;
        overflow: hidden;
      }
    }

    .button {
      width: 100%;
      margin-top: 10px;
      font-size: 16px;
    }
  }
}
</style>
