<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>-->
        <el-image  @click="draw" :src="url" class="login_img" />
      </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 {editLoginState, getLoginImg, loginIn} from "@/service/show-platform";

import {showConfirm, showMessage} from "@/unit/element-ui/tip";
import {useRootStore} from "@/stores/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:""
      },
      url:""
    }
  },
  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);
    },
    confirmLogin(rows){
      const store=  useRootStore()
      //获取用户信息
      var usercode = rows[0].USERID;
      var username = rows[0].USERNAME;

      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"];
      var ROLE_UUID = rows[0]["ROLE_UUID"];


      //保存用户信息

      editLoginState(usercode,userkeycode,'1').then(async res =>{
        let isSuccess = false

        try {
          var date = res.msg;
          if (date[0]["success"] == "true"){
            isSuccess = true
          }
        }catch {
          isSuccess = false
        }

        if (isSuccess) {
          store.userInfo = {
            ptjk_usercode:usercode,
            ptjk_username:username,
            ptjk_unitcode:unitcode,
            ptjk_unitname:unitname,
            //ptjk_password:password,
            ptjk_lasttime:lasttime,
            ptjk_changetime:change_time,
            ptjk_role:role,
           ' ptjk-part':'',
            ptjk_userkeycode:userkeycode,
            ptjk_role_uuid:ROLE_UUID
          }
          localStorage.setItem('dataWatchLoginUserInfo',JSON.stringify(store.userInfo))
          // this.$router.push('/other/data-watch')
          const rootPiniaStore = useRootStore()

          await rootPiniaStore.getLoginUserInfo(store.userInfo)

          var myDate = new Date();
          var now_date = myDate.toLocaleDateString()   //直接获取当前的年月日        2017/10/19
          var change_date = this.formatDate(store.userInfo.ptjk_changetime);
          var days = this.getDayNum(change_date, now_date);
          if (days > 90) {
            showMessage({
              showClose: true,
              message: '密码已过期，请尽快修改！',
              type: 'error'
            });
          }
          showMessage({
            type:'success',
            message:'登录成功'
          })
          this.$router.push({
            name:'home'
          })
          //user.InsertSyslog(unitcode, usercode, "系统登录", "政务管理-登录", "登录系统成功");
          //切换首页
          //parent.location.href = 'index.html';

        } else {
          showMessage({
            type:'error',
            message:'登录失败'
          })

          this.draw();
          return;
        }
      })
      this.setOperationTime();
    },
    loginIn(){
      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 = "请输入用户名!";
      }
      if(this.message_text != null){

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

        var result
        var rows
        try {
          result = data.msg;
         rows = result[0].Rows;
        }
        catch {
          showMessage({
            type:'error',
            message:'登录失败'
          })

          this.draw();
          return;
        }


        if (result.length == 0) {
          showMessage({
            type:'error',
            message:'登录失败'
          })
          this.draw()
          return;
        }
        var rowcount = result[0].TotalRowCount;
        if (rowcount != "1" || rows.length != 1) {
          showMessage({
            type:'error',
            message:'登录失败'
          })
          this.draw()
          return;
        }
        var time2 = new Date(rows[0]["GETTIME"]).getTime() - new Date(rows[0]["LAST_TIME"]).getTime();
        console.log('time2',time2)

        if (time2<=15*60*1000){

          if (+rows[0].LOGIN_COUNT>0){
            if (+rows[0].LOGIN_COUNT<5){
              showMessage({
                type:'error',
                message:`密码错误${+rows[0].LOGIN_COUNT}次,5次将锁定账号`
              })

            }else {
              showMessage({
                type:'error',
                message:'账号已锁定，请15分钟后重试'
              })
            }
            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) {

            showConfirm(() => {
              this.confirmLogin(rows)
            },'当前用户已登录！是否继续登录','系统提示',{
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            })
          }else {
            this.confirmLogin(rows)
          }
        }
        else {
          this.confirmLogin(rows)

        }




      })
    },
    draw() {
      getLoginImg().then(res =>{
        const blob = new Blob([res], { type: "image/png" });
        // 创建URL对象
        this.url = URL.createObjectURL(blob);
      })
    },
    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;
      .input_type{
        width: 68%;
      }
      .login_img{
        width: 90px;
        height: 40px;
      }
    }
    .input_login{
      padding-top: 40px;
    }
    .single_login{
      width: 100%;
      background-color: #1a7bb9;
      border-color: #1a7bb9;
      color: #FFFFFF;
    }
  }
}
</style>
