<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 psd">
        <el-input id="password" 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>
        <el-button class="single_login" @click="loginIn('2')">游客</el-button>
      </div>

    </div>


  </div>
</template>

<script>
import {Base64} from "js-base64";
import {editLoginState,loginIn} from "@/service/login";
import {ElMessageBox} from "element-plus";
import {showMessage} from "@/units/element-ui/tip";
import {useRootStore} from "@/pinia/useStore";

export default {
  name: "LoginRight",
  //inject:['globalInfo'],
  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.globalInfo.operationTimer);
  },

  methods:{
    // ...mapLoginUserMutations({
    //   'changeUserInfo':'changeUserInfo'
    // }),
    setOperationTime(){
      // this.$global.operationTimer = setInterval(() => {
      //   //登录成功后修改用户登录唯一标识
      //   updateLoginLasttime().then(response => {
      //     var date = response.msg;
      //     if (date[0]["success"] == "true") {
      //       return;
      //     } else {
      //       return;
      //     }
      //   });
      // }, 10000);
    },
    loginIn(type){
        let store = useRootStore()
        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 = "请输入用户名!";
        }
        let username;
        let password;
      if(type=='2'){
        username = 'youke';
        password = '123456';
      }else{
        if(this.message_text != null){

          showMessage({
            type:"warning",
            message:this.message_text
          })
          this.draw();
          return;
        }
        username = this.loginForm.userName;
        password = this.loginForm.passWord;
      }
        loginIn(username,Base64.encode(password)).then(data =>{

          var result = data.msg;

          var rows = result[0].Rows;
          if (result.length == 0) {
            showMessage({
              type:'error',
              message:'获取登录信息失败'
            })
            this.draw()
            return;
          }
          var rowcount = result[0].TotalRowCount;
          if (rowcount != "1") {
            showMessage({
              type:'error',
              message:'用户名或密码错误'
            })
            this.draw()
            return;
          }
          if (rows.length != 1) {
            showMessage({
              type:'error',
              message:'用户名或密码错误'
            })
            this.draw()
            return;
          }
          // if (rows[0].USERNAME != "PTGL"
          //    && rows[0].USERNAME != "ADMIN"
          //    && rows[0].USERNAME != "ptgl"
          //    && rows[0].USERNAME != "admin") {
          //    layerAlert("系统提示", "无登录权限！", null, 2);
          //    return;
          // }
          // if (rows[0].USERNAME == "jptgl") {
          //   showMessage({
          //     type:'error',
          //     message:'无登录权限'
          //   })
          //   this.draw()
          //   return;
          // }
          // if (rows[0].ROLE_CODE != "0"
          //     && rows[0].ROLE_CODE != "1" && rows[0].ROLE_CODE != "12") {
          //   showMessage({
          //     type:'error',
          //     message:'无登录权限'
          //   })
          //   this.draw()
          //   return;
          // }
          var LOGIN_LOCK = rows[0]["LOGIN_LOCK"];
          if (LOGIN_LOCK == 1) {
            var time = new Date(rows[0]["GETTIME"]).getTime() - new Date(rows[0]["LAST_TIME"]).getTime();
            time = time / 1000;
            if (time < 20) {
              showMessage({
                type:'error',
                message:'当前用户已登录'
              })
              this.draw()
              return;
            }
          }

          //获取用户信息
          var usercode = rows[0].USERID;
          var username = rows[0].USERNAME;
          var truename = rows[0].NAME;
          var unitcode = rows[0].UNIT;
          var unitname = rows[0].UNIT_NAME;
          var lasttime = rows[0].LAST_TIME;
          var password = Base64.encode(this.loginForm.passWord)
          var change_time = rows[0].CHANGE_TIME;
          var role = rows[0].ROLE_CODE;
          var userkeycode = rows[0]["TEMPUSERKEYCODE"];

          //保存用户信息

          editLoginState(usercode,userkeycode).then(res =>{

            var date = res.msg;
            if (date[0]["success"] == "true") {
              localStorage.setItem("xyxx_usercode", usercode);
              localStorage.setItem("xyxx_username", username);
              localStorage.setItem("xyxx_unitcode", unitcode);
              localStorage.setItem("xyxx_unitname", unitname);
              localStorage.setItem("xyxx_password", password);
              localStorage.setItem("xyxx_lasttime", lasttime);
              localStorage.setItem("xyxx_changetime", change_time);
              localStorage.setItem("xyxx_role", role);
              localStorage.setItem("xyxx_userkeycode", userkeycode);
              localStorage.setItem("xyxx-part", '');
              store.userInfo = {
                xyxx_usercode:usercode,
                xyxx_username:username,
                xyxx_unitcode:unitcode,
                xyxx_unitname:unitname,
                xyxx_password:password,
                xyxx_lasttime:lasttime,
                xyxx_changetime:change_time,
                xyxx_role:role,
                xyxx_userkeycode:userkeycode
              }
              localStorage.setItem('dataWatchLoginUserInfo',JSON.stringify(store.userInfo))
              this.$router.push('/main')

              //user.InsertSyslog(unitcode, usercode, "系统登录", "政务管理-登录", "登录系统成功");
              //切换首页
              //parent.location.href = 'index.html';
              return;
            } else {
              ElMessageBox.alert('登录失败！', '提示', {
                confirmButtonText: '确定'
              });
              this.draw();
              return;
            }
          })
          this.setOperationTime();

        })
    },
    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 glyphicons = Math.floor(Math.random() * 256);
      // var b = Math.floor(Math.random() * 256);
      // return "rgb(" + r + "," + glyphicons + "," + 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  lang="scss" scoped>
#login-right{

  :deep(.el-input__wrapper){
    padding: 0;

  }
  .single-input{

    &.psd{
      position:relative;
      :deep(.el-input__inner){
        padding-right: 30px;
      }
    }
    &.el-input__wrapper{

    }
    :deep(.el-input__suffix-inner){
      right: 6px;
      top: 12px;
      position: absolute;
      background-color:  #E7EBF7 !important;
    }
    :deep(.el-input__inner){
      height: 38px;
      background-color:  #E7EBF7 !important;
      //background-color: #E7EBF7 !important;
      border: 1px solid #C7CBCE !important;
      color: black;
      box-sizing: border-box;
      padding: 0 15px;
      width: 100%;
      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;
      flex-wrap: wrap;
      .input_type{
        width: 68%;
      }
    }
    .input_login{
      padding-top: 40px;
    }
    .single_login{
      width: 100%;
      margin: 10px;
      background-color: #1a7bb9;
      border-color: #1a7bb9;
      color: #FFFFFF;
    }
  }
}
</style>
