"use strict";
import { khcAlert } from './component/alert/khcAlert.js';
import { util } from './util/util.js'
import {config} from "./config.js";
import {khcToastr} from "./component/alert/khcToastr.js";
import {httpUtil} from "./util/httpUtil.js";
axios.defaults.baseURL = config.getConfigJson().baseURL;
config.getConfigJson().nosessionDownFileYZM=config.getConfigJson().baseURL+config.getConfigJson().contextPath+'/nosession/file/downFileYZM'//这个没走axios，所以补上/api
// 添加响应拦截器
axios.interceptors.response.use( (response)=> {
    //正常状态下的返回值，这个能捕捉到。
    return response;
},  (error) =>{
    return Promise.reject(error);//错误信息不处理，交给全局异常处理
});
window.addEventListener('error', (error) => {
    khcAlert.showSystemError(error.message);
    console.log('全局异常')
    console.log(error)
});
window.addEventListener('unhandledrejection', (error) => {
    if (error.reason.code == "ERR_BAD_RESPONSE") {//后端接口不通异常
        window.location.href=window.location.origin+config.getConfigJson().contextFrontPath+'/index.html'
    } else {
        //其他异常，这个能复现的有当前页面还没渲染完就点击下一个菜单导致捕抓到此异常
        let alertData={title:'操作频繁',text:'请稍后再访问'}
        khcAlert.showSystemError(alertData);
    }
});
let submitButton=document.getElementById('submit');
//Ladda.bind( submitButton, { timeout: 1000 } );
let l = Ladda.create(document.getElementById('submit'));
// 登录按钮单击事件
submitButton.addEventListener('click', ()=>{
    doLogin();
})
// 回车事件
let keyupFunc= (e)=>{
    if(e.keyCode==13){
        doLogin();
    }
}
util.addEventListener(document.body,'keyup',keyupFunc);
document.querySelector('title').innerText=config.getConfigJson().systemFullName+' 登录';//set 系统名称
document.getElementById('systemLogoImgPC').src=config.getConfigJson().logoPath;//set logo 大屏
document.querySelector('link[rel="icon"]').href=config.getConfigJson().iconPath;//set icon
if(config.getConfigJson().loadOutDescription.length>0){
    console.log(config.getConfigJson().loadOutDescription);
}
if(config.getConfigJson().loadOutLink.length>0){
    console.log(config.getConfigJson().loadOutLink,"color:red");
}
isWhiteListIP();
getCaptchaImage();
function isWhiteListIP(){
    let timestamp=new Date().getTime()
    let params={}
    params.nosessionCode='ns_system_config'
    params.methodNameShow="isWhiteListIP";//调试字段
    params.methodName=util.textEncrypt('isWhiteListIP',timestamp,util.getLocalStorageItem('ip'));
    let obj={url:config.getConfigJson().nosessionActionUrl,params:params,config:'no token'}
    httpUtil.post(obj, (response)=> {
        let ip=response.data.data.ip
        console.log(ip)
        util.setLocalStorageItem('ip',ip)
        if(!util.isNull(config.getConfigJson().autocompleteLoginUsername)){
            document.getElementById('username').value=config.getConfigJson().autocompleteLoginUsername
            document.getElementById('password').value=config.getConfigJson().autocompleteLoginPassword
        }
    })
}
let yzmURL='';
function getCaptchaImage(){
    let timestamp=new Date().getTime()
    let params={}
    params.nosessionCode='ns_system_config'
    params.methodNameShow="getCaptchaImage";//调试字段
    params.methodName=util.textEncrypt('getCaptchaImage',timestamp,util.getLocalStorageItem('ip'));
    let obj={url:config.getConfigJson().nosessionActionUrl,params:params,config:'no token'}
    httpUtil.post(obj, (response)=> {
        yzmURL=response.data.data.url;
        let srcUrl=config.getConfigJson().nosessionDownFileYZM+'?fileDiskName='+yzmURL;
        document.getElementById('yzmImg').src=srcUrl;
    })
}
document.getElementById('yzmImg').addEventListener('click', ()=>{
    getCaptchaImage()
})
function doLogin(){
    l.start();
    let username=document.getElementById('username').value;
    let password=document.getElementById('password').value;
    let yzm=document.getElementById('yzm').value;
    if(username.length==0||password.length==0||yzm.length==0){
        setTimeout(function (){
            khcToastr.showErrorMessage('请填写完整的登录信息');
            l.stop();
        },500)
    }else{
        let timestamp=new Date().getTime();
        util.setLocalStorageItem('timestamp',timestamp)
        password=util.passwordEncrypt(password,timestamp,util.getLocalStorageItem('ip'));
        let params = {version: '1.0.0',dsCode:'ds_system_user', username: username,password: password,timestamp:timestamp,yzmURL:yzmURL,yzm:yzm}
        let obj={url:config.getConfigJson().contextPath+'/api/data/login',params:params,config:'no token'}
        obj.errorCallback= (response)=>{
            setTimeout(function (){
                document.getElementById('yzm').value='';
                getCaptchaImage();
                khcToastr.showErrorMessage('登录失败：原因是 '+response.data.message+'('+response.data.status+')');
                l.stop();
            },1000)
        }
        return httpUtil.post(obj,(response)=> {
                if (response.data.status != 'ok') {
                    setTimeout(function (){
                        khcToastr.showErrorMessage(response.data.message);//,text:'错误码：'+response.data.status
                        l.stop();
                    },1000)
                } else {
                    config.setToken(response.data.data.token);
                    let oldUserLoginName=util.getLocalStorageItem('userLoginName');
                    util.setLocalStorageItem('userLoginName',username);
                    let sessionPageCodeValue=util.getSessionStorageItem('pageCode');
                    if (oldUserLoginName!=username||util.isNull(sessionPageCodeValue)) {
                        if(!util.isNull(response.data.data.redirect_url)){
                            window.location.href=response.data.data.redirect_url;
                        }else{
                            util.setSessionStorageItem('pageCode','');
                            window.location.href=config.getIndexUrl();
                        }
                    }else{
                        let url=config.getIndexUrl()+sessionPageCodeValue
                        window.location.href = url
                    }
                }
            })
    }
}