(function () {
    'use strict';
    var target = '#docs_table';
    var info;

    BX24.init(main);

    function main () {
        window.App = new window.CApp();
        window.AppStorage = new window.CStorage();

        App.init(run);

        docReady();
    }

    function docReady() {
        $().ready(function () {
            $('#app_settings_btn').on('click', function () {
                dealTin();
            });
        });
    }

    function run () {
		info = BX24.placement.info();
        console.log('run ->', info);

        if (info.options.action === 'view_activity' && info.options.activity_id) {
            $('#info').remove();
            $('#app_settings').remove();
            viewEmberDoc(info);
        } else if (info.options && info.options.ENTITY_ID) {
            $('#info').remove();
            $('#app_settings').show();
            viewApp(info);
        } else {
            $('#app_settings').remove();
            viewAppInfo();
        }
    }

    function viewApp (info) {
        BX24.callMethod('crm.documentgenerator.document.list', {
            filter: {
                entityId: info.options.ENTITY_ID
            }
        }, function (res) {
            var data = res.data();
            docs = data.documents;

            if (!App.getSavedTinKey()) {
                dealTin();
            }

            BX24.callMethod('crm.deal.get', {
                ID: info.options.ENTITY_ID
            }, function (res2) {
                deal = res2.data();

                window.Didox = new window.CDidox();
                window.EAuth = new window.CEAuth();
                window.DocSign = new window.CDocSign();
                window.DocsTable = new window.CDocsTable({
                    docs: docs,
                    target: target
                });

                window.DocsTable.init();
                EAuth.init();

                if (deal.TITLE) {
                    $('#deal_name').html('Документы "' + deal.TITLE + '"');
                } else {
                    $('#deal_name').html('Сделка не найдена');
                }
            });
        });
    }

    function viewEmberDoc (info) {
        BX24.callMethod("crm.activity.get", {
            id: info.options.activity_id
        }, function (result) {
            if (result.error() ) {
                console.error(result.error());
            } else {
                var activity = result.data();
                var docId = App.getDocId(activity.DESCRIPTION);
                if (!doc) {
                    App.showMessage('Документ не найден');
                    return;
                }

                BX24.callMethod('crm.documentgenerator.document.get', {
                    id: docId
                }, function (res) {
                    if(res.error()) {
                        console.error(res.error());
                        return;
                    }
                    var doc = res.data();

                    App.loadFile(doc.pdfUrlMachine, App.showDoc);
                });

                App.loadFile();
            }
        });

    }

    function viewAppInfo () {
        var divInfo = '#app_default';
        var divInstruction = '#app_instruction';

        $('#deal_name').html(App.getAppName());
        $('#docs_table').remove();
        $('#info').show();
        $('#default_btn').addClass('bg-gray-400');

        $('#default_btn').on('click', function () {
            $('#default_btn').addClass('bg-gray-400');
            $('#instruction_btn').removeClass('bg-gray-400');
            $(divInfo).show();
            $(divInstruction).hide();
        });
        $('#instruction_btn').on('click', function () {
            $('#instruction_btn').addClass('bg-gray-400');
            $('#default_btn').removeClass('bg-gray-400');
            $(divInstruction).show();
            $(divInfo).hide();
        });

        App.eventRegist('load_default', null, function (res) {
            if (!(typeof res === 'object' && res.page)) {
                return;
            }
            var page = res.page;
            $(divInfo).html(page);
            // $('#app_version').html(App.VERSION);
        });
        App.eventRegist('load_instructions', null, function (res) {
            if (!(typeof res === 'object' && res.page)) {
                return;
            }
            var page = res.page;
            $(divInstruction).html(page);
        });
    }

    function dealTin() {
        BX24.callMethod(
            "crm.deal.fields", {type: 'string'}, function(result) {
                if(result.error()) {
                    console.error(result.error());
                } else {
                    var res = App.getSavedTinKey();

                    showDealKeys(result.data(), res);
                }
            }
        );
    }

    /**
     * @param arr {Array}
     * @param selected {String}
     */
    function showDealKeys(arr, selected) {
        var form = $('<form class="p-1" />').html(createSelect(arr));

        Swal.fire({
            title: '',
            html: form.get(0),
            didOpen: function () {
                var id = document.getElementById('tin_'+selected);

                if (id) {
                    id.setAttribute('selected', 'true');
                }
            }
        }).then(function (res) {
            if (res.isConfirmed) {
                var code = $('#select_tin').val()
                App.setAppOptions({
                    tin_key: code
                });
                App.setAppTinKey(code);
            }
        });
    }

    function  createSelect(arr) {
        var keys = Object.keys(arr);
        var select = $('<select id="select_tin" class="py-3 px-4 bg-white rounded-lg placeholder-gray-400 text-gray-900 appearance-none inline-block w-full shadow-md mt-2 focus:outline-none focus:ring-2 focus:ring-blue-600" />');

        keys.forEach(function (key) {
            var data = arr[key];
            select.append(createOption(key, data.listLabel || data.title));
        });

        return select.get(0);

        function createOption(val, text) {
            return $('<option value="'+val+'" id="tin_'+val+'">'+text+'</option>');
        }
    }
})();
