import { Modal, message } from 'antd'
const confirm = Modal.confirm;
import { WeaTools, WeaLocaleProvider } from 'ecCom';
import {WeaLicenseSubmit} from 'weaPortalPublic';
const getLabel = WeaLocaleProvider.getLabel;
import {i18n} from '../public/i18n';
import * as mobx from 'mobx';

import LoginPluginFactory from './plugin/loginPluginFactory'

const toJS = mobx.toJS;
const { ua } = WeaTools;
const isIE9 = (ua.browser === "IE");

const getLoginForm = (params) => {
    const { langid, callback } = params;
    window.currLanguageId = langid;
    let loginid = params.loginid || '';
    if (loginid == '') {
        loginid = jQuery('#loginid').val();
    }

    let loginFormItems = [];
    let loginFormHiddenItems = [];
    let loginSetting = {};
    let qrCode = {};
    let hasMultiLang = false;

    loginFormItems = [
        { label: '账号', atype: 'account', id: 'loginid', name: 'loginid', type: 'text' },
        { label: '密码', atype: 'password', id: 'userpassword', name: 'userpassword', type: 'password'},
    ];
    WeaTools.callApi('/api/hrm/login/getLoginForm', 'POST', { loginid, langid }).then((result) => {
        // loginFormItems = [
        //     {label: '账号', atype: 'account', id: 'loginid', name: 'loginid', type: 'text'},
        //     {label: '密码', atype: 'password', id: 'userpassword', name: 'userpassword', type: 'password'},
        //     {label: '验证码', atype: 'validatecode', id: 'validatecode', name: 'validatecode', type: 'text'},
        //     {label: '动态令牌口令', atype: 'common', id: 'tokenAuthKey', name: 'tokenAuthKey', type: 'text'}
        // ];
        loginFormItems = result.formItems;
        loginSetting = result.loginSetting;
        qrCode = result.qrcode;
        hasMultiLang = loginSetting.hasMultiLang;
        loginFormHiddenItems = [
            { html: '<input type="hidden" id="messages" name="messages" value="">' }
        ];

        new LoginPluginFactory().getLocalPlugin(result,()=>{
            window.loginPlugin && window.loginPlugin.init() ;
        })

        if (callback && typeof callback == 'function') callback({ hasMultiLang, loginFormItems, loginFormHiddenItems, loginSetting,qrCode });
    }).catch((err) => {
        message.error(err);
        if (callback && typeof callback == 'function') callback({ hasMultiLang, loginFormItems, loginFormHiddenItems, loginSetting,qrCode });
    });
};

const login = (params) => {
    const {openRSA} = params.loginSetting;
    const loginid = jQuery('#loginid').val();
    let userpassword = jQuery('#userpassword').val();
    if(openRSA && openRSA=='1'){//启用RSA加密
        __RSAEcrypt__.refreshRsaCode(function(){
            loginSync(params);
        });
    }else{
        loginSync(params);
    }
};

const loginSync = (params) => {
    const { userUsbType, hasMultiLang, hasValidateCode, validateCodeKey, numValidateWrong, validateType, showDynamicPwd,openRSA} = params.loginSetting;
    let { langid, success, failure, logintype, queryParams} = params;
    const loginid = jQuery('#loginid').val();
    let userpassword = jQuery('#userpassword').val();
    let userpasswordRsa = userpassword;
    if(openRSA && openRSA=='1'){//启用RSA加密
        userpasswordRsa = __RSAEcrypt__.rsa_data_encrypt(userpassword);
       // jQuery('#userpassword').val(userpassword);
    }
    
    const tokenAuthKey = jQuery('#tokenAuthKey') ? jQuery('#tokenAuthKey').val() : '';
    const validatecode = jQuery('#validatecode') ? jQuery('#validatecode').val() : '';
    const messages = jQuery('#messages') ? jQuery('#messages').val() : '';
    if (loginid == '' || userpassword == '') {
        message.error(getLabel('386478',"请输入用户名、密码"), 3);
        if (failure && typeof failure == 'function') failure();
        return;
    }

    if (hasValidateCode && validatecode == '') {
        message.error(getLabel('84270',"请输入验证码"), 3);
        if (failure && typeof failure == 'function') failure();
        return;
    }

    if (userUsbType == '3') {
        if (tokenAuthKey == '') {
            message.warning(getLabel('84271',"请输入动态令牌口令"));
            if (failure && typeof failure == 'function') failure();
            return;
        } else if (!isdigit(tokenAuthKey) || tokenAuthKey.length != 6) {
            message.warning(getLabel('386435',"动态令牌口令必须为6位数字！"));
            if (failure && typeof failure == 'function') failure();
            return;
        }
    }

    queryParams = toJS(queryParams);
    if(queryParams && queryParams.appid && queryParams.service){
        queryParams.loginid=loginid;
        queryParams.userpassword=userpassword;
        let tmps = [];  
        jQuery("body").append("<form name='ssoForm'></form>");
        let form = jQuery("form[name='ssoForm']")
        form.attr("action", '/login/VerifyLoginWeaversso.jsp');
        form.attr("method", "post");
        form.attr("style", "display:none");
        for (let key in queryParams) {  
            form.append("<input type='text' name='" + key + "' value = '" + queryParams[key] + "'></input>");
        }  
        //跳转到sso
        form.submit();
        return;
    }

    const {plugin} = params 

    WeaTools.callApi('/api/hrm/login/checkLogin', 'POST', {
        islanguid: langid,
        loginid: loginid,
        userpassword: userpasswordRsa,
        tokenAuthKey: tokenAuthKey,
        validatecode: validatecode,
        validateCodeKey:validateCodeKey,
        logintype: logintype,
        messages: messages,
        isie: isIE9,
        ...plugin
    }).then((result) => {
        if ('access_token' in result && typeof result.access_token === 'string' && result.access_token !== '') {
            localStorage.setItem('access_token', result.access_token);
        } else {
            localStorage.access_token && localStorage.removeItem('access_token');
        }

        if(result.user_token && result.user_token!=''){
            userpassword = result.user_token;
        }

        if (result.loginstatus == 'true' || result.msgcode == '101') {
            if (result.msgcode == '101') {
                let vNumber = result.validitySec
                jQuery("#messages").val(result.msgcode);
                let interval = setInterval(() => {
                    if (jQuery('#errorMessage').length == 0) {//跳转后不再刷新
                        clearInterval(interval);
                    }
                    //console.log("跳转后不再刷新")
                    if (vNumber == 0) {
                        clearInterval(interval);
                        jQuery('#errorMessage').html(getLabel('84255',"动态密码已过期，请重新登录"));
                    } else {
                        jQuery('#errorMessage').html(`${getLabel('20289',"请输入动态密码")}（${vNumber--}）`);
                    }
                }, 1000);
                message.error(<span id='errorMessage'>{getLabel('20289',"请输入动态密码")}（{vNumber}）</span>, Number(result.validitySec) + 5);
                jQuery('#userpassword').val("");
                if (failure && typeof failure == 'function') failure({reflashValidateCode:true});
            } else {
                if (success && typeof success == 'function') {
                    message.destroy();
                    WeaTools.callApi('/api/hrm/login/remindLogin', 'POST', {logintype: logintype}).then((result) => {
                        if (result.status == '1') {
                            if (result.isUpPswd == 'true') {
                                if (failure && typeof failure == 'function') failure({reflashValidateCode:true});
                                confirm({
                                    title: i18n.confirm.systemhints(),
                                    content: getLabel('81626',"首次登录需修改密码！"),
                                    onOk() {
                                        if (failure && typeof failure == 'function') failure({reflashValidateCode:true});
                                        showDialog("", `/spa/hrm/index_mobx.html#/main/hrm/password`, { width: 800, height: 500 });
                                        return;
                                    },
                                    onCancel() {
                                        if (failure && typeof failure == 'function') failure({reflashValidateCode:true});
                                        WeaTools.callApi('/api/hrm/login/checkLogout', 'POST', {}).then((result) => { });
                                        return;
                                    },
                                });
                            } else {
                                if (result.passwdReminder == '1') {
                                    if (result.canpass == '1') {
                                        if (result.canremind == '1') {
                                            const content = getLabel('386479',"您的密码还有{params}天过期,是否现在修改?").replace('{params}', result.passwdelse);
                                            confirm({
                                                title: i18n.confirm.systemhints(),
                                                content,
                                                onOk() {
                                                    if (failure && typeof failure == 'function') failure({reflashValidateCode:true});
                                                    showDialog("", `/spa/hrm/index_mobx.html#/main/hrm/password`, { width: 800, height: 500 });
                                                    return;
                                                },
                                                onCancel() {
                                                    success(loginid, userpassword, result);
                                                },
                                            });
                                        } else {
                                            success(loginid, userpassword, result);
                                        }
                                    } else {
                                        confirm({
                                            title: i18n.confirm.systemhints(),
                                            content: getLabel('386480',"您的密码已经过期,请立即修改！"),
                                            onOk() {
                                                if (failure && typeof failure == 'function') failure({reflashValidateCode:true});
                                                showDialog("", `/spa/hrm/index_mobx.html#/main/hrm/password`, { width: 800, height: 500 });
                                                return;
                                            },
                                            onCancel() {
                                                if (failure && typeof failure == 'function') failure({reflashValidateCode:true});
                                                WeaTools.callApi('/api/hrm/login/checkLogout', 'POST', {}).then((result) => { });
                                                return;
                                            },
                                        });
                                    }
                                } else {
                                    success(loginid, userpassword, result);
                                }
                            }
                        }
                    });
                }
            }
        } else {
            if (failure && typeof failure == 'function') failure({reflashValidateCode:true});
            message.destroy();
            if (result.msgcode == '57') {
                jQuery('#userpassword').val("");
            }

            let errorMsg = result.msg || getLabel('386481',"登录失败");
            let errorUrl = '';
            let errorText = '';

            if (result.msgcode == '120') {
                errorUrl = '/spa/hrm/index_mobx.html#/main/hrm/BindTokenKey?langid='+langid;
                errorText = getLabel('386125',"令牌绑定");
            } else if (result.msgcode == '122') {
                errorUrl = '/spa/hrm/index_mobx.html#/main/hrm/BindTokenKey?syncTokenKey=1&langid='+langid;
                errorText = getLabel('129202',"令牌同步");
            } else if (result.msgcode == '19') {
                // errorText = "提交License";
                // window.location.href = '/system/InLicense.jsp';
                const div = document.createElement('div');
                document.body.appendChild(div);
                ReactDOM.render(<WeaLicenseSubmit ecId={`${this && this.props && this.props.ecId || ''}_WeaLicenseSubmit@skc4bu`} visible={true} from="login" />, div);
                return;
            }


            // 返回错误信息提示
            message.error((
                <span>
                    {errorMsg}
                    {errorUrl ? (
                        <span style={{ marginLeft: '5px', color: '#00a9ff', cursor: 'pointer' }} onClick={() => showDialog('', errorUrl, { width: 800, height: 465 })}>{errorText}</span>
                    ) : ''
                    }
                </span>
            ), 5);
        }
    });
};

const showDialog = (title, url, style, callback, onCancel) => {
    style=style||{ width: 800, height: 465 };
    const dialog = ecCom.WeaTools.createDialog({ moduleName: 'hrm', title, url, style, callback, onCancel });
    dialog.show();
};

const isdigit = (s) => {
    var r, re;
    re = /\d*/i; //\d表示数字,*表示匹配多个数字
    r = s.match(re);
    return (r == s) ? true : false;
}

// 提供登录相关的全局方法
window.doLoginAction = (actionName, params) => {
    if (actionName == 'getLoginForm') {
        const { langid } = params;
        if(langid && langid!='7'){
            WeaLocaleProvider.getLocaleLabelByLang(['common', 'hrm'], langid).then(()=>{
                getLoginForm(params);
            })
        }else{
            getLoginForm(params);
        }
    } else if (actionName == 'login') {
        window.loginPlugin.willLogin(params,login)
    } else if(actionName == 'forgetPassword'){
        const url = `/spa/hrm/index_mobx.html#/main/hrm/forgetPassword?langid=${window.currLanguageId}`;//`/#/main/hrm/forgetPassword?langid=${window.currLanguageId}`;//`/spa/hrm/index_mobx.html#/main/hrm/forgetPassword?langid=${window.currLanguageId}`
        showDialog(getLabel('127899',"找回密码"), url, { width: 600, height: 245 });
    }
};
//window.doLoginAction('forgetPassword')