Array.prototype.remove = function () {
    var what, a = arguments, L = a.length, ax;
    while (L && this.length) {
        what = a[--L];
        while ((ax = this.indexOf(what)) !== -1) {
            this.splice(ax, 1);
        }
    }
    return this;
};
var leadsScript = leadsScript || function () {
    var isInit = false;
    var leadsListingDataTable = null;
    var selectedLeads = [];
    var customCheckBox = '<div class="icheck-material-primary f_custom_checkbox" style="pointer-events: none"><input type="checkbox" id="bulk-action-checkbox" class="select_all" /><label for="bulk-action-checkbox"></label></div>';

    var init = function () {
        if (isInit) return;
        isInit = true;
        handler();
    };

    var handler = function () {
        leadsListDataTable($('#leadSearchFrom').serialize());
        globalScript.initValidator();

        $("body").on('click', '.select_all', function () { // bulk checked
            var status = this.checked;
            if (status === true) {
                $('#bulk-action-checkbox').prop('checked', true);
                $('#deleteAllBtn').fadeIn();
                $('#bulkActionsBtn').fadeIn();
                $('body').find(".bulkRow").each(function () {
                    $(this).prop("checked", status);
                    var roleId = $(this).closest('tr').find('.lead-id').val();
                    if (selectedLeads.indexOf(roleId) === -1) {
                        selectedLeads.push(roleId);
                    }
                });
            } else {
                $('#deleteAllBtn').fadeOut();
                $('#bulkActionsBtn').fadeOut();
                $(".bulkRow, .select_all").prop('checked', false);
                $('#bulk-action-checkbox').prop('checked', false);
                selectedLeads = [];
            }
        });

        $('body').on('click', '.bulkRow', function () {
            var status = this.checked;
            var cdId = $(this).closest('tr').find('.lead-id').val();
            if (status === true) {
                $('#deleteAllBtn').fadeIn();
                $('#bulkActionsBtn').fadeIn();
                if (selectedLeads.indexOf(cdId) === -1) {
                    selectedLeads.push(cdId);
                }
                // $('#bulk-action-checkbox').prop('checked', true);
            } else {
                selectedLeads.remove(cdId);
            }
            if (selectedLeads.length === 0) {
                $('#deleteAllBtn').fadeOut();
                $('#bulkActionsBtn').fadeOut();
                $(".bulkRow, .select_all").prop('checked', false);
            }
        });

        $('body').on('click', '#deleteAllBtn', function () {
            globalScript.showConfirmationAlert(
                'You want to delete?',
                function () {
                    deleteLeads(function () {
                        toastr.success('Deleted successfully');
                        selectedLeads = [];
                        $(".bulkRow, .select_all").prop('checked', false);
                        $('#deleteAllBtn').fadeOut();
                        $('#bulkActionsBtn').fadeOut();
                        leadsListDataTable($('#leadSearchFrom').serialize());
                    });
                }
            )
        });

        $('body').on('submit', '#create_lead_form', function (e) {
            e.preventDefault();
            if ($('#submit_btn').hasClass('disabled')) {
                return false;
            }
            $('#submit_btn').addClass('disabled');
            $('.add_errors').hide();
            $('.add_errors ul').html('');
            var lead_title = $('#lead_title').val();
            var lead_phone = $('#lead_phone').val();
            var lead_email = $('#lead_email').val();
            var lead_name = $('#lead_name').val();
            var lead_property_type = $('#lead_property_type').val();
            var lead_lead_type = $('#lead_lead_type').val();
            var lead_lead_category = $('#lead_lead_category').val();
            var lead_lead_status = $('#lead_lead_status').val();
            var lead_primary_source = $('#lead_primary_source').val();
            var lead_secondary_source = $('#lead_secondary_source').val();
            var lead_lead_interest_level = $('#lead_lead_interest_level').val();
            var lead_assign_to = $('#lead_assign_to').val();
            var lead_description = $('#lead_description').val();
            var obj = Object.create(globalScript.CREATE_LEAD);
            obj.data = {
                'title': lead_title,
                'phone': lead_phone,
                'name': lead_name,
                'email': lead_email,
                'property_type_id': lead_property_type,
                'lead_type_id': lead_lead_type,
                'lead_category_id': lead_lead_category,
                'lead_status_id': lead_lead_status,
                'lead_primary_source_id': lead_primary_source,
                'lead_secondary_source_id': lead_secondary_source,
                'lead_interest_level_id': lead_lead_interest_level,
                'assign_to': lead_assign_to,
                'description': lead_description,
            };
            globalScript.ajaxCall(obj).done(function (response) {
                if (response.errors && response.errors.length !== 0) {
                    $('.add_errors').show();
                    $('#submit_btn').removeClass('disabled');
                    _.each(response.errors, function (v, k) {
                        $('.add_errors ul').append('<li>' + v + '</li>');
                    });
                    return false;
                } else {
                    toastr.success(response._metadata.message);
                    setTimeout(function () {
                        window.location.reload()
                    }, 500)
                    // $('#addCallingDatabaseModal').modal('hide');
                    // leadsListDataTable($('#leadSearchFrom').serialize());
                }
            });
        });

        $('body').on('submit', '#edit_lead_form', function (e) {
            e.preventDefault();
            if ($('#edit_submit_btn').hasClass('disabled')) {
                return false;
            }
            $('#edit_submit_btn').addClass('disabled');
            $('.edit_errors').hide();
            $('.edit_errors ul').html('');
            var cdId = $('#lead_id').val();
            var lead_title = $('#edit_lead_title').val();
            var lead_phone = $('#edit_lead_phone').val();
            var lead_email = $('#edit_lead_email').val();
            var lead_name = $('#edit_lead_name').val();
            var lead_property_type = $('#edit_lead_property_type').val();
            var lead_lead_type = $('#edit_lead_lead_type').val();
            var lead_lead_category = $('#edit_lead_lead_category').val();
            var lead_lead_status = $('#edit_lead_lead_status').val();
            var lead_primary_source = $('#edit_lead_primary_source').val();
            var lead_secondary_source = $('#edit_lead_secondary_source').val();
            var lead_lead_interest_level = $('#edit_lead_lead_interest_level').val();
            var lead_assign_to = $('#edit_lead_assign_to').val();
            var lead_description = $('#edit_lead_description').val();
            var obj = Object.create(globalScript.UPDATE_LEAD);
            obj.url = obj.url(cdId);
            obj.data = {
                'title': lead_title,
                'phone': lead_phone,
                'name': lead_name,
                'email': lead_email,
                'property_type_id': lead_property_type,
                'lead_type_id': lead_lead_type,
                'lead_category_id': lead_lead_category,
                'lead_status_id': lead_lead_status,
                'lead_primary_source_id': lead_primary_source,
                'lead_secondary_source_id': lead_secondary_source,
                'lead_interest_level_id': lead_lead_interest_level,
                'assign_to': lead_assign_to,
                'description': lead_description,
            };
            globalScript.ajaxCall(obj).done(function (response) {
                if (response.errors && response.errors.length !== 0) {
                    $('#edit_submit_btn').removeClass('disabled');
                    _.each(response.errors, function (v, k) {
                        $('.edit_errors ul').append('<li>' + v + '</li>');
                        $('.edit_errors').show();
                    });
                } else {
                    toastr.success(response._metadata.message);
                    setTimeout(function () {
                        window.location.reload()
                    }, 500)
                }
            });
        });

        $('body').on('click', '.convert-btn', function () {
            var type = $(this).attr('data-type');
            var leadId = $(this).attr('data-id');
            selectedLeads = [];
            $(".bulkRow, .select_all").prop('checked', false);
            selectedLeads.push(leadId);
            globalScript.showConfirmationAlert(
                'You want to move this to ' + type + '?',
                function () {
                    updateStatus(2,'type', type, function () {
                        toastr.success('Successfully moved to ' + type);
                        setTimeout(function () {
                            window.location.reload()
                        }, 500)
                    });
                }
            )
        });

        $('body').on('click', '.edit-btn', function () {
            var leadId = $(this).attr('data-id');
            var obj = Object.create(globalScript.GET_LEAD_DETAILS);
            var url = obj.url(leadId);
            obj.url = url;
            globalScript.ajaxCall(obj).done(function (response) {
                if (response.hasOwnProperty('_metadata') && response._metadata.hasOwnProperty('outcomeCode') && response._metadata.outcomeCode === 0) {
                    $('body').find('#lead_id').val(response.records.id);
                    $('body').find('#edit_lead_form #edit_lead_title').val(response.records.title);
                    $('body').find('#edit_lead_form #edit_lead_phone').val(response.records.phone);
                    $('body').find('#edit_lead_form #edit_lead_name').val(response.records.name);
                    $('body').find('#edit_lead_form #edit_lead_email').val(response.records.email);
                    $('body').find('#edit_lead_form #edit_lead_property_type').selectpicker('val', response.records.property_type_id);
                    $('body').find('#edit_lead_form #edit_lead_lead_type').selectpicker('val', response.records.lead_type_id);
                    $('body').find('#edit_lead_form #edit_lead_lead_category').selectpicker('val', response.records.lead_category_id);
                    $('body').find('#edit_lead_form #edit_lead_lead_status').selectpicker('val', response.records.lead_status_id);
                    $('body').find('#edit_lead_form #edit_lead_primary_source').selectpicker('val', response.records.lead_primary_source_id);
                    $('body').find('#edit_lead_form #edit_lead_secondary_source').selectpicker('val', response.records.lead_secondary_source_id);
                    $('body').find('#edit_lead_form #edit_lead_lead_interest_level').selectpicker('val', response.records.lead_interest_level_id);
                    $('body').find('#edit_lead_form #edit_lead_assign_to').selectpicker('val', response.records.assign_to);
                    $('body').find('#edit_lead_form #edit_lead_description').val(response.records.description);
                    $('.edit_errors').hide();
                    $('.edit_errors ul').html('');
                    $('#editLeadModal').modal('show');
                }
            })
        });

        $('body').on('click', '.delete-btn', function () {
            selectedLeads = [];
            $(".bulkRow, .select_all").prop('checked', false);
            var cdId = $(this).closest('tr').find('.lead-id').val();
            selectedLeads.push(cdId);
            globalScript.showConfirmationAlert(
                'You want to delete?',
                function () {
                    deleteLeads(function () {
                        toastr.success('Deleted successfully');
                        leadsListDataTable($('#leadSearchFrom').serialize());
                    });
                }
            )
        });

        $('body').on('change', '.update_lead_status', function (e) {
            const column = $(this).attr('data-column');
            const id = $(this).attr('data-id');
            const type = $(this).attr('data-type');
            const status = e.target.value
            selectedLeads = [];
            selectedLeads.push(id);
            updateStatus(status, column, type, function () {
                toastr.success('Successfully updated');
                setTimeout(function () {
                    window.location.reload()
                }, 500)
            })
        });

        $('#addLeadModal').on('hidden.bs.modal', function (e) {
            $('.add_errors').hide();
            $('.add_errors ul').html('');
            $('#create_lead_form').trigger("reset");
            $('#lead_property_type').selectpicker('val', '');
            $('#lead_lead_type').selectpicker('val', '');
            $('#lead_lead_category').selectpicker('val', '');
            $('#lead_lead_status').selectpicker('val', '');
            $('#lead_primary_source').selectpicker('val', '');
            $('#lead_secondary_source').selectpicker('val', '');
            $('#lead_lead_interest_level').selectpicker('val', '');
            $('#lead_assign_to').selectpicker('val', '');
        });

        $('#editLeadModal').on('hidden.bs.modal', function (e) {
            $('.edit_errors').hide();
            $('.edit_errors ul').html('');
            $('#edit_lead_form').trigger("reset");
            $('#edit_lead_property_type').selectpicker('val', '');
            $('#edit_lead_lead_type').selectpicker('val', '');
            $('#edit_lead_lead_category').selectpicker('val', '');
            $('#edit_lead_lead_status').selectpicker('val', '');
            $('#edit_lead_primary_source').selectpicker('val', '');
            $('#edit_lead_secondary_source').selectpicker('val', '');
            $('#edit_lead_lead_interest_level').selectpicker('val', '');
            $('#edit_lead_assign_to').selectpicker('val', '');
        });

        $('body').on('click', '#leadSearchFormReset', function () {
            $('body').find('#project_search').empty();
            $('body').find('#project_search').append('<option value="">Select Project</option>');
            $('body').find('#project_search').selectpicker('val', '');
            $('body').find('#project_search').selectpicker('refresh');
            $('#district_search').selectpicker('val', '');
            $('#property_type_search').selectpicker('val', '');
            $('#lead_status_search').selectpicker('val', '');
            $('#lead_category_search').selectpicker('val', '');
            $('#lead_type_search').selectpicker('val', '');
            $('#lead_source_search').selectpicker('val', '');
            $('#lead_il_search').selectpicker('val', '');
            leadsListDataTable('');
        });

        $('body').on('submit', '#leadSearchFrom', function (e) {
            e.preventDefault();
            leadsListDataTable($('#leadSearchFrom').serialize());
        });

        $('#bulkModal').on('shown.bs.modal', function (e) {
            $('#slBulkIds').html(selectedLeads.toString());
            $('#bulkIds').val(selectedLeads.toString());
        });
    };

    var updateStatus = function (status, column, type, callback) {
        var obj = Object.create(globalScript.UPDATE_LEAD_STATUS);
        obj.data = {
            'lead_ids[]': selectedLeads,
            'type': type,
            'status': status,
            'column': column
        };
        globalScript.ajaxCall(obj).done(function (response) {
            selectedLeads = [];
            if (typeof callback == 'function') callback();
        });
    };

    var deleteLeads = function (callback) {
        var obj = Object.create(globalScript.DELETE_LEAD);
        obj.data = {
            'lead_ids[]': selectedLeads
        };
        globalScript.ajaxCall(obj).done(function (response) {
            selectedLeads = [];
            if (typeof callback == 'function') callback();
        });
    };

    var leadsListDataTable = function (query) {
        if (leadsListingDataTable != null) {
            leadsListingDataTable.clear().destroy();
        }
        leadsListingDataTable = $('#leadsListTable').DataTable({
            "ajax": {
                url: globalScript.APP_URL + "leads?" + query,
                type: "GET",
                xhrFields: {
                    withCredentials: true
                },
                dataSrc: function (json) {
                    if (json.hasOwnProperty('_metadata') && json._metadata.hasOwnProperty('outcomeCode') && json._metadata.outcomeCode === 4) {
                        window.top.location.href = "login";
                        return;
                    }
                    json.draw = json.records.draw;
                    json.recordsTotal = json.records.recordsTotal;
                    json.recordsFiltered = json.records.recordsFiltered;
                    $('body').find('#module_total_count').html(json.records.recordsTotal);
                    if (json.records.data.length !== 0) {
                        $("body").find(".f_custom_checkbox").css('pointer-events', 'all');
                        $("body").find(".f_custom_card_footer").show();
                    } else {
                        $("body").find(".f_custom_card_footer").hide();
                    }
                    return json.records.data;
                }
            },
            "searching": true,
            "ordering": true,
            "serverSide": true,
            "paging": true,
            "stateSave": false,
            "columns": [
                {
                    "orderable": true,
                    "searchable": false,
                    "data": 'created_at',
                    "visible": false
                },
                {"orderable": false, "searchable": false, "data": null, "title": customCheckBox},
                {"data": "reference_number", "title": "Ref.", "name": "reference_number", "searchable": true, "orderable": false},
                {"data": "title", "title": "Title", "name": "title", "searchable": true, "orderable": false},
                {"data": "name", "title": "Name", "name": "name", "searchable": true, "orderable": true},
                {"data": "email", "title": "Email", "name": "email", "searchable": true, "orderable": false},
                {"data": "phone", "title": "Phone", "name": "phone", "searchable": true, "orderable": false},
                {"data": "lead_type", "title": "Lead Type", "name": "lead_type.name", "searchable": false, "orderable": false},
                {"data": "lead_category", "title": "Lead Category", "name": "lead_category.name", "searchable": false, "orderable": false},
                {"data": "lead_status", "title": "Lead Status", "name": "lead_status.name", "searchable": false, "orderable": false},
                {"data": "assignee", "title": "Assigned To", "name": "assignee.name", "searchable": false, "orderable": false},
                {"data": "property_type", "title": "Property Type", "name": "property_type.name", "searchable": false, "orderable": false},
                {
                    "data": null,
                    "title": "Actions",
                    "searchable": false,
                    "orderable": false
                }
            ],
            "order": [[2, 'desc']],
            "rowCallback": function (row, data) {
                var tmpl = _.template($('#leadsListTemplate').html());
                $(row).html(tmpl(data));
            }
        });
    };

    return {
        'init': init
    }

}();

$(document).ready(function () {
    leadsScript.init();
});
