/**
 * File encoding: utf-8
 */


const validationEmail = (email) => /^([a-z0-9_\.-])+@[a-z0-9-]+\.([a-z]{2,4}\.)?[a-z]{2,4}$/i.test(email);

let alertList = {

    production: {
        title: 'Статусы заказов (производство)',
        items: {
            'order_created': 'Заказ создан',
            'order_deleted': 'Заказ удалён',
            'maket_fail': 'Макет не удовлетворяет требованиям печати',
            'maket_success': 'Макет подтверждён',
            'order_print': 'Заказ в печати',
            'order_success': 'Заказ отпечатан',
        }
    },

    logistics: {
        title: 'Логистика',
        items: {
            'to_delivery': 'Заказ принят в транспортную компанию',
            'in_way': 'Заказ в пути',
            'att_courier': 'Заказ закреплён за курьером',
            'delivery_wait': 'Заказ готов к выдаче',
            'delivery_success': 'Заказ выдан получателю',
        }
    },

    mailings: {
        title: 'Рассылки',
        items: {
            'shares': 'Акции',
            'news': 'Новости',
        }
    },

    finance: {
        title: 'Документы / Финансы',
        items: {
            'invoice': 'Счет на оплату',
            'balance': 'Поступление денежных средств на баланс',
            'pay': 'Списание денежных средств с баланса',
            'bonus': 'Поступление бонусов по заказу',
            'pay_bonus': 'Списание бонусов по заказу',
        }
    },

};


// Questionnaire
let Q = new (function () {

    let instance = this;

    this.uploaded = 1;
    this.profile = 1;

    this.__ACTIVE__ = true;

    const findName = function(key) {
        for (let group in alertList)
        {
            for (let service in alertList[group]['items'])
            {
                if (service === key)
                {
                    return alertList[group]['items'][service];
                }
            }
        }

        return false;
    };

    const notifyConfig = function(allData) {

        let data = {};

        if (!instance.profile && allData['active'] !== '1') return false;

        if (allData['cfg'] !== false)
        {
            data = allData['cfg'];

            if (!instance.profile && data['_date_update'] !== null) return false;
        }

        let html = '';

        for (let key in alertList)
        {
            if (allData['default']['id_region'] === '1' && key === 'logistics')
            {
                continue;
            }

            html += `<tr class="alert_group_header">` +
                `<th class="group_name">${alertList[key]['title']}</th>` +
                `<th style="width: 227px;"><div style="position: relative"><!--<i class="fa fa-check-circle group-select" aria-hidden="true"></i>-->Email</div></th>` +
                `<th class="th_email_" style="width: 227px;"><div style="position: relative"><!--<i class="fa fa-check-circle group-select" aria-hidden="true"></i>-->WhatsApp</div></th>` +
                `<th class="th_telegram_" style="width: 227px;"><div style="position: relative"><!--<i class="fa fa-check-circle group-select" aria-hidden="true"></i>-->Telegram</div></th>` +
                `<th class="th_sborka" style="width: 137px;"><div style="position: relative;"><!--<i class="fa fa-check-circle group-select" aria-hidden="true"></i>-->В сообщения на сайте</div></th></tr>`;

            let items = alertList[key]['items'];

            for (let key in items)
            {

                let checkbox = { email: 'checked', whatsApp: 'checked', telegram: 'checked', sborka: 'checked'},
                    input = { email: '', whatsApp: '', telegram: '', },
                    inputValue = { email: '', whatsApp: '', telegram: '', },
                    inputStyle = {};


                if( data['value'] && key in data['value'] )
                {
                    let value = data['value'][key];

                    for(let _key in value)
                    {
                        inputValue[_key] = data[_key][key];

                        if (value[_key] === "false" || inputValue[_key] == '')
                        {
                            checkbox[_key] = '';
                            input[_key] = 'disabled';
                        }
                    }

                }

                if (allData['cfg'] === false)
                {
                    console.log('cfg', false);
                    inputValue['email'] = (allData['default']['email']) ? allData['default']['email'] : '';
                    inputValue['whatsApp'] = (!!allData['default']['whatsapp_num']) ? allData['default']['whatsapp_num'] : "";
                    inputValue['telegram'] = (!!allData['default']['telegram_num']) ? allData['default']['telegram_num'] : "";


                    if (inputValue['email'] == "")
                    {
                        checkbox['email'] = '';
                        input['email'] = 'disabled';
                    }

                    if (inputValue['whatsApp'] == "")
                    {
                        checkbox['whatsApp'] = '';
                        input['whatsApp'] = 'disabled';
                    }

                    if (inputValue['telegram'] == "")
                    {
                        checkbox['telegram'] = '';
                        input['telegram'] = 'disabled';
                    }
                }

                inputValue['whatsApp'] = parseInt(inputValue['whatsApp'].replace(/\D+/g,""));
                inputValue['telegram'] = parseInt(inputValue['telegram'].replace(/\D+/g,""));

                let turnOff = { email: 'disabled', whatsApp: 'disabled', telegram: 'disabled', };

                if (checkbox['email'] === '')
                {
                    turnOff['email'] = '';
                }
                if (checkbox['whatsApp'] === '')
                {
                    turnOff['whatsApp'] = '';
                }

                if (checkbox['telegram'] === '')
                {
                    turnOff['telegram'] = '';
                }

                // STATUS
                html += `<tr><td>${items[key]}</td>`;

                // EMAIL
                html += `<td class="p-0 type"><div>` +
                    `<label class="d-flex notify_contact" service="email" eventkey="${key}" style="padding: 6px 15px;align-items: center;">` +
                    `<input autocomplete="off" type="checkbox" ${checkbox['email']}/> ` +
                    `<input autocomplete="off" class="show-${input['email']}" style="width: 180px;" type="text" value="${inputValue['email']}" placeholder="Введите email"/>` +
                    `<span class="turnoff show-${turnOff['email']}">не отправлять</span>` +
                    `</label></div></td>`;

                // WHATSAPP
                html += `<td class="p-0 type"><div>` +
                    `<label class="d-flex notify_contact" service="whatsApp" eventkey="${key}" style="padding: 6px 15px;align-items: center;">` +
                    `<input autocomplete="off" type="checkbox" ${checkbox['whatsApp']}/> ` +
                    `<input autocomplete="off" class="phone_number show-${input['whatsApp']}" type="text" style="width: 180px;" value="${inputValue['whatsApp']}" placeholder="Введите телефон" />` +
                    `<span class="turnoff show-${turnOff['whatsApp']}">не отправлять</span>` +
                    `</label></div></td>`;

                // TELEGRAM
                html += `<td class="p-0 type"><div>` +
                    `<label class="d-flex notify_contact" service="telegram" eventkey="${key}" style="padding: 6px 15px;align-items: center;">` +
                    `<input autocomplete="off" type="checkbox" ${checkbox['telegram']}/> ` +
                    `<input autocomplete="off" class="phone_number show-${input['telegram']}" type="text"  style="width: 180px;" value="${inputValue['telegram']}" placeholder="Введите телефон" />` +
                    `<span class="turnoff show-${turnOff['telegram']}">не отправлять</span>` +
                    `</label></div></td>`;

                // SBORKA
                html += `<td class="p-0 type"><div>` +
                    `<label class="d-flex justify-content-center notify_contact" service="sborka" eventkey="${key}" style="padding: 6px 15px;align-items: center;">` +
                    `<input autocomplete="off" type="checkbox" ${checkbox['sborka']}/> ` +
                    `<input autocomplete="off" class="input_sborka" style="display: none" type="text" value="${inputValue['sborka']}" ${input['sborka']}"/>` +
                    `</label></div></td></tr>`;
            }
        }

        if (typeof instance.__ACTIVE__ !== "undefined")
        {
            $('#notice_load').hide();
            $('#cfg_replace').replaceWith(`<table id="notifyConfig">${html}</table>`);
        }

        $('input.phone_number').each(function (el) {
            $(this).mask("+99999999999?9")
                .keydown(function () {
                    var $elem = $(this);
                    var a = this.value.replace(/\D/g, "").length;
                    setTimeout(function () {
                        var n = $elem.val().replace(/\D/g, "").length;
                        if (n !== a && (n === 11 || n === 12)) {
                            var mask = (n === 12 ? "+999999999999" : "+99999999999?9");
                            $elem.mask(mask);
                        }
                    }, 1);
                });
        });



        $('#notifyConfig input[type=checkbox]').on('change', function () {

            let checked = $(this).prop('checked');
            console.log(checked);
            let $input = $(this).siblings('input[type=text]'),
                $span = $(this).siblings('span');

            if (!$input.hasClass('input_sborka'))
            {
                if(checked)
                {
                    $span.hide();
                    $input.show();
                }
                else
                {
                    $input.hide();
                    $span.show();
                }
            }

            $input.prop('disabled', !checked);
        });


        $('#questionnaire_save').click( () => instance.update() );
        return true;
    };

    const saveAlertsPrepare = () => {
        let obj = { value: {}, }, errMsg = '';

        $('.notify_contact').each(function (el) {

            let service = $(this).attr('service'),
                eventKey = $(this).attr('eventkey');

            if( !(eventKey in obj.value) )
            {
                obj.value[eventKey] = {};
            }

            obj.value[eventKey][service] = $(this).find('input[type=checkbox]').prop('checked');

            if( !(service in obj) )
            {
                obj[service] = {};
            }

            let $input = $(this).find('input[type=text]'),
                memory = $input.attr('memory');

            obj[service][eventKey] =  $input.val().trim();

            if (obj.value[eventKey][service] && service !== "sborka")
            {
                if (obj[service][eventKey] === "")
                {
                    errMsg = 'Поля обозначенные галочкой не могут быть пустыми';
                    return;
                }

                if (service === "email" && !validationEmail(obj[service][eventKey]))
                {
                    errMsg = 'Некорректно указан Email для «' + findName(eventKey) + '»';
                    return;
                }
            }
        });

        return {errMsg, obj};
    };

    const show = function(data) {
        $('.q_save_success').empty();
        notifyConfig(data);
    };

    const initConfig = function () {
        $.ajax({
            type: 'POST',
            data: {},
            url: "/AJAX/questionnaire.php",
            async: true,
            dataType: 'json',
            success: function (response) {
                show(response['Q']);
            },
        });
    };

    this.show = function () {
        $(document).ready(function () {
            initConfig();
        });
    };

    this.update = function ()
    {
        $('.q_save_success').empty();

        let {errMsg, obj} = saveAlertsPrepare();

        if (errMsg !== '')
        {
            $('.q_save_errors').text(errMsg);
        }
        else
        {
            //save
            $.ajax({
                type: 'POST',
                data: {
                    'alerts': obj,
                    'q-only': '1'
                },
                url: "AJAX/rewriteAlertsProfile.php",
                async: false,

                success: function (data) {

                    if (instance.profile)
                    {
                        $('.q_save_success').text('Данные успешно сохранены.');
                    }

                }
            });

            $('#modal_questionnaire').modal('hide');
        }

    }

})();
