(function ($) {
    var _companyService = abp.services.app.companyMaster
       l = abp.localization.getSource('BMC'),
    _$modal = $('#ClientMasterCreateModal'),
        _$form = _$modal.find('form'),
           _$table = $('#CompanyMasterTable');

    var _$companyTable = _$table.DataTable({
        paging: true,
        serverSide: true,
        listAction: {
            ajaxFunction: _companyService.getCompanies,
            inputFilter: function () {
                return $('#CompanySearchForm').serializeFormToObject(true);
            }
        },
        buttons: [
            {
                name: 'refresh',
                text: '<i class="fas fa-redo-alt"></i>',
                action: () => _$companyTable.draw(false)
            }
        ],
        responsive: {
            details: {
                type: 'column'
            }
        },
        columnDefs: [
            {
                targets: 0,
                'className': 'dt-body-center',
                'render': function (data, type, full, meta) {
                    return '<input type="checkbox" name="id[]" value="'
                        + $('<div/>').text(data).html() + '">';
                }
            }, {
                targets: 1,
                data: 'id',
                defaultContent: '',
            }, {
                targets: 2,
                data: 'companyName',
                sortable: false
           
            }, {
                targets: 3,
                data: 'url',
                sortable: false           
            },{
                targets: 4,
                data: 'domainName',
                sortable: false
            }, {

                targets: 5,
                data: 'subDomainName',
                sortable: false
            },{
                targets: 6,
                data: null,
                sortable: false,
                autoWidth: false,
                defaultContent: '',
                render: (data, type, row, meta) => {
                    return [
                        `   <button type="button" class="btn btn-sm bg-secondary edit-company" data-tenant-id="${row.id}" data-toggle="modal" data-target="#CompanyEditModal">`,
                        `       <i class="fas fa-pencil-alt"></i> ${l('Edit')}`,
                        '   </button>',
                        `   <button type="button" class="btn btn-sm bg-danger delete-company" data-tenant-id="${row.id}" data-company-name="${row.name}">`,
                        `       <i class="fas fa-trash"></i> ${l('Delete')}`,
                        '   </button>'
                        
                    ].join('');
                }
            }
        ]
    });

    // Handle click on "Select all" control
    $('#example-select-all').on('click', function () {
        // Check/uncheck all checkboxes in the table
        var rows = _$companyTable.rows({ 'search': 'applied' }).nodes();
        $('input[type="checkbox"]', rows).prop('checked', this.checked);
    });

    _$form.find('.save-button').on('click', (e) => {
        e.preventDefault();

        if (!_$form.valid()) {
            return;
        }

        var companydetails = _$form.serializeFormToObject();
        

        abp.ui.setBusy(_$modal);
        _companyService.createOrUpdateCompanyMaster(companydetails).done(function () {
            _$modal.modal('hide');
            _$form[0].reset();
            abp.notify.info(l('SavedSuccessfully'));
            _$companyTable.ajax.reload();
        }).always(function () {
            abp.ui.clearBusy(_$modal);
        });
    });

    $(document).on('click', '.delete-company', function () {
        var companyId = $(this).attr("data-tenant-id");
        var domainName = $(this).attr('data-company-name');
        deleteUser(companyId, domainName);
    });

    function deleteUser(companyId, domainName) {
        abp.message.confirm(
            abp.utils.formatString(
                l('AreYouSureWantToDelete'),
                companyId),
            null,
            (isConfirmed) => {
                if (isConfirmed) {
                    _companyService.deleteCompany({
                        id: companyId
                    }).done(() => {
                        abp.notify.info(l('SuccessfullyDeleted'));
                        _$companyTable.ajax.reload();
                    });
                }
            }
        );
    }

    $(document).on('click', '.edit-company', function (e) {
        var id = $(this).attr("data-tenant-id");

        e.preventDefault();
        abp.ajax({
            url: abp.appPath + 'CompanyMaster/CreateOrEditModal?id=' + id,
            type: 'POST',
            dataType: 'html',
            success: function (content) {
                $('#CompanyEditModal div.modal-content').html(content);
            },
            error: function (e) {
            }
        });
    });

    $(document).on('click', 'a[data-target="#ClientMasterCreateModal"]', (e) => {
        $('.nav-tabs a[href="#client-details"]').tab('show')
    });

    abp.event.on('tenant.edited', (data) => {
        _$companyTable.ajax.reload();
    });

    _$modal.on('shown.bs.modal', () => {
        _$modal.find('input:not([type=hidden]):first').focus();
    }).on('hidden.bs.modal', () => {
        _$form.clearForm();
    });

    $('.btn-search').on('click', (e) => {
        _$companyTable.ajax.reload();
    });

    $('.txt-search').on('keypress', (e) => {
        if (e.which == 13) {
            _$companyTable.ajax.reload();
            return false;
        }
    });


    var $delete = $('#btnDelete');

    $delete.click(function () {
        var ids = _$companyTable
            .row({ selected: true })
            .data();
        console.log(ids.id)

            if (ids.id <= 0) {
                return confirm("Please Select Atleast One Record");
            }
            else {
                deletOpenTagsByCheckBoxes(ids.id);
            }
            deletOpenTagsByCheckBoxes();
        });

    
    function deletOpenTagsByCheckBoxes(idList) {
        abp.utils.formatString(
            l('Deleteselectedrecords'),
            function (isConfirmed) {
                if (isConfirmed) {
                    _companyService.deleteCompanyList({
                        ids: idList.id
                    }).done(function () {
                        if (_$table.data('rows') === 1) {
                            params.pageIndex = params.pageIndex === 1 ? 1 : params.pageIndex - 1;
                        }
                        prevParams.filter = 'start';
                        _$companyTable.ajax.reload();
                        abp.notify.success(app.localize('SuccessfullyDeleted'));
                    });
                }
            }
        );
    }
})(jQuery);