<template>
  <div id="backlogin">
    <div class="content">
      <h1>虚拟营业厅管理平台</h1>
      <h3>账户密码登录</h3>
      <el-form id="form" :model="loginForm" :rules="rules" ref="loginForm">
        <el-form-item prop="username">
          <div class="line">
            <img src="../../../static/images/icon/username.png" alt="">
            <input type="text" placeholder="账户" v-model="loginForm.username" autofocus clearable>
          </div>
        </el-form-item>
        <el-form-item prop="password">
          <div class="line">
            <img src="../../../static/images/icon/password.png" alt="">
            <input type="password" placeholder="密码" v-model="loginForm.password" @keyup.enter="submitForm" clearable>
          </div>
        </el-form-item>
        <el-form-item>
          <div class="line">
            <img src="../../../static/images/icon/verifyCode.png" alt="">
            <input  placeholder="验证码" v-model="loginForm.captcha" clearable>
            <img :src="verifyCodeImg" alt="" class="verifyCodeImg">
            <img src="../../../static/images/icon/refresh.png" alt="" class="verfyRefesh" @click="getVerifyCode">
          </div>
        </el-form-item>
        <el-form-item prop="rem">
          <!--<el-checkbox v-model="checked">自动登录</el-checkbox>-->
          <router-link to="/forgetPassword" class="forget-password r-float"><span>忘记密码</span></router-link>
        </el-form-item>
        <el-form-item>
          <el-button class="login" :disabled="flag" type="submit" @click="submitForm">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
  import { baseUrl } from '@/config/env'
  import axios from 'axios'
  let i = 0;
  export default {
    data() {
      return {
        checked: '',
        loginForm: {
          username: '',
          password: '',
          captcha:'',
        },
        CaptchaId:'',
        verifyCodeImg:'',
        rules: {
          username: [
            {required: true, message: '请输入用户名', trigger: 'blur,change'},
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur,change'}
          ]
        },
        flag:false,
      }
    },
    mounted() {
      this.initLogin();
      // 获取验证码
      this.getVerifyCode()
    },
    methods: {
      getVerifyCode(){
        axios({
          method: 'get',
          // url:'http://localhost:3001/api/verifyCode',
          url:`${baseUrl}verifyCode1`,
          responseType: 'arraybuffer'
        }).then(res => {
          this.CaptchaId = res.headers['captchaid'] || ''
          this.verifyCodeImg = this.getUserPhoto(res)
        })
      },
      getUserPhoto(res){
        let uInt8Array = new Uint8Array(res.data);
        let len = uInt8Array.length;
        let binaryString = new Array(len);
        while (len--) {
          binaryString[len] = String.fromCharCode(uInt8Array[len]);
        }
        let data = window.btoa(binaryString.join(''));
        let imageType = 'image/jpeg';
        let imageUrl = "data:" + imageType + ";base64," + data
        return imageUrl

      },
      initLogout() {
        let vm = this;
        let loginDate = vm.$qs.stringify({
          username: vm.loginForm.username,
          password: vm.loginForm.password,
          captcha: vm.loginForm.captcha
        });
        let headers = {
          CaptchaId: this.CaptchaId
        }
        vm.$https({
          method: 'post',
          url: 'ajaxLogin',
          authType: this.token,
          headers:headers
        }, loginDate, '' , '' ).then((res) => {
          if (res.data.status === 201 || res.data.status === 200) {
            localStorage.setItem("checked", this.checked);
            /*自动登录状态*/
            localStorage.setItem('userId', res.data.employee.id);
            /*登录用户*/
            localStorage.setItem("backToken", res.data.token);
            /*登录用户token签名*/
            if (!res.data.employee.avatar || res.data.employee.avatar == "") {
              res.data.employee.avatar = "./static/images/pic/usericon.png";
            }
            localStorage.setItem("bankBranchName", res.data.employee.bankBranchName);    /*网点名称*/
            localStorage.setItem("roleId", res.data.employee.roleId); /*角色id*/
            localStorage.setItem('roleName', res.data.employee.roleName); /*角色名*/
            localStorage.setItem("avatar", res.data.employee.avatar); /*头像*/
            localStorage.setItem("username", res.data.employee.username); /*用户名*/
            localStorage.setItem("bankBranchId", res.data.employee.bankBranchId); /*网点ID*/
            localStorage.setItem("menuList", JSON.stringify(res.data.menuList));  /*菜单*/
            vm.$message({
              type: 'success',
              message: res.data.message
            });
            setTimeout(function () {
              vm.$router.push('/indexPage');
              vm.flag = false;
            }, 1000);
          } else {
            i = i+1;
            vm.$message({
              type: 'error',
              message: res.data.message,
              // message: '用户名或密码错误',
            })
            if (i >= 3) {
              vm.$router.push('/forgetPassword');
              i = 0;
              return false;
            }
            this.flag = false;
            this.getVerifyCode()
          }
        }).catch(function (err) {
          this.flag = false;
          console.log(err);
        })
      },
      submitForm() {
        this.$refs.loginForm.validate((valid) => {
          if (valid) {
            if(!this.flag) {
              this.flag = true;
              this.initLogout();
            }
          } else {
            this.flag = false;
            return false;
          }
        })
      },
      initLogin() {
        let checked = localStorage.getItem('checked');
        if (checked == 'true') {
          this.checked = true;
          this.autoLogin();
        } else {
          this.checked = false;
        }
      },
      autoLogin() {
        let _this = this;
        let backToken = localStorage.getItem('backToken');
        if (backToken) {
          this.$router.push('/indexPage');
          _this.$https({
            method: 'get',
            url: 'public/authToken',
            authType: this.backToken
          }).then((res) => {
              if (res.data.status == 200) {
                _this.$router.push('/indexPage')
              }
            }, (error) => {
              console.log(error)
            }
          )
        }
      }
    }
  }


</script>

<style lang="less">
  @import '../../style/common';

  #backlogin {
    width: 100%;
    height: 100%;
    background: url("../../../static/images/pic/bg.png");
    overflow: hidden;
    .content {
      width: 360px;
      height: 393px;
      margin: 10% auto;
      h1 {
        font-size: 36px;
        font-weight: 600;
        text-align: center;
        color: rgba(24, 144, 255, 1);
        font-family: SourceHanSansCN-Bold;
      }
      h3 {
        font-size: 20px;
        font-weight: 500;
        color: rgba(0, 0, 0, 1);
        margin: 8% 0% 5%;
        text-align: center;
      }
      .el-form {
        padding: 0px 10%;
        .line {
          width: 100%;
          height: 100%;
          border-radius: 4px;
          border: 1px solid rgba(217, 217, 217, 1);
          background: #fff;
          input {
            margin-left: 10px;
            height: 100%;
            width: 85%;
            font-size: 18px;
            background: transparent;
            border: none;
          }

          ::-webkit-input-placeholder { /* WebKit browsers */
            font-size: 12px;
            color: rgba(192, 196, 204, 1);
          }
          :-moz-placeholder { /* Mozilla Firefox 4 to 18 */
            font-size: 12px;
            color: rgba(192, 196, 204, 1);
          }
          ::-moz-placeholder { /* Mozilla Firefox 19+ */
            font-size: 12px;
            color: rgba(192, 196, 204, 1);
          }
          :-ms-input-placeholder { /* Internet Explorer 10+ */
            font-size: 12px;
            color: rgba(192, 196, 204, 1);
          }

          img {
            float: left;
            width: 16px;
            height: 16px;
            margin: 10px 0 0 6px;
          }
          .verifyCodeImg{
            position: absolute;
            right: -160px;
            top: -8px;
            width: 150px;
            height: 40px;
          }
          .verfyRefesh{
            position: absolute;
            right: -200px;
            width: 22px;
            height: 22px;
            cursor: pointer;
          }

        }
        input {
          width: 100%;
          height: 40px;
          background: rgba(255, 255, 255, 1);
          border-radius: 4px;
          border: 1px solid rgba(217, 217, 217, 1);
        }
        .forget-password {
          font-size: 14px;
          font-weight: 400;
          color: rgba(24, 144, 255, 1) !important;
        }

      }
      .el-button {
        width: 100%;
        height: 40px;
        background: rgba(24, 144, 255, 1);
        border-radius: 4px;
        color: #fff;
      }
    }
  }

</style>
