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 ordersScript = ordersScript || function () {
    var isInit = false;
    var orderListingDataTable = null;
    var selectedOrders = [];
    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 () {
        orderListDataTable($('#searchFrom').serialize());
        globalScript.initValidator();

        $('body').on('change', '.update_order_status', function () {
            var status = $(this).val();
            var orderId = $(this).closest('tr').find('.order-id').val();
            selectedOrders.push(orderId);
            updateOrderStatus(status, function () {
                toastr.success('Status successfully updated');
                orderListDataTable($('#searchFrom').serialize());
            });
        });

        $('body').on('submit', '#create_order_form', function (e) {
            e.preventDefault();
            if ($('#submit_btn').hasClass('disabled')) {
                return false;
            }
            $('#submit_btn').addClass('disabled');
            $('.add_errors').hide();
            $('.add_errors ul').html('');
            var adminName = $('#order_name').val();
            var adminEmail = $('#order_email').val();
            var adminPhone = $('#order_phone').val();
            var adminPassword = $('#order_password').val();
            var obj = Object.create(globalScript.CREATE_ORDER);
            obj.data = {
                'name': adminName,
                'email': adminEmail,
                'phone': adminPhone,
                'password': adminPassword
            };
            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);
                    $('#addOrderModal').modal('hide');
                    $('#create_order_form').trigger("reset");
                    orderListDataTable($('#searchFrom').serialize());
                }
            });
        });

        $('body').on('submit', '#edit_order_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 orderId = $('#order_id').val();
            // var edit_order_user_id = $('#edit_order_user_id').val();
            var edit_order_name = $('#edit_order_name').val();
            // var edit_order_country = $('#edit_order_country').val();
            var edit_order_city = $('#edit_order_city').val();
            var edit_order_state = $('#edit_order_state').val();
            var edit_order_zip = $('#edit_order_zip').val();
            var edit_order_phone = $('#edit_order_phone').val();
            var edit_order_email = $('#edit_order_email').val();
            var edit_order_billing_address = $('#edit_order_billing_address').val();
            var edit_order_customer_note = $('#edit_order_customer_note').val();
            var edit_order_price = $('#edit_order_price').val();
            var edit_order_status = $('#edit_order_status').val();
            var obj = Object.create(globalScript.UPDATE_ORDER);
            obj.url = obj.url(orderId);
            obj.data = {
                // 'user_id': edit_order_user_id,
                'name': edit_order_name,
                'city': edit_order_city,
                'state': edit_order_state,
                'zip': edit_order_zip,
                'phone': edit_order_phone,
                'email': edit_order_email,
                'billing_address': edit_order_billing_address,
                'customer_note': edit_order_customer_note,
                'price': edit_order_price,
                'status': edit_order_status,
            };
            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);
                    $('#editOrderModal').modal('hide');
                    $('#edit_order_form').trigger("reset");
                    orderListDataTable($('#searchFrom').serialize());
                }
            });
        });

        $('body').on('click', '.view-btn', function () {
            var orderId = $(this).closest('tr').find('.order-id').val();
            var obj = Object.create(globalScript.GET_ORDER_DETAILS);
            var url = obj.url(orderId);
            obj.url = url;
            globalScript.ajaxCall(obj).done(function (response) {
                if (response.hasOwnProperty('_metadata') && response._metadata.hasOwnProperty('outcomeCode') && response._metadata.outcomeCode === 0) {
                    $('body').find('#order_id').val(response.records.id);
                    $('body').find('#edit_order_form #edit_order_name').val(response.records.name);
                    $('body').find('#edit_order_form #edit_order_country').val(response.records.billing_country);
                    $('body').find('#edit_order_form #edit_order_city').val(response.records.billing_city);
                    $('body').find('#edit_order_form #edit_order_state').val(response.records.billing_state);
                    $('body').find('#edit_order_form #edit_order_zip').val(response.records.billing_zip);
                    $('body').find('#edit_order_form #edit_order_phone').val(response.records.phone);
                    $('body').find('#edit_order_form #edit_order_email').val(response.records.email);
                    $('body').find('#edit_order_form #edit_order_billing_address').val(response.records.billing_address);
                    $('body').find('#edit_order_form #edit_order_customer_note').val(response.records.customer_note);
                    $('body').find('#edit_order_form #edit_order_price').val(response.records.order_price);
                    $('body').find('#edit_order_form #edit_order_user_id').selectpicker('val', response.records.user_id);
                    $('body').find('#edit_order_form #edit_order_status').val(response.records.status);
                    // if (response.records.is_admin === 2) {
                    $('#customerSection').show();
                    $('#vcb').show();
                    $('#vcba').attr('href', '/admin/users?user=' + response.records.user_id);
                    // } else {
                    //     $('#customerSection').show();
                    //     $('#vcb').hide();
                    // }
                    // $('body').find('#edit_order_form #edit_order_height').val(response.records.height);
                    $('body').find('#edit_product_form #edit_order_products').selectpicker('val', response.records.products);
                    $('body').find('#oPCount').html(response.records.order_products.length);
                    if (response.records.order_products.length > 0) {
                        _.each(response.records.order_products, function (v, k) {
                            $('body').find('#oPList').append(
                                '<div class="card">' +
                                '<div class="card-body">' +
                                '<h6>Title: ' + v.product.title + '</h6>' +
                                '<h6>SKU: ' + v.product.sku + '</h6>' +
                                '<h6>Quantity: ' + v.quantity + '</h6>' +
                                '<h6>Color: ' + v.colors + '</h6>' +
                                '<h6>Size: ' + v.sizes + '</h6>' +
                                '<h6>Material: ' + v.materials + '</h6>' +
                                '<a class="btn btn-secondary text-white" target="_blank" href="/admin/products?product=' + v.product.id + '" style="margin-right: 10px">View Product</a>' +
                                '<a class="btn btn-secondary text-white" target="_blank" href="/product/' + v.product.slug + '">View Product on Website</a>' +
                                '</div>' +
                                '</div>'
                            );
                            // $('body').find('#oPList').append('<div class="card"><div class="card-body"><h6>Title: '+v.product.title+'</h6><h6>Quantity: '+v.quantity+'</h6><h6>Colors: '+v.colors+'</h6><h6>Sizes: '+v.sizes+'</h6><h6>Materials: '+v.materials+'</h6><h6>Brands: '+v.brands+'</h6></div></div>');
                        });
                    }
                    $('.edit_errors').hide();
                    $('.edit_errors ul').html('');
                    $('#editOrderModal').modal('show');
                }
            })
        });

        $('body').on('change', '#statusSearch', function (e) {
            orderListDataTable($('#searchFrom').serialize());
        });

        // $('#addOrderModal').on('hidden.bs.modal', function (e) {
        //     $('.add_errors').hide();
        //     $('.add_errors ul').html('');
        // });

        $('#editOrderModal').on('hidden.bs.modal', function (e) {
            $('body').find('#oPList').html('');
            $('.edit_errors').hide();
            $('.edit_errors ul').html('');
        });
    };

    var deleteOrders = function (callback) {
        var obj = Object.create(globalScript.DELETE_ORDER);
        obj.data = {
            'order_ids[]': selectedOrders
        };
        globalScript.ajaxCall(obj).done(function (response) {
            selectedOrders = [];
            if (typeof callback == 'function') callback();
        });
    };

    var orderListDataTable = function (type) {
        if (orderListingDataTable != null) {
            orderListingDataTable.clear().destroy();
        }
        orderListingDataTable = $('#orderListTable').DataTable({
            "ajax": {
                url: globalScript.APP_URL + "orders?" + type,
                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
                },
                {"data": "order_id", "title": "Order ID", "name": "order_id", "searchable": true, "orderable": true},
                {"data": "order_product", "title": "Reference", "name": "order_product", "searchable": false, "orderable": false},
                {
                    "data": "order_price",
                    "title": "Order Price",
                    "name": "order_price",
                    "searchable": true,
                    "orderable": true
                },
                {"data": "name", "title": "Full Name", "name": "name", "searchable": true, "orderable": true},
                {"data": "email", "title": "Email", "name": "email", "searchable": true, "orderable": true},
                {"data": "phone", "title": "Phone", "name": "phone", "searchable": true, "orderable": false},
                {"data": "status", "title": "Status", "name": "status", "searchable": false, "orderable": false},
                {
                    "data": null,
                    "title": "Action",
                    "searchable": false,
                    "orderable": false
                }
            ],
            "order": [[0, 'desc']],
            "rowCallback": function (row, data) {
                // if (!data.profile) {
                //     data.id = data.order_id
                //     data.profile = data;
                // }
                var tmpl = _.template($('#orderListTemplate').html());
                $(row).html(tmpl(data));
            }
        });
    };

    var updateOrderStatus = function (status, callback) {
        var obj = Object.create(globalScript.UPDATE_ORDER_STATUS);
        obj.data = {
            'order_ids[]': selectedOrders,
            'status': status
        };
        globalScript.ajaxCall(obj).done(function (response) {
            selectedOrders = [];
            if (typeof callback == 'function') callback();
        });
    };

    return {
        'init': init
    }

}();

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