/**
 * common js of app(web).
 * The following is written.
 * 1.language
 * 2.loading
 * 3.alert
 * 4.url
 * 5.cms communication
 * 6.check if user is logged in
 *
 * @since cms:1.4.3.2&1.4.3.3 web:1.0
 */
var CHK_Common = {};

CHK_Common.lang;

/**
 * get lang code in local storage
 * web gets lang form local storage
 * but app gets lnag from session storage
 */
CHK_Common.setLangCodeWeb = function () {
    let lang = CHK_Common.getLangWeb();
    if (lang.split('-')[0] == CONSTANT.LANG.English) {
        lang = CONSTANT.LANG.ENGLISH;
    } else if (lang.split('-')[0] == CONSTANT.LANG.KOREA) {
        lang = CONSTANT.LANG.KOREA;
    } else {
        lang = CONSTANT.LANG.JAPAN;
    }
    CHK_Common.lang = lang;
};

/**
 * get lang in local storage
 *
 * @returns String pageLang
 */
CHK_Common.getLangWeb = function () {
    if (!CHK_Common.lang) {
        let pageLang;
        if (localStorage[CONSTANT.LANG.SAVE_NAME]) {
            pageLang = localStorage[CONSTANT.LANG.SAVE_NAME];
        } else {
            pageLang = (window.navigator.languages && window.navigator.languages[0]) || window.navigator.language || window.navigator.userLanguage || window.navigator.browserLanguage;
            localStorage[CONSTANT.LANG.SAVE_NAME] = pageLang;
        }
        return pageLang;
    } else {
        return CHK_Common.lang;
    }

    return pageLang;
};

/**
 * change lang of html
 */
CHK_Common.updateLang = function () {
    $('.multi-lang').each(function () {
        const key = $(this).attr('data-msg');
        if (key) {
            if ($(this).prop('tagName').toLowerCase() == 'input' && ($(this).attr('type') == 'text' || $(this).attr('type') == 'search')) {
                const attr = $(this).attr('placeholder');
                if (typeof attr !== 'undefined' && attr !== false) {
                    $(this).attr('placeholder', CHK_Common.getMsg(key));
                } else {
                    $(this).val(CHK_Common.getMsg(key));
                }
            } else {
                $(this).html(CHK_Common.getMsg(key));
            }
        }
    });
};

/**
 * get any lang msg from CHK_Common.msgMap
 *
 * @param String key
 * @returns String msg
 */
CHK_Common.getMsg = function (key) {
    const msg = CONSTANT.MSG_MAP[key];
    if (!msg) {
        return '';
    }

    return msg[CHK_Common.lang];
};

/**
 * show loading dialog
 * show msg by key
 *
 * @param {String} key
 */
CHK_Common.showLoading = function () {
    $('#check_loading').dialog({
        dialogClass: 'noTitleDialog ui-dialog-titlebar dialogNoBorder', //cssを追加する必要がある
        autoOpen: false,
        resizable: false,
        modal: true,
        width: '100%',
        title: ' ',
        open: function (e) {
            $(e.target).parent().css('background-color', 'rgba(128,128,128)');
            $(e.target).parent().css('position', 'absolute');
            $(e.target).parent().css('left', '50%');
            $(e.target).parent().css('top', '25vh');
            $(e.target).parent().css('transform', 'translateX(-50%)');
            $(e.target).parent().css('-webkit- transform', 'translateY(-50%) translateX(-50%)');
            $(e.target).parent().children('.ui-dialog-buttonpane').css('background-color', 'rgba(128,128,128)').css('border', 'none');
        },
        close: function () {},
    });

    $('#check_loading').dialog('open');
};

/**
 * close loading
 */
CHK_Common.closeLoading = function () {
    if ($('#check_loading').hasClass('ui-dialog-content')) {
        $('#check_loading').dialog('close');
    }
};

/**
 * show alert
 *
 * @param {String} msgCode
 */
CHK_Common.displayAlert = function (msgCode, title) {
    $('#alertMsg').html(CHK_Common.getMsg(msgCode));
    $('.alert-overlay').removeClass('d-none');
    $('.alert-area').removeClass('d-none');

    const positionY = $(document).scrollTop() + screen.height / 8;
    const height = screen.height / 4;
    $('.alert-overlay').css('height', screen.height);
    $('.alert-area').css('top', positionY);
    $('.alert-area').css('min-height', height);
    $('body').css('overflow', 'hidden');
};

/**
 * close alert
 */
CHK_Common.alertClose = function () {
    $('.alert-overlay').addClass('d-none');
    $('.alert-area').addClass('d-none');
    $('body').css('overflow', 'visible');
};

/**
 * go Url page With Current Params
 *
 * ios will remove all web types data when reopen webview
 * need add common parameters: app, lang, debug, mobile_flg, isChat, ...
 *
 * @param {String} url
 * @param {Object} params
 */
CHK_Common.goUrlWithCurrentParams = function (url, params) {
    if (!params) {
        location.href = CONSTANT.URL.BASE_WEB + url;
    }

    const mixParams = Object.assign(CHK_Common.getUrlParameter(), params);
    if (url.includes('?')) {
        location.href = url + '&' + new URLSearchParams(mixParams);
    } else {
        location.href = url + '?' + new URLSearchParams(mixParams);
    }
};

/**
 * get url parameter
 *
 */
CHK_Common.getUrlParameter = function () {
    var ret = {};
    if (location.search) {
        var param = {};
        location.search
            .substring(1)
            .split('&')
            .forEach(function (val) {
                var kv = val.split('=');
                param[kv[0]] = kv[1];
            });
        ret = param;
    }
    console.log({ ret: ret });
    return ret;
};

/**
 * get sid in local Storage
 *
 * @returns sid
 */
CHK_Common.getSid = function () {
    return ClientData.userInfo_sid_local();
};

/**
 * cms communication
 *
 * @param {String} url
 * @param {Json} param
 * @param {boolean} async
 * @param {Object} callback
 * @param {Object} errorCallback
 */
CHK_Common.cmsAjax = function (url, param, async = true, callback, errorCallback) {
    if (url) {
        $.ajax({
            type: 'POST',
            url: url,
            data: param,
            dataType: 'json',
            cache: false,
            async: async,
            success: function (result) {
                if (result.status == '200') {
                    if (callback) callback(result);
                } else if (result.status == '401') {
                    CHK_Common.goUrlWithCurrentParams(CONSTANT.PAGE_NAME.LOGIN);
                } else if (errorCallback) {
                    errorCallback();
                } else {
                    CHK_Common.closeLoading();
                    CHK_Common.displayAlert(result.message);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (errorCallback) {
                    errorCallback();
                } else {
                    CHK_Common.closeLoading();
                    CHK_Common.displayAlert('errorCommunicationFailed');
                }
            },
        });
    } else {
        if (errorCallback) {
            errorCallback();
        } else {
            CHK_Common.closeLoading();
            CHK_Common.displayAlert('errorOccurred');
        }
    }
};

/**
 * Communicate with cms and post
 *
 * @param {String} url
 * @param {Object} params
 * @param {String} method
 */
CHK_Common.postCommunication = function (url, params, method = 'post') {
    const form = document.createElement('form');
    form.method = method;
    form.action = url;

    for (const key in params) {
        if (params.hasOwnProperty(key)) {
            const hiddenField = document.createElement('input');
            hiddenField.type = 'hidden';
            hiddenField.name = key;
            hiddenField.value = params[key];
            form.appendChild(hiddenField);
        }
    }

    document.body.appendChild(form);
    form.submit();
};

/**
 * Check if user is logged in
 *
 * @param {boolean} async
 */
CHK_Common.checkAuth = function (async = true) {
    let params = {};
    params.sid = CHK_Common.getSid;
    const url = CONSTANT.URL.BASE_CMS + CONSTANT.URL.AUTH_SESSION;
    CHK_Common.cmsAjax(url, params, async, null, function () {
        CHK_Common.goUrlWithCurrentParams(CONSTANT.PAGE_NAME.LOGIN);
    });
};
