<template>
  <div id="login-right">
    <div class="right_content">
      <div class="single_title">
        欢迎登录
      </div>

      <div class="single-input">
        <el-input v-model="loginForm.userName" placeholder="请输入用户名"></el-input>
      </div>

      <div class="single-input">
        <el-input placeholder="请输入密码" v-model="loginForm.passWord" show-password></el-input>
      </div>

      <div class="single-input">
        <div class="input_type">
          <el-input  type="text"  v-model="loginForm.identifyingCode" placeholder="请输入验证码"></el-input>
        </div>
        <canvas @click="draw" id="myCanvas" width="90" height="40"></canvas>
      </div>

      <div class="single-input input_login">
        <el-button class="single_login" @click="loginIn">登录</el-button>
      </div>

    </div>


  </div>
</template>

<script>
import {Base64} from "js-base64";
import {loginIn} from "@/service/show-platform";
import {MessageBox} from "element-ui";
import {updateLoginLasttime,addLoginLog} from "@/service/interfaceKoolkit";
export default {
  name: "LoginRight",
  data(){
    return{
      canvas: null,
      context: null,
      message_text:null,
      show_num:[],
      width: window.innerWidth,
      height: window.innerHeight,
      loginForm: {
        userName: "",
        passWord: "",
        identifyingCode:""
      }
    }
  },
  mounted() {
    this.canvas = document.getElementById("myCanvas");
    this.draw();
    clearInterval(this.$global.operationTimer);
  },
  methods:{
    setOperationTime(){
      this.$global.operationTimer = setInterval(() => {
        //登录成功后修改用户登录唯一标识
        updateLoginLasttime().then(response => {
          var date = response.msg;
          if (date[0]["success"] == "true") {
            return;
          } else {
            return;
          }
        });
      }, 10000);
    },
    loginIn(){
      this.message_text = null;
      if(this.loginForm.identifyingCode == "" || this.loginForm.identifyingCode == null){
        this.message_text = "请输入验证码!";
      }
      if(this.show_num.join("") != this.loginForm.identifyingCode.toString().toLocaleLowerCase()){
        this.message_text = "验证码输入错误!";
      }
      if(this.loginForm.passWord == "" || this.loginForm.passWord == null){
        this.message_text = "请输入密码!";
      }

      if(this.loginForm.userName == "" || this.loginForm.userName == null){
        this.message_text = "请输入用户名!";
      }
      if(this.message_text != null){
        MessageBox.alert(this.message_text, '提示', {
          confirmButtonText: '确定'
        });
        this.draw();
        return;
      }
      loginIn(this.loginForm.userName,Base64.encode(this.loginForm.passWord)).then(res =>{
        let data = res.msg[0].Rows;
        if(data.length > 0){
          var LOGIN_LOCK = data[0]["LOGIN_LOCK"];
          if (LOGIN_LOCK == 1) {
            var time = new Date(data[0]["GETTIME"]).getTime() - new Date(data[0]["LAST_TIME"]).getTime();
            time = time / 1000;
            if (time < 20) {
              MessageBox.alert('当前用户已登录！', '提示', {
                confirmButtonText: '确定'
              });
              return;
            }
          }
          var bool = false;
          if(data[0]["SYSTEM_TYPE"] == "1"){
            for(var i = 0 ; i < data[0].ROLE_LIST.length ;i++){
              if(data[0].ROLE_LIST[i]["ROLE_ID"] == "1" || data[0].ROLE_LIST[i]["ROLE_ID"] == "25"){
                bool = true;
                break;
              }
            }
          }

          if(data[0]["SYSTEM_TYPE"] == "2"){
            for(var i = 0 ; i < data[0].ROLE_LIST.length ;i++){
              if(data[0].ROLE_LIST[i]["ROLE_ID"] == "1" || data[0].ROLE_LIST[i]["ROLE_ID"] == "0"){
                bool = true;
                break;
              }
            }
          }
          if(bool == false){
            this.$message({
              showClose: true,
              message: '当前用户无登录权限！',
              type: 'error'
            });
            return;
          }

          //获取用户信息  0  1 163  173  174
          var usercode = data[0].USERID;
          var username = data[0].USERNAME;
          var unitcode = data[0].UNIT;
          var unitname = data[0].UNIT_NAME;
          var lasttime = data[0].LAST_TIME;
          var changetime = data[0].CHANGE_TIME;
          var role = data[0].ROLE_LIST;
          var userkeycode = data[0]["TEMPUSERKEYCODE"];
          var role_uuid = data[0]["ROLE_UUID"];
          var change_time = data[0].CHANGE_TIME;
          //判断用户角色，只有平台管理员和系统管理员可以登录

          //保存用户信息
          localStorage.setItem("zhfx_usercode", usercode);
          localStorage.setItem("zhfx_username", username);
          localStorage.setItem("zhfx_unitcode", unitcode);
          localStorage.setItem("zhfx_unitname", unitname);
          localStorage.setItem("zhfx_lasttime", lasttime);
          localStorage.setItem("zhfx_role", role);
          localStorage.setItem("zhfx_userkeycode", userkeycode);
          localStorage.setItem("zhfx_changetime", changetime);
          localStorage.setItem("zhfx_role_uuid", role_uuid);
          localStorage.setItem("zhfx_changetime", change_time);
          this.$router.push('/showPlatform');
          this.setOperationTime();
          addLoginLog().then(response => {
            var date = response.msg;
            if (date[0]["success"] == "true") {
              return;
            } else {
              return;
            }
          });

          var myDate = new Date();
          var now_date = myDate.toLocaleDateString()   //直接获取当前的年月日        2017/10/19
          var change_date = this.formatDate(localStorage.getItem("zhfx_changetime"));
          var days = this.getDayNum(change_date, now_date);
          if (days > 90) {
            this.$message({
              showClose: true,
              message: '密码已过期，请尽快修改！',
              type: 'error'
            });
          }
        }else{
          this.$message({
            showClose: true,
            message: '登录失败,请检查用户名密码是否正确！',
            type: 'error'
          });
          this.draw();
        }
      })
    },
    draw() {
      var canvas_width = this.canvas.width;
      var canvas_height = this.canvas.height;
      var canvas = document.getElementById("myCanvas");//获取到canvas的对象，演员
      var context = canvas.getContext("2d");//获取到canvas画图的环境，演员表演的舞台
      canvas.width = canvas_width;
      canvas.height = canvas_height;
      var sCode = "A,B,C,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0";
      var aCode = sCode.split(",");
      var aLength = aCode.length;//获取到数组的长度

      for (var i = 0; i <= 3; i++) {
        var j = Math.floor(Math.random() * aLength);//获取到随机的索引值
        var deg = Math.random() * 30 * Math.PI / 180;//产生0~30之间的随机弧度
        var txt = aCode[j];//得到随机的一个内容
        this.show_num[i] = txt.toLowerCase();
        var x = 10 + i * 20;//文字在canvas上的x坐标
        var y = 20 + Math.random() * 8;//文字在canvas上的y坐标
        context.font = "bold 23px 微软雅黑";

        context.translate(x, y);
        context.rotate(deg);

        context.fillStyle = this.randomColor();
        context.fillText(txt, 0, 0);

        context.rotate(-deg);
        context.translate(-x, -y);
      }
      for (let i = 0; i <= 5; i++) { //验证码上显示线条
        // context.strokeStyle = this.randomColor();
        // context.beginPath();
        // context.moveTo(Math.random() * canvas_width, Math.random() * canvas_height);
        // context.lineTo(Math.random() * canvas_width, Math.random() * canvas_height);
        // context.stroke();
      }
      for (let i = 0; i <= 30; i++) { //验证码上显示小点
        context.strokeStyle = this.randomColor();
        context.beginPath();
        let x = Math.random() * canvas_width;
        let y = Math.random() * canvas_height;
        context.moveTo(x, y);
        context.lineTo(x + 1, y + 1);
        context.stroke();
      }
    },randomColor() {//得到随机的颜色值
      return "#11E3FF";
      // var r = Math.floor(Math.random() * 256);
      // var g = Math.floor(Math.random() * 256);
      // var b = Math.floor(Math.random() * 256);
      // return "rgb(" + r + "," + g + "," + b + ")";
    },
    formatDate(times){
      var timearr = times.replace(" ", "-").replace(/\-/g, "-").split("-");
      var timestr = "" + timearr[0] + "/" + timearr[1] + "/" + timearr[2]
      //var timestr = "" + timearr[1].split("")[1] + "月" + timearr[2] + "日\t" + timearr[3] + ":" + timearr[4] + ""
      return timestr
    },getDayNum(startTime, endTime){
      const stTime = Date.parse(new Date(startTime))
      const etTime = Date.parse(new Date(endTime))
      const usedTime = etTime - stTime;
      const days = Math.floor(usedTime / (24 * 3600 * 1000));
      return days
    }
  }
}
</script>

<style scoped lang="scss">
#login-right{
  ::v-deep{
    .el-input__inner{
      background-color: #E7EBF7 !important;
      border: 1px solid #C7CBCE !important;
      color: black;
      caret-color: black;
    }
  }
  width: 360px;
  height: 380px;
  border-radius: 3px;
  background-color: #E7EBF7;
  .right_content{
    padding: 20px;
    .single_title{
      padding: 10px 10px;
    }
    .single-input{
      display: flex;
      flex-direction: row;
      padding: 10px;
      .input_type{
        width: 68%;
      }
    }
    .input_login{
      padding-top: 40px;
    }
    .single_login{
      width: 100%;
      background-color: #1a7bb9;
      border-color: #1a7bb9;
      color: #FFFFFF;
    }
  }
}
</style>
