<template>
  <el-card class="rpm-sign-in">
    <div slot="header" align="center">
      <span>登入内业管理系统</span>
    </div>
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" label-width="0" class="rpm-sign-in-login">
      <el-form-item prop="username">
        <el-input
          ref="username"
          placeholder="输入账号"
          type="text"
          tabindex="1"
          autocomplete="on"
          v-model="loginForm.username"
        />
        <div class="rpm-sign__tip cprimary" >
          仅内部账号使用
        </div>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          ref="password"
          placeholder="输入密码"
          tabindex="2"
          :type="passwordType"
          autocomplete="new-password"
          v-model="loginForm.password"
          @keyup.native="checkCapslock"
          @blur="capsTooltip = false"
          @keyup.enter.native="handleLogin"
        >
          <i slot="suffix" class="el-icon-view" @click="showPwd"></i>
        </el-input>
        <div class="rpm-sign-in__tip cdanger" @click="qrcode=true" >
          忘记密码
        </div>
      </el-form-item>

      <el-form-item prop="remember">
        <input type="checkbox" v-model="loginForm.remember"  />
        <label class="ml10">记住密码</label>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click.native.prevent="handleLogin">
          登入
        </el-button>
      </el-form-item>
    </el-form>

    <el-dialog
      title="微信小程序扫码登入"
      class="fc tc"
      :visible.sync="qrcode"
      width="500px"
      :append-to-body="true"
      @close="qrcode=false"
    >
      <div class="qrcode">
        <img src="../../../assets/qrcode.jpg" />
      </div>
    </el-dialog>

  </el-card>
</template>

<script>
import { validateLoginname, validatePassword } from '@/utils/validate'
import md5 from '@/utils/md5'
import { mapActions } from "vuex";

const Base64 = require("js-base64").Base64;

export default {
  name: 'Login',
  data() {
    return {
      visibleForm: 'signIn',
      loginForm: {
        username: '',
        password: '',
        remember: false,
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateLoginname }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      qrcode: false,
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {}
    }
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  created(){
    this.redirect = this.$route.query.redirect
    this.loginForm.username = this.getCookie("username");
    let password = this.getCookie("password")
    if (password) {
      this.loginForm.password = Base64.decode( password );
      this.loginForm.remember = true;
    }else{
      this.loginForm.remember = false;
    }
  },
  methods: {
    ...mapActions("user", ["login", "loadDepartment"]),
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
    },
    getCookie: function (key) {
      if (document.cookie.length > 0) {
        var start = document.cookie.indexOf(key + "=");
        if (start !== -1) {
          start = start + key.length + 1;
          var end = document.cookie.indexOf(";", start);
          if (end === -1) end = document.cookie.length;
          return unescape(document.cookie.substring(start, end));
        }
      }
      return "";
    },
    setCookie: function (cName, value, expiredays) {
      var exdate = new Date();
      exdate.setDate(exdate.getDate() + expiredays);
      document.cookie =
        cName +
        "=" +
        decodeURIComponent(value) +
        (expiredays == null ? "" : ";expires=" + exdate.toGMTString());
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      let remember = this.loginForm.remember
      this.$refs.loginForm.validate(valid => {
        if (!valid)  return;
        this.loading = true
        let param = { username: this.loginForm.username, password: md5(this.loginForm.password) }
        let path = this.redirect || '/';
        this.login( param).then(() => {
          this.$router.push({ path, query: this.otherQuery })
          this.setCookie("username", this.loginForm.username, 30);
          if( remember ){
            let passWord = Base64.encode(this.loginForm.password);
            this.setCookie("password", passWord, 30);
          }else{
            this.setCookie("password", "", 30);
          }
          this.loadDepartment()
          this.loading = false
        }).catch((err) => {
          console.log("err", err)
          this.loading = false
        })
      })
    }
  }
}
</script>


<style lang="scss" scoped>
.el-button {
  width: 100% !important;
}
.login-form{
  width: 450px;
}
.rpm-sign-in {
  position: absolute;
  top: 20px;
  right: 30px;
  width: 350px;
}
.rpm-sign-in__tip {
  padding-top: 2px;
  padding-bottom: 2px;
  cursor: pointer;
  display: inline-block;
  line-height: 100%;
  position: relative;
  font-size: 14px;
}
</style>
