$(document).ready(function () {
    $(document).on('click', '.create-new-post-by-franchise-js', function () {
        var url = $(this).data('url');
        var id = $(this).data('collaps_id');
        var that = $(this);
        that.find('.loader-create-franchise-js').show();
        $.post(url, {
            collaps_id: id.toString().trim()
        }).done(function (response) {
            that.hide();
        }).fail(function (response) {
            DLEalert(response.responseText, 'Ошибка: ' + response.status)
        }).always(function () {
            that.find('.loader-create-franchise-js').hide();
        })
    });

    let tableFilm = $('#films table');
    tableFilm.DataTable({
        "order": [[0, "desc"]],
        "ordering": true,
        pagingType: "input",
        "columnDefs": [{
            "orderable": false,
            "targets": "no-sort"
        }],
        "processing": true,
        "serverSide": true,
        "paging": true,
        "ajax": tableFilm.data('action-url') + '&franchise_type=' + tableFilm.data('franchise-type'),
        "columns": [
            {
                "data": "kinopoisk_id",
                "className": "text-center",
                "mRender": function (data, type, full) {
                    var a = '';

                    if (data !== null) {
                        a = '<a target="_blank" href="https://www.kinopoisk.ru/film/' + data + '/">' + data + '</a>'
                    }
                    return a;
                }
            },
            {
                "data": "name",
                "mRender": function (data, type, full) {
                    if (data.length > 25) {
                        data = data.substring(0, 25) + '...'
                    }

                    if (full.has_in_db) {
                        var aButton = document.createElement('a');
                        aButton.href = full.post_url;
                        aButton.textContent = data;
                        data = aButton.outerHTML;
                    }

                    return data;
                }
            },
            {
                "data": "ads",
                "className": "text-center",
                "mRender": function (data, type, full) {
                    if (!data) {
                        return '<span class="text-success">Нет</span>';
                    }
                    return '<span class="text-danger"><b>Есть</b></span>';
                }
            },
            {"data": "quality"},
            {"data": "kinopoiskRating"},
            {"data": "ImdbRating"},
            {
                "data": "year",
                "className": "text-center",
            },
            {
                "data": "has_in_db",
                "className": "text-center",
                "mRender": function (data, type, full) {
                    if (!data) {
                        return '<i class="text-danger fa fa-times-circle-o"></i>';
                    }
                    return '<i class="text-success fa fa-check-circle"></i>';
                }
            },
            {
                "data": null,
                "mRender": function (data, type, full) {

                    if (!full.has_in_db) {
                        var button = document.createElement('button');
                        var loadDiv = document.createElement('div');

                        loadDiv.classList = 'loader loader-create-franchise loader-create-franchise-js';
                        loadDiv.textContent = 'Подождите!';
                        loadDiv.style.display = 'none';

                        button.classList = 'btn-link create-new-post-by-franchise-js overflow-hidden';
                        button.innerHTML = '<i class="fa fa-plus" aria-hidden="true"></i>' + loadDiv.outerHTML;
                        button.type = 'button';
                        button.dataset.url = tableFilm.data('action-url-add');
                        button.dataset.collaps_id = full.id;
                        return button.outerHTML;
                    }

                    return '';
                }
            },
        ],
        language: {
            lengthMenu: "Показывать _MENU_ записей на странице",
            zeroRecords: "Ничего не найдено - извините",
            info: "Отображение страницы _PAGE_ из _PAGES_",
            infoEmpty: "Нет доступных записей",
            infoFiltered: "(отфильтровано по итоговым записям _MAX_)",
            search: "Поиск:",
            processing: "Загрузка...",
            paginate: {
                info: "Страница _INPUT_ из _TOTAL_",
                first: "<i class=\"fa fa-fast-backward\" aria-hidden=\"true\"></i>",
                last: "<i class=\"fa fa-fast-forward\" aria-hidden=\"true\"></i>",
                next: "<i class=\"fa fa-step-forward\" aria-hidden=\"true\"></i></i>",
                previous: "<i class=\"fa fa-step-backward\" aria-hidden=\"true\"></i>"
            },
        },
    });

    $('.tab-js').on('click', function () {

        let tableType = $(this).attr('href');

        if (!$.fn.dataTable.isDataTable(tableType + ' table')) {
            let table = $(tableType + ' table');
            table.DataTable({
                "order": [[0, "desc"]],
                "ordering": true,
                pagingType: "input",
                "columnDefs": [{
                    "orderable": false,
                    "targets": "no-sort"
                }],
                "processing": true,
                "serverSide": true,
                "ajax": table.data('action-url') + '&franchise_type=' + table.data('franchise-type'),
                "columns": [
                    {
                        "data": "kinopoisk_id",
                        "className": "text-center",
                        "mRender": function (data, type, full) {
                            var a = '';

                            if (data !== null) {
                                a = '<a target="_blank" href="https://www.kinopoisk.ru/film/' + data + '/">' + data + '</a>'
                            }
                            return a;
                        }
                    },
                    {
                        "data": "name",
                        "mRender": function (data, type, full) {
                            if (data.length > 20) {
                                data = data.substring(0, 20) + '...'
                            }

                            if (full.has_in_db) {
                                var aButton = document.createElement('a');
                                aButton.href = full.post_url;
                                aButton.textContent = data;
                                data = aButton.outerHTML;
                            }

                            return data;
                        }
                    },
                    {
                        "data": "ads",
                        "className": "text-center",
                        "mRender": function (data, type, full) {
                            if (!data) {
                                return '<span class="text-success">Нет</span>';
                            }
                            return '<span class="text-danger"><b>Есть</b></span>';
                        }
                    },
                    {"data": "quality"},
                    {"data": "kinopoiskRating"},
                    {"data": "ImdbRating"},

                    {
                        "data": "year",
                        "className": "text-center",
                    },
                    {
                        "data": "has_in_db",
                        "className": "text-center",
                        "mRender": function (data, type, full) {
                            if (!data) {
                                return '<i class="text-danger fa fa-times-circle-o"></i>';
                            }
                            return '<i class="text-success fa fa-check-circle"></i>';
                        }
                    },
                    {
                        "data": null,
                        "mRender": function (data, type, full) {

                            if (!full.has_in_db) {
                                var button = document.createElement('button');
                                var loadDiv = document.createElement('div');

                                loadDiv.classList = 'loader loader-create-franchise loader-create-franchise-js';
                                loadDiv.textContent = 'Подождите!';
                                loadDiv.style.display = 'none';

                                button.classList = 'btn-link create-new-post-by-franchise-js overflow-hidden';
                                button.innerHTML = '<i class="fa fa-plus" aria-hidden="true"></i>' + loadDiv.outerHTML;
                                button.type = 'button';
                                button.dataset.url = table.data('action-url-add');
                                button.dataset.collaps_id = full.id;
                                return button.outerHTML;
                            }

                            return '';
                        }
                    },
                ],
                language: {
                    lengthMenu: "Показывать _MENU_ записей на странице",
                    zeroRecords: "Ничего не найдено - извините",
                    info: "Отображение страницы _PAGE_ из _PAGES_",
                    infoEmpty: "Нет доступных записей",
                    infoFiltered: "(отфильтровано по итоговым записям _MAX_)",
                    search: "Поиск:",
                    processing: "Загрузка...",
                    paginate: {
                        info: "Страница _INPUT_ из _TOTAL_",
                        first: "<i class=\"fa fa-fast-backward\" aria-hidden=\"true\"></i>",
                        last: "<i class=\"fa fa-fast-forward\" aria-hidden=\"true\"></i>",
                        next: "<i class=\"fa fa-step-forward\" aria-hidden=\"true\"></i></i>",
                        previous: "<i class=\"fa fa-step-backward\" aria-hidden=\"true\"></i>"
                    },
                },
            });
        }
    });
});
