"use strict";
import { khcToastr } from './component/alert/khcToastr.js';
import { util } from './util/util.js';
import { config } from './config.js';
import { khcAlert } from './component/alert/khcAlert.js';
import { httpUtil } from './util/httpUtil.js';
config.getConfigJson().baseURL='';
axios.defaults.baseURL = config.getConfigJson().baseURL;
config.getConfigJson().nosessionDownFileYZM = config.getConfigJson().baseURL + config.getConfigJson().contextPath + '/nosession/file/downFileYZM';

axios.interceptors.response.use((response) => response, (error) => Promise.reject(error));

window.addEventListener('error', (error) => {
    khcAlert.showSystemError(error.message);
});

window.addEventListener('unhandledrejection', (error) => {
    if (error?.reason?.code === 'ERR_BAD_RESPONSE') {
        window.location.href = window.location.origin + config.getConfigJson().contextFrontPath + '/index.html';
    } else {
        khcAlert.showSystemError({ title: '操作频繁', text: '请稍后再访问' });
    }
});

const submitButton = document.getElementById('submit');
const loginButton = Ladda.create(submitButton);
let yzmURL = '';

submitButton.addEventListener('click', doLogin);
util.addEventListener(document.body, 'keyup', (e) => {
    if (e.keyCode === 13) {
        doLogin();
    }
});

document.querySelector('title').innerText = config.getConfigJson().systemFullName + ' 登录';
document.getElementById('systemLogoImgPC').src = config.getConfigJson().logoPath;
document.querySelector('link[rel="icon"]').href = config.getConfigJson().iconPath;

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();

document.getElementById('yzmImg').addEventListener('click', () => {
    getCaptchaImage();
});

function isWhiteListIP() {
    const timestamp = new Date().getTime();
    const params = {};
    params.nosessionCode = 'ns_system_config';
    params.methodNameShow = 'isWhiteListIP';
    params.methodName = util.textEncrypt('isWhiteListIP', timestamp, util.getLocalStorageItem('ip'));
    const obj = { url: config.getConfigJson().nosessionActionUrl, params, config: 'no token' };
    httpUtil.post(obj, (response) => {
        const ip = response.data.data.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;
        }
    });
}

function getCaptchaImage() {
    const timestamp = new Date().getTime();
    const params = {};
    params.nosessionCode = 'ns_system_config';
    params.methodNameShow = 'getCaptchaImage';
    params.methodName = util.textEncrypt('getCaptchaImage', timestamp, util.getLocalStorageItem('ip'));
    const obj = { url: config.getConfigJson().nosessionActionUrl, params, config: 'no token' };
    httpUtil.post(obj, (response) => {
        yzmURL = response.data.data.url;
        let yzm=response.data.data.yzm;
        const srcUrl = config.getConfigJson().nosessionDownFileYZM + '?fileDiskName=' + yzmURL;
        document.getElementById('yzmImg').src = srcUrl;
        if(!util.isNull(yzm)){
            document.getElementById('yzm').value=yzm;
        }
    });
}

function doLogin() {
    loginButton.start();

    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    const yzm = document.getElementById('yzm').value;

    if (username.length === 0 || password.length === 0 || yzm.length === 0) {
        setTimeout(() => {
            khcToastr.showErrorMessage('请填写完整的登录信息');
            loginButton.stop();
        }, 300);
        return;
    }

    const timestamp = new Date().getTime();
    util.setLocalStorageItem('timestamp', timestamp);

    const params = {
        version: '1.0.0',
        dsCode: 'ds_system_user',
        username: username,
        password: util.passwordEncrypt(password, timestamp, util.getLocalStorageItem('ip')),
        timestamp: timestamp,
        yzmURL: yzmURL,
        yzm: yzm
    };

    axios.post(config.getConfigJson().contextPath + '/session/doLogin', params, {
        headers: {
            'Content-Type': 'application/json'
        },
        withCredentials: true
    }).then((response) => {
        const data = response.data;
        if (data && data.status !== 'ok') {
            khcToastr.showErrorMessage(data.message || '登录失败');
            document.getElementById('yzm').value = '';
            getCaptchaImage();
            return;
        }
        window.location.href=config.getConfigJson().contextPath + '/session/index';
    }).catch((error) => {
        document.getElementById('yzm').value = '';
        getCaptchaImage();
        const msg = error?.response?.data?.message || error.message || '登录失败';
        khcToastr.showErrorMessage(msg);
    }).finally(() => {
        loginButton.stop();
    });
}
