const $ = require('jquery');
require("../css/reset.less")
require("../css/login.less")
require("./modal.js")
const {api} = require('./api.js')

const {post,setCookie,delCookie} = require('../js/utils.js');
const md5 = require('js-md5');
$(function(){
  delCookie('accessToken')
  $(document).keyup(function(event){  
    if(event.keyCode ==13){  
      sureLogin()
    }  
  }); 
  $(".sureLogin").click(()=>{
    sureLogin()
  })
  $("#password").focus(function(){
    $(this).attr("type","password")
  })
  $(".iptWrap input").focus(function(){
    $(this).parent().addClass('inputFocus')
  })
  $(".iptWrap input").blur(function(){
    $(this).parent().removeClass('inputFocus')
  })
  $("body").on('input','#username,#password',function(){
    if($(this).val().trim() != ''){
      $(".login .waring").html('')
    }
  })
});
function sureLogin(){
  $(".login .waring").html('')
  localStorage.removeItem('accessToken')
  let username = $("#username").val().trim();
  let password = $("#password").val().trim();
  if(!username){
    $(".login .waring").css('display','block').html('请输入用户名')
    return
  }else if(!password){
    $(".login .waring").css('display','block').html('请输入密码')
    return
  }
  $.alerModal({type:"loading"});
  post(api.getJwt,{
    username:username,
    password:md5(password)
  }).then((res)=>{
    const data = res.data;
    if(data.code == 0){
      setCookie('accessToken',data.data.accessToken)
     
      localStorage.setItem('accessToken',data.data.accessToken)
      $(".divModal").remove()
      $.alerModal({"message":"登录成功",type:"tip",time:'1000'});
      setTimeout(() => {
        window.location.href = '/index.html'
      }, 600);
    }else{
      $(".divModal").remove()
      $(".login .waring").css('display','block').html(data.msg)
    }
  }).catch(()=>{
    $(".divModal").remove()
  })
}