$(document).on('keydown','.decimal', function (event) {
    handleEnterPressedinNormalCell(event, function() {})
}).on('focusout','.decimal', function () {
    $(this).val(format_decimal(minusComma($(this).val()), $(this).data('point')))
});

const CheckDecimal = x => {
    const realStringObj = obj && obj.toString();
    if (!jQuery.isArray(obj) && (realStringObj - parseFloat(realStringObj) + 1) >= 0) return false;

    const parts = x.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
}

const CheckMail = email => {
    const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    const result = re.test(String(email).toLowerCase());
    // !result && alert('Email is invalid !!!', 'error');
    return result;
}

const CheckNum = input => !isNaN(input);

const LenCheck = (input, length) => {
    return input.length <= length;
}

const CheckMinMax = (elm, min, max) => {
    const length = $(elm).val().length;
    if (length < min || length > max) {
        $(elm).empty();
        $(elm).focus();
    }
}

function isEmptyArr(arr)  {
    if(Array.isArray(arr) && arr.length === 0)  {
        return true;
    }

    return false;
}

const CheckSSN = ssn => {
    const ssnPattern = /^[0-9]{3}\-?[0-9]{2}\-?[0-9]{4}$/;
    return ssnPattern.test(ssn);
}

const CheckRequired = inputList => {
    inputList.forEach(item => {
        const value = item.val();
        if (value == null || value == '' || value == undefined) {
            alert(`${item.data('name')} is required !!!`, 'error');

            return false;
        }
    })
};

const ComfirmPasswd = (pass, confirmPass) => pass === confirmPass;

const DisableInput = elm => $(elm).prop('disabled', function (i, v) {
    return !v;
});

const BlinkObject = elm => {
    $(elm).fadeOut('slow', function () {
        $(this).fadeIn('slow', function () {
            BlinkObject(this);
        });
    });
}

const InitCheckBox = (data, name) => {
    let html = '';
    data.forEach(item => {
        html += `<input type="checkbox" name="${name}" value="${item}"> ${item}`;
    });

    return html;
}
const InitRadio = (data, name) => {
    let html = '';
    data.forEach(item => {
        html += `<input type="radio" name="${name}" value="${item}"> ${item}`;
    });

    return html;
}

const InitSelect = (data, name) => `<select name="${name}">${ArrayToOption(data)}</select>`;

const ArrayToOption = array => {
    let html = '';
    array.forEach(item => {
        html += `<option value="${item}">${item}</option>`
    });

    return html;
}

function commaCheck($this) {
    $($this).val(function (index, value) {
        value = value.replace(/,/g, '');
        return numberWithCommas(value);
    });
}

function minusComma(value) {
    let formNumber = "" + value;
    // 문자제거
    // value = formNumber.toString().replace(/[^\d]+/g, "");

    // 콤마제거
    value = formNumber.toString().replace(/,/g, "");
    return value;
}

function rand(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}

function format_decimal(val, number) {
    let format = decimal_convert(number);
    return numeral(parseFloat(val).toFixed(number)).format(format);
}

function fill_zero(width, str) {
    return (str.length && width > 0) ? str + '.' + new Array(width + 1).join('0') : str;
}

function decimal_convert(point_name) {
    return fill_zero(parseInt(point_name), '0,0')
}

function remove_tag( html ) {
    return html.replace(/(<([^>]+)>)/gi, "");
}

function is_localhost() {
    if (location.hostname === 'localhost' || location.hostname === '127.0.0.1') {
        return true
    }
    return false
}

function get_clusterize_rows_in_block() {
    return 10
    // return is_localhost() ? 10 : 10
}

function remove_comma_and_arithmetic(a, b, type) {
    switch (type) {
        case 'plus':
            return Number(minusComma(a)) + Number(minusComma(b))
        case 'minus':
            return Number(minusComma(a)) - Number(minusComma(b))
    }
}

function format_conver_for(data, format, display_vars = undefined) {
    let result = data;
    switch (format) {
        case 'YYYY-MM-DD': case 'YYYY.MM.DD': case 'YYYYMMDD':
        case 'YY-MM-DD': case 'YY.MM.DD': case 'YYMMDD':
        case 'yy-mm-dd': case 'yy.mm.dd': case 'yymmdd':
            result = isEmpty(data) ? '' : moment(data).format(format.toUpperCase());
            break;
        case 'unixtime':
            result = isEmpty(data) ? '' : moment(new Date(data * 1000)).format('YYYY-MM-DD HH:mm:ss');
            break;
        case 'unix-yyyy.mm.dd':
            result = isEmpty(data) ? '' : moment(new Date(data * 1000)).format('YYYY-MM-DD');
            break;
        case '$_ThumbNail':
            result = `<img src="${window.env['MEDIA_URL'] + data}" width="${display_vars['ListWidth']}" height="${display_vars['ListHeight']}" style="max-width: 100%;" onerror="this.src='/images/folder.jpg'"`;
            break;
        case '$_FileName':
            let path_list = data.split('/')
            result = path_list[path_list.length - 1];
            break;
        case 'check':
            if (data == 1 || data == true) {
                result = '√';
            } else {
                result = '';
            }
            break;
        case 'unique':
            result = data.split("'").join('');
            break;
        case 'date_month':
            result = isEmpty(data) ? '' : moment(data).format('YY.MM');
            break;
        case 'date_week':
            result = isEmpty(data) ? '' : `${moment(data).format('YY.MM')}-${moment(data).isoWeek()}`;
            break;
        case 'remove_tag':
            result = remove_tag(data);
            break;
        default:
            if (! isEmpty(format) && format.match(/[A-Za-z]+\s*\(\s*'(.*?)\'\s*\)\s*/)) {
                const func_name = format.replace(')', `, '${data}')`);
                try {
                    result = eval(`format_func_${func_name}`);
                } catch (err) {
                    result = 'Invalid';
                }
            }
            break;
    }

    return result;
}

function format_func_decimal(...argv) {
    const format = capitalize(camelCase(argv[0])) + 'Point';
    let data;

    if (window.User[format] == undefined) {
        return 'Invalid';
    }

    switch (argv.length) {
        case 2:
            data = format_decimal(argv[1], window.User[format]);
            break;
        case 3:
            data = format_decimal(argv[2], window.User[format])
            if (argv[1] === 'nz' && (isEmpty(data) || data == 0)) { data = 0; }
            else if (argv[1] === 'zn' && (isEmpty(data) || data == 0)) { data = ''; }
            break;
    }

    return data;
}

function format_func_status_update(value, data) {
    return { Field: 'Status', Value: format_func_status_rev(value, data),  };
}

function format_func_status_code_update(value, data) {
    return { Field: 'Status', Value: data,  };
}

function format_func_status_rev(value, data) {
    const status = Object.values(window.CodeTitle['status'][value]).filter(status => status.Title == data)
    if (isEmptyArr(status)) { return data;  }

    return _.first(status)['Code'];
}

function format_func_status(value, data) {
    if (window.CodeTitle['status'] && window.CodeTitle['status'][value][data]) {
        return window.CodeTitle['status'][value][data]['Title'];
    }

    return 'Invalid';
}

function format_func_sort_update(value, data) {
    return { Field: 'Sort', Value: format_func_sort_rev(value, data),  };
}

function format_func_sort_code_update(value, data) {
    return { Field: 'Sort', Value: data,  };
}

function format_func_sort_rev(value, data) {
    const sort = Object.values(window.CodeTitle['sort'][value]).filter(sort => sort.Title == data)
    if (isEmptyArr(sort)) { return data;  }

    return _.first(sort)['Code'];
}

function format_func_sort(value, data) {
    if (window.CodeTitle['sort'] && window.CodeTitle['sort'][value][data]) {
        return window.CodeTitle['sort'][value][data]['Title'];
    }

    return 'Invalid';
}

function format_func_deal_type_update(value, data) {
    return { Field: 'DealType', Value: format_func_deal_type_rev(value, data),  };
}

function format_func_deal_type_rev(value, data) {
    const deal_type = Object.values(window.CodeTitle['deal-type'][value]).filter(deal_type => deal_type.Title == data)
    if (isEmptyArr(deal_type)) { return data;  }

    return _.first(deal_type)['Code'];
}

function format_func_deal_type(value, data) {
    if (window.CodeTitle['deal-type'] && window.CodeTitle['deal-type'][value][data]) {
        return window.CodeTitle['deal-type'][value][data]['Title'];
    }

    return 'Invalid';
}

function format_func_paymethod_rev(value, data) {
    const paymethod = Object.values(window.CodeTitle['paymethod'][value]).filter(paymethod => paymethod.Title == data)
    if (isEmptyArr(paymethod)) { return data;  }

    return _.first(paymethod)['Code'];
}

function format_func_paymethod(value, data) {
    if (window.CodeTitle['paymethod'] && window.CodeTitle['paymethod'][value][data]) {
        return window.CodeTitle['paymethod'][value][data]['Title'];
    }

    return 'Invalid';
}

function format_func_situation_rev(value, data) {
    const situation = Object.values(window.CodeTitle['situation'][value]).filter(situation => situation.Title == data)
    if (isEmptyArr(situation)) { return data;  }

    return _.first(situation)['Code'];
}

function format_func_situation(value, data) {
    if (window.CodeTitle['situation'] && window.CodeTitle['situation'][value][data]) {
        return window.CodeTitle['situation'][value][data]['Title'];
    }

    return 'Invalid';
}

function check_dom_input_number(dom_array) {
    let arr = dom_array.filter(el => isNaN($(el).val()))

    arr.forEach(el => $(el).val('') );

    if (! isEmptyArr(arr)) {
        iziToast.error({
            title: 'Error',
            message: $('#please-enter-a-number').text(),
        });
        return true;
    }

    return false;
}

function show_iziToast_msg(page, callback = undefined) {
    if (page) {
        iziToast.success({
            title: 'Success',
            message: $('#action-completed').text(),
        });
        if (! isEmpty(callback)) {
            callback()
        }
    } else {
        iziToast.error({
            title: 'Error',
            message: page.data.body ?? $('#api-request-failed-please-check').text(),
        });
    }
}

function token_value(balance, unit_point, decimal_point) {
    if (decimal_point === -1) {
        return balance / (10 ** unit_point)
    }

    return format_decimal(balance / (10 ** unit_point), decimal_point)
}

function token_value_rev(balance, unit_point) {
    // return balance + '0'.repeat(unit_point);

    return String(balance * (10 ** unit_point))
}

function long_number_string(n){
    var str, str2= '', data= n.toExponential().replace('.','').split(/e/i);
    str= data[0], mag= Number(data[1]);
    if(mag>=0 && str.length> mag){
        mag+=1;
        if (isEmpty(str.substring(mag))) { return str.substring(0, mag) }
        return (str.substring(0, mag)+'.'+str.substring(mag));
    }
    if(mag<0){
        while(++mag) str2+= '0';
        return '0.'+str2+str;
    }
    mag= (mag-str.length)+1;
    while(mag> str2.length){
        str2+= '0';
    }

    return (str+str2);
}

// 현재 value 값이 소수점 n 자리 숫자라면 더 이상 입력 X
function check_number_of_decimal_places(val, n) {
    // const _pattern1 = /^\d*[.]\d{16}$/
    const _pattern1 = new RegExp(`^\\d*[.]\\d{${n}}$`, 'g')
    return !_pattern1.test(val)
}

function is_mobile() {
    var user = navigator.userAgent;
    var is_mobile = false;

    if( user.indexOf("iPhone") > -1
        || user.indexOf("Android") > -1
        || user.indexOf("iPad") > -1
        || user.indexOf("iPod") > -1
    ) {

        is_mobile = true;

    }

    return is_mobile;

}
