HEX
Server: Apache/2.4.41 (Ubuntu)
System: Linux ip-172-31-42-149 5.15.0-1084-aws #91~20.04.1-Ubuntu SMP Fri May 2 07:00:04 UTC 2025 aarch64
User: ubuntu (1000)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /var/www/vhost/disk-apps/agile-selling-mia/public/js/orders.js
// formato a los precios
function formatNumber(num) {
    return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
}

function printReturn() {
    var divContents = document.getElementById("modal_returns").innerHTML;
    var a = window.open("", "", "height=500, width=500");
    a.document.write("<html>");
    a.document.write("<body > <h1>Div contents are <br>");
    a.document.write(divContents);
    a.document.write("</body></html>");
    a.document.close();
    a.print();
}

function getReturnInProgress() {
    $("#modal_returns").modal();
    $("#tbody-order_returns").empty();
    $.ajax({
        url: "/sapb1/get/returns",
        method: "get",
        success: (data) => {
            $("#discardBtnReturn").data("returnid", data.id);
            $("#_client").val(
                data.user.first_name +
                    " - " +
                    data.user.document +
                    " ( " +
                    data.user.bo_contact_person +
                    " )"
            );
            let total = 0;
            let restokingFee = 0;
            data.return_details.forEach((elem, index) => {
                total = total + elem.order_product.product.price;
                restokingFee = restokingFee + elem.price;

                tr = `<tr>
                <td>${elem.order_product.order.code}</td>
                <td>${elem.plu}</td>
                <td>${elem.order_product.product.name}</td>
                <td>${elem.order_product.product.price}</td>

                <td>${elem.quantity}</td>
                <td>${elem.after_30}</td>


                <td><button type="button" class="btn btn-default" onclick="deleteReturnItem(${elem.id}, ${index})"><i class="fa fa-trash"></i></button></td>
                </tr>`;

                $("#tbody-order_returns").append(tr);

                $("#_return_cost").val(parseFloat(total).toFixed(2));
                $("#_restocking_fee").val(
                    parseFloat(total - restokingFee).toFixed(2)
                );
                $("#_total_credit").val(parseFloat(restokingFee).toFixed(2));
            });
        },
        error: () => {},
    });
}

function discardReturn() {
    let id = $("#discardBtnReturn").data("returnid");

    $.ajax({
        url: "/sapb1/discard/return/" + id,
        method: "delete",
        success: (resp) => {
            window.location.reload();
        },
        error: () => {},
    });
}

function saveReturn() {
    let id = $("#discardBtnReturn").data("returnid");

    $.ajax({
        url: "/sapb1/save/return",
        method: "post",
        data: { id },
        success: (resp) => {
            if (resp.r) {
                swal("", resp.m, "success").then(() => {
                    window.location.reload();
                });
            } else {
                swal("", resp.m, "error");
            }
        },
        error: () => {},
    });
}

function deleteReturnItem(id, position) {
    $.ajax({
        url: "/sapb1/delete/pos_return/" + id,
        method: "delete",
        success: (resp) => {
            $("#tbody-order_returns > tr").eq(position).children("td").remove();
        },
        error: () => {},
    });
}

function B1ReturnItem(order_id, item_id, quantity) {
    let info = {
        order_id,
        item_id,
        quantity,
    };

    let input = document.createElement("input");
    input.value = quantity;
    input.type = "number";
    input.max = quantity;
    input.min = 1;
    input.className = "swal-content__input";

    swal(Lang.get("Do you want to return the item ?"), {
        buttons: {
            cancel: "No",
            Ok: true,
        },
        content: input,
    }).then((val) => {
        if (val == "Ok") {
            if (input.value > quantity) {
                swal(
                    "Invalid value, quantity must be less than the current quantity in order."
                );
                return;
            }

            info.quantity = input.value;

            $.ajax({
                url: "/sapb1/create/return",
                method: "POST",
                contentType: "application/json",
                headers: {
                    "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr(
                        "content"
                    ),
                    "Content-Type": "application/json",
                },
                data: JSON.stringify(info),
                success: (resp) => {
                    if (resp.status) {
                        swal("", resp.m, "success");
                    } else {
                        swal("", resp.m, "error");
                    }
                },
                error: (err) => {},
            });
        }
    });
}

//var needToConfirm = true;
function validateInputs() {
    $(function () {
        $("#phone").keyup(function () {
            this.value = (this.value + "").replace(/[^0-9]/g, "");
        });
        $("#total_price").keyup(function () {
            this.value = (this.value + "").replace(/[^0-9]/g, "");
        });
    });
}

// Modal Attributes
function openAttributes(attributes) {
    var group = attributes.reduce((r, a) => {
        r[a.attribute_id] = [...(r[a.attribute_id] || []), a];
        return r;
    }, {});
    var groupArray = Object.entries(group);
    var formatter = new Intl.NumberFormat("en-US", {
        style: "currency",
        currency: "USD",
        minimumFractionDigits: 0,
    });
    $("#list_attributes").empty();
    if (groupArray.length > 0) {
        for (var i = 0; i < groupArray.length; i++) {
            var sel =
                '<div class="row"><div class="titulo2-modal"><label for="exampleInputPassword1" class="label-product-info">' +
                groupArray[i][1][0].attribute.display_name +
                '</label></div></div><div class="row" style="background-color: #ececec;"> <div class="col-xs-4"><label style="font-weight: 700;">Valor</label></div>  <div class="col-xs-4"><label style="font-weight: 700;">Cantidad</label></div> <div class="col-xs-4"><label style="font-weight: 700;">Precio adicional</label></div>';
            $("#list_attributes").append(sel);
            for (var v = 0; v < groupArray[i][1].length; v++) {
                var attribute = groupArray[i][1][v];
                var quantity = attribute.quantity ? attribute.quantity : 1;
                var pickerColor =
                    attribute.attribute.attribute_type_id == 4
                        ? '<div class="pickerColor" style="background-color:' +
                          attribute.value +
                          ';"></div>'
                        : "";
                var row =
                    '<div class="row"> <div class="col-xs-4"><p>' +
                    attribute.value +
                    pickerColor +
                    '</p></div><div class="col-xs-4"><p>' +
                    quantity +
                    '</p></div><div class="col-xs-4"><p>' +
                    formatter.format(attribute.price_additional) +
                    "</p></div></div></div>";
                $("#list_attributes").append(row);
            }
        }
        $("#modal-attributes-product").modal();
    }
}

function clickCopyOrder(id) {
    console.log(id);
    $(location).attr("href", "/orders/add/" + id);
}

function chargeDataOrder() {
    console.log("hola");

    // var info = {
    //     id: 5,
    //     order_id: id,
    // };

    // $.ajax({
    //     url: "/orders/typeOrder",
    //     type: "POST",
    //     contentType: "application/json",
    //     headers: {
    //         "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
    //         "Content-Type": "application/json",
    //     },
    //     data: JSON.stringify(info),
    //     success: function (data) {
    //         console.log(data);
    //         $("#content-form").empty();
    //         $("#content-form").append(data);
    //         if (id == 5) {
    //             orderReferenceValidate();
    //             viewProductsStorage();
    //             // $('#btn-open-modal-direction-ec').addClass('disabled');
    //         }
    //     },
    //     error: function (e) {},
    // });
}

// MODAL INFO order
function clickInfoOrder(id) {
    $.ajax({
        url: "/orders/info/" + id,
        type: "GET",
        contentType: "application/json",
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
            "Content-Type": "application/json",
        },
        success: function (r) {
            console.log(r);
            order = r.order;
            transfer = r.transfers;
            productsOrder = r.products;
            parameter = r.parameter;

            $("#label_delivery_man").text(parameter.name_delivery_man + ":");

            if (order.discount_price == null) {
                order.discount_price = 0;
            }
            // Create our number formatter.
            var formatter = new Intl.NumberFormat("en-US", {
                style: "currency",
                currency: "USD",
                minimumFractionDigits: 0,
            });

            var district_address = "";
            var current_address = "";
            if (order.address_id) {
                current_address = order.address_id;
                district_address = order.address.district;
            } else {
                current_address = order.point_sale.name;
            }

            $("#code").text(order.code);
            $("#sucursal").text(order.sucursal_id);
            $("#client").text(order.client_id);
            $("#direction").text(current_address);
            $("#district").text(district_address);
            $("#phone").text(order.client.phone);
            $("#sucursalOrigin").text(order.sucursal_origin_id);
            $("#sucursalT").text(order.sucursal_id);
            $("#deliveryMan").text(order.delivery_man_id);
            $("#admin").text(order.admin_id);
            $("#state").text(order.order_state_id);
            $("#time").text(r.time);
            $("#paymentTypes").text(order.payment_type_id);
            $("#isChange").text(order.is_change);
            $("#qualification").text(r.qualification);
            $("#city_name").text(r.city);

            if (order.payment_type.id == 5) {
                $("#payment_state").show();
                if (order.gw_state == "CONFIRMED") {
                    $("#payment_success").show();
                    $("#payment_pending").hide();

                    $("#payment_success").text(
                        "PAGO REF: " + order.gw_code_transaction
                    );
                } else {
                    $("#payment_pending").show();
                    $("#payment_success").hide();

                    $("#payment_pending").text(
                        "PENDIENTE REF: " + order.gw_code_transaction
                    );
                }
            } else {
                $("#payment_state").hide();
            }

            if (order.current_sucursal_id) {
                $("#divSucursalUser").removeClass("hidden");
                $("#sucursalUser").text(r.current_sucursal_id.name);
            } else {
                $("#divSucursalUser").addClass("hidden");
            }

            if (order.discount_delivery > 0) {
                $("#deliveryDiscount").removeClass("hidden");
                var currentValue =
                    order.cost_delivery + order.discount_delivery;
                $("#deliveryDiscount").text(formatter.format(currentValue));
            } else {
                $("#deliveryDiscount").addClass("hidden");
            }
            $("#delivery").text(formatter.format(order.cost_delivery));
            $("#discount").text(formatter.format(order.discount_price));
            if (order.subtotal) {
                $("#subtotal").text(formatter.format(order.subtotal));
            } else {
                $("#subtotal").text("$" + "");
            }

            if (order.discount_price > 0) {
                $("#totalDiscount").removeClass("hidden");
                var currentValueTotal =
                    order.total_price + order.discount_price;
                $("#totalDiscount").text(formatter.format(currentValueTotal));
            } else {
                $("#totalDiscount").addClass("hidden");
            }
            $("#total").text(formatter.format(order.total_price));
            $("#typeOrder").text(r.order_type);

            if (order.instructions) {
                $("#instructions").text(order.instructions);
            } else {
                $("#instructions").text("Ninguna");
            }

            if (order.discount_order_user.length) {
                var discountActive = "";
                for (var i = 0; i < order.discount_order_user.length; i++) {
                    if (i == 0) {
                        discountActive =
                            order.discount_order_user[i].discount.name;
                    } else {
                        discountActive +=
                            ", " + order.discount_order_user[i].discount.name;
                    }
                }
                $("#listDiscounts").text(discountActive);
            } else {
                discountActive = "Sin descuentos";
                $("#listDiscounts").text(discountActive);
            }

            if (order.cost_real) {
                $("#cost_real").text(formatter.format(order.cost_real));
            } else {
                $("#cost_real").text("");
            }

            switch (order.order_type_id) {
                case 1:
                    $("#file_info_client").css("display", "block");
                    $("#file_info_direction").css("display", "block");
                    $("#file_info_district").css("display", "block");
                    $("#file_info_phone").css("display", "block");
                    $("#info_type_sale").css("display", "block");
                    $("#info_type_transfer").css("display", "none");
                    $("#cost_real").css("display", "none");
                    break;
                case 2:
                    $("#info_type_sale").css("display", "block");
                    $("#info_type_transfer").css("display", "none");
                    $("#file_info_client").css("display", "none");
                    $("#file_info_direction").css("display", "none");
                    $("#file_info_phone").css("display", "none");
                    $("#cost_real").css("display", "none");
                    break;
                case 3:
                    $("#info_type_sale").css("display", "none");
                    $("#info_type_transfer").css("display", "block");
                    $("#cost_real").css("display", "none");
                    break;
                case 4:
                    $("#info_type_sale").css("display", "block");
                    $("#info_type_transfer").css("display", "none");
                    $("#file_info_client").css("display", "none");
                    $("#file_info_direction").css("display", "none");
                    $("#file_info_phone").css("display", "none");
                    $("#cost_real").css("display", "none");
                    break;
                case 5:
                    $("#file_info_client").css("display", "block");
                    $("#file_info_direction").css("display", "block");
                    $("#file_info_district").css("display", "block");
                    $("#file_info_phone").css("display", "block");
                    $("#info_type_sale").css("display", "block");
                    $("#info_type_transfer").css("display", "none");
                    $("#cost_real").css("display", "block");
                    break;

                default:
                    break;
            }

            $("#list_transfer").empty();
            $("#list_products").empty();

            if (productsOrder.length > 0) {
                var sel =
                    '<div class="row" style="background-color: #ececec;"> <div class="col-xs-4"><label style="font-weight: 700;">Nombre</label></div>  <div class="col-xs-2"><label style="font-weight: 700;">Cantidad</label></div> <div class="col-xs-2"><label style="font-weight: 700;">Valor U</label></div> <div class="col-xs-2"><label style="font-weight: 700;">Valor</label></div> <div class="col-xs-2"><label style="font-weight: 700;">Disponibilidad</label></div></div>';
                $("#list_products").append(sel);
                for (let i = 0; i < productsOrder.length; i++) {
                    if (productsOrder[i].available == 1) {
                        available =
                            '<span class="label label-success labelCollected">Disponible</span>';
                    } else if (
                        productsOrder[i].available == 0 &&
                        productsOrder[i].replace_by != null
                    ) {
                        available =
                            '<span class="label label-warning">Reemplazado</span>';
                    } else {
                        available =
                            '<span class="label label-warning">No disponible</span>';
                    }

                    if (productsOrder[i].discount > 0) {
                        value =
                            productsOrder[i].quantity *
                            productsOrder[i].discount;
                        var row =
                            '<div class="row"> <div class="col-xs-4"><p>' +
                            productsOrder[i].name +
                            '</p></div><div class="col-xs-2"  ><p>' +
                            productsOrder[i].quantity +
                            '</p></div><div class="col-xs-2" style="display: flex;"><p style="text-decoration:line-through;">' +
                            formatter.format(productsOrder[i].price) +
                            '</p> <p style="color:#e62e00; margin-left: 5px;">' +
                            formatter.format(productsOrder[i].discount) +
                            '</p> </div><div class="col-xs-2"><p>' +
                            formatter.format(value) +
                            '</p></div><div class="col-xs-2">' +
                            available +
                            "</div></div>";
                    } else {
                        if (productsOrder[i].flash_price) {
                            value =
                                productsOrder[i].quantity *
                                productsOrder[i].flash_price;
                            var row =
                                '<div class="row"> <div class="col-xs-4"><p>' +
                                productsOrder[i].name +
                                '</p></div><div class="col-xs-2"><p>' +
                                productsOrder[i].quantity +
                                '</p></div><div class="col-xs-2" style="display: flex;"><p style="text-decoration:line-through;">' +
                                formatter.format(productsOrder[i].price) +
                                '</p> <p style="color:#e62e00; margin-left: 5px;">' +
                                formatter.format(productsOrder[i].flash_price) +
                                '</p> </div><div class="col-xs-2"><p>' +
                                formatter.format(value) +
                                '</p></div><div class="col-xs-2">' +
                                available +
                                "</div></div>";
                        } else {
                            value =
                                productsOrder[i].quantity *
                                productsOrder[i].price;
                            var row =
                                '<div class="row"> <div class="col-xs-4"><p>' +
                                productsOrder[i].name +
                                '</p></div><div class="col-xs-2"><p>' +
                                productsOrder[i].quantity +
                                '</p></div><div class="col-xs-2"><p>' +
                                formatter.format(productsOrder[i].price) +
                                '</p></div><div class="col-xs-2"><p>' +
                                formatter.format(value) +
                                '</p></div><div class="col-xs-2">' +
                                available +
                                "</div></div>";
                        }
                    }
                    $("#list_products").append(row);
                }
                $("#modal-info-order").modal();
            } else {
                if (order.express_products == null) {
                    order.express_products = "No hay productos";
                }
                var row =
                    '<div class="row"> <div class="col-xs-12"><textarea rows="7" style="width:100%;" disabled>' +
                    order.express_products +
                    "</textarea></div></div>";
                $("#list_products").append(row);
                $("#modal-info-order").modal();
                $("#sub_row").css("display", "none");
                $("#dom_row").css("display", "none");
            }
            console.log(transfer.length);
            if (transfer.length > 0) {
                var sel =
                    '<div class="row" style="background-color: #ececec;"> <div class="col-xs-5"><label style="font-weight: 700;">Sucursal</label></div>  <div class="col-xs-4"><label style="font-weight: 700;">Productos</label></div><div class="col-xs-3"><label style="font-weight: 700;">Estado</label></div> </div>';
                $("#list_transfer").append(sel);
                for (let i = 0; i < transfer.length; i++) {
                    console.log(transfer[i].sucursal);
                    if (transfer[i].date) {
                        var row =
                            '<div class="row"> <div class="col-xs-5"><p>' +
                            transfer[i].sucursal +
                            '</p></div><div class="col-xs-4"><p>' +
                            transfer[i].description +
                            '</p></div><div class="col-xs-3"><span class="label label-success labelCollected">Recogido</span></div></div>';
                    } else {
                        var row =
                            '<div class="row"> <div class="col-xs-5"><p>' +
                            transfer[i].sucursal +
                            '</p></div><div class="col-xs-4"><p>' +
                            transfer[i].description +
                            '</p></div><div class="col-xs-3"><span class="label label-warning">Pendiente</span></div></div>';
                    }
                    $("#list_transfer").append(row);
                }
                $("#transfer_row").css("display", "block");

                $("#modal-info-order").modal();
            } else {
                $("#transfer_row").css("display", "none");
            }
        },
    });
}

function clickDeleteOrder(id) {
    console.log(id);
    var info = {
        id: id,
    };
    swal(Lang.get("¿Esta seguro de eliminar el pedido?"), {
        buttons: {
            cancel: "No",
            Ok: true,
        },
    }).then((val) => {
        if (val == "Ok") {
            $.ajax({
                url: "/orders/deleteOrder",
                type: "POST",
                contentType: "application/json",
                headers: {
                    "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr(
                        "content"
                    ),
                    "Content-Type": "application/json",
                },
                data: JSON.stringify(info),
                success: function (r) {
                    if (r.status == "success") {
                        swal(Lang.get("Orden eliminada"), {
                            icon: "success",
                            buttons: {
                                Ok: "OK",
                            },
                        }).then((val) => {
                            window.onbeforeunload = null;
                            $(location).attr("href", "/orders");
                        });
                    } else {
                        swal("Advertencia", r.status, "warning");
                        $("#btn-edit-order").prop("disabled", false);
                    }
                },
            });
        } else {
            $("#btn-edit-order").prop("disabled", false);
        }
    });
}

// actions table
function clickEditOrder(value) {
    _table = $("#example2").DataTable();
    index = _table.page();
    localStorage.setItem("productsTableIndex", index);
    $(location).attr("href", "/orders/edit/" + value);
}

function clickEditTransfer(value) {
    _table = $("#example2").DataTable();
    index = _table.page();
    localStorage.setItem("productsTableIndex", index);
    $(location).attr("href", "/orders/transfer/" + value);
}

function clickEvidence(value) {
    _table = $("#example2").DataTable();
    index = _table.page();
    localStorage.setItem("productsTableIndex", index);
    $(location).attr("href", "/orders/evidence/" + value);
}

function clickCommand(value) {
    printInvoice(value);
}

function editOrderEC(id) {
    $("#editOrder").validator("update");
    $("#editOrder")
        .validator("update")
        .on("submit", function (e) {
            e.preventDefault();
            $("#btn-edit-order").prop("disabled", true);

            var arrayProducts = localStorage.getItem("arrayProducts");
            if (arrayProducts && arrayProducts != "") {
                arrayProducts = JSON.parse(arrayProducts);
            } else {
                arrayProducts = [];
            }
            var info = {
                data: {
                    id: id,
                    order_state_id: $(
                        " #editOrder select[name='order_state_id']"
                    ).val(),
                    delivery_man_id: $(
                        " #editOrder select[name='delivery_man_id']"
                    ).val(),
                },
                addProducts: arrayProducts,
                sucursalsTransf: [],
                productsTransf: [],
            };
            var sucursals = [];
            var j = 0;
            for (let index = 0; index < 10; index++) {
                if ($("#st" + index).length) {
                    if ($("#st" + index).val() != "ninguna") {
                        sucursals[j] = $("#st" + index).val();
                        j++;
                    }
                }
            }
            info.sucursalsTransf.push(sucursals);

            var products = [];
            var l = 0;
            for (let i = 0; i < 10; i++) {
                if ($("#pt" + i).length) {
                    products[l] = $("#pt" + i).val();
                    l++;
                }
                info.productsTransf.push(products);
                if (sucursals.length == products.length) {
                    swal(Lang.get("messagesClient.orders_tag7"), {
                        buttons: {
                            cancel: "No",
                            Ok: true,
                        },
                    }).then((val) => {
                        if (val == "Ok") {
                            $("#modalLoader").modal("show");
                            $("#modalLoader").css("display", "flex");
                            $.ajax({
                                url: "/orders/update",
                                type: "POST",
                                contentType: "application/json",
                                headers: {
                                    "X-CSRF-TOKEN": $(
                                        'meta[name="csrf-token"]'
                                    ).attr("content"),
                                    "Content-Type": "application/json",
                                },
                                data: JSON.stringify(info),
                                success: function (r) {
                                    $("#modalLoader").modal("hide");
                                    $("#modalLoader").css("display", "none");
                                    console.log(r);
                                    if (r.r) {
                                        swal(
                                            Lang.get(
                                                "messagesClient.orders_tag9"
                                            ),
                                            {
                                                icon: "success",
                                                buttons: {
                                                    Ok: true,
                                                },
                                            }
                                        ).then((val) => {
                                            if (val == "Ok") {
                                                localStorage.setItem(
                                                    "arrayProducts",
                                                    ""
                                                );
                                                localStorage.setItem(
                                                    "setPageTable",
                                                    true
                                                );
                                                $(location).attr(
                                                    "href",
                                                    "/orders"
                                                );
                                            }
                                        });
                                    } else {
                                        if (r.m && r.m != "") {
                                            swal("Error", r.m, "error");
                                        } else {
                                            swal(
                                                "Error",
                                                Lang.get(
                                                    "messagesClient.orders_tag8"
                                                ),
                                                "error"
                                            );
                                        }
                                        $("#btn-edit-order").prop(
                                            "disabled",
                                            false
                                        );
                                    }
                                },
                                error: function (e) {
                                    $("#modalLoader").modal("hide");
                                    $("#modalLoader").css("display", "none");
                                    swal(
                                        "Error",
                                        Lang.get("messagesClient.orders_tag8"),
                                        "error"
                                    );
                                    $("#btn-edit-order").prop(
                                        "disabled",
                                        false
                                    );
                                },
                            });
                        } else {
                            $("#btn-edit-order").prop("disabled", false);
                        }
                    });
                } else {
                    swal(
                        "Advertencia",
                        "¡Debe seleccionar sucursal para cada transferencia!",
                        "warning"
                    );
                    $("#btn-edit-order").prop("disabled", false);
                }
            }
        });
}

function editOrderSale(id) {
    console.log("editar order");

    $("#editOrder").validator("update");
    $("#editOrder")
        .validator("update")
        .on("submit", function (e) {
            if (e.isDefaultPrevented()) {
            } else {
                e.preventDefault();
                $("#btn-edit-order").prop("disabled", true);

                var info = {
                    data: {
                        id: id,
                        order_state_id: $(
                            " #editOrder select[name='order_state_id']"
                        ).val(),
                        delivery_man_id: $(
                            " #editOrder select[name='delivery_man_id']"
                        ).val(),
                        user_id: $(" #editOrder input[name='user_id']").attr(
                            "data-id"
                        ),
                        first_name: $(
                            " #editOrder input[name='user_id']"
                        ).val(),
                        last_name: $(
                            " #editOrder input[name='last_name']"
                        ).val(),
                        document: $("#editOrder input[name='document']").val(),
                        direction:
                            document.getElementById("address_id_sales")
                                .selectedOptions[0].text,
                        lat: $("#address_id_sales option:selected").attr(
                            "data-lat"
                        ),
                        long: $("#address_id_sales option:selected").attr(
                            "data-long"
                        ),
                        direction_id: $("#address_id_sales").val(),
                        phone: $(" #editOrder input[name='phone']").val(),
                        indications: $(
                            "#address_id_sales option:selected"
                        ).attr("indications"),
                        payment_type_id: $(
                            " #editOrder select[name='payment_type_id']"
                        ).val(),
                        district: $("#address_id_sales option:selected").attr(
                            "district"
                        ),
                        sucursal_id: $(
                            "#editOrder select[name='sucursal_id']"
                        ).val(),
                        express_products: $(
                            "#editOrder textarea[name='express_products']"
                        ).val(),
                        total_price: $(
                            "#editOrder input[name='total_price']"
                        ).val(),
                        discount: $("#editOrder input[name='discount']").val(),
                        line_businesses_id: $(
                            "#editOrder select[name='line_businesses_id']"
                        ).val(),
                        sales_channel_id: $(
                            "#editOrder select[name='sales_channel_id']"
                        ).val(),
                        city_id: $("#editOrder select[name='city_id']").val(),
                    },

                    sucursalsTransf: [],
                    productsTransf: [],
                };
                var sucursals = [];
                var j = 0;
                for (let index = 0; index < 10; index++) {
                    if ($("#st" + index).length) {
                        if ($("#st" + index).val() != "ninguna") {
                            sucursals[j] = $("#st" + index).val();
                            j++;
                        }
                    }
                }
                info.sucursalsTransf.push(sucursals);

                var products = [];
                var l = 0;
                for (let i = 0; i < 10; i++) {
                    if ($("#pt" + i).length) {
                        products[l] = $("#pt" + i).val();
                        l++;
                    }
                }
                info.productsTransf.push(products);

                if (sucursals.length == products.length) {
                    swal(Lang.get("messagesClient.orders_tag7"), {
                        buttons: {
                            cancel: "No",
                            Ok: true,
                        },
                    }).then((val) => {
                        if (val == "Ok") {
                            $("#modalLoader").modal("show");
                            $("#modalLoader").css("display", "flex");
                            $.ajax({
                                url: "/orders/update",
                                type: "POST",
                                contentType: "application/json",
                                headers: {
                                    "X-CSRF-TOKEN": $(
                                        'meta[name="csrf-token"]'
                                    ).attr("content"),
                                    "Content-Type": "application/json",
                                },
                                data: JSON.stringify(info),
                                success: function (r) {
                                    $("#modalLoader").modal("hide");
                                    $("#modalLoader").css("display", "none");
                                    console.log(r);
                                    if (r.r) {
                                        swal(
                                            Lang.get(
                                                "messagesClient.orders_tag9"
                                            ),
                                            {
                                                icon: "success",
                                                buttons: {
                                                    Ok: true,
                                                },
                                            }
                                        ).then((val) => {
                                            if (val == "Ok") {
                                                localStorage.setItem(
                                                    "setPageTable",
                                                    true
                                                );
                                                $(location).attr(
                                                    "href",
                                                    "/orders"
                                                );
                                            }
                                        });
                                    } else {
                                        swal(
                                            "Error",
                                            Lang.get(
                                                "messagesClient.orders_tag8"
                                            ),
                                            "error"
                                        );
                                        $("#btn-edit-order").prop(
                                            "disabled",
                                            false
                                        );
                                    }
                                },
                                error: function (e) {
                                    $("#modalLoader").modal("hide");
                                    $("#modalLoader").css("display", "none");
                                    swal(
                                        "Error",
                                        Lang.get("messagesClient.orders_tag8"),
                                        "error"
                                    );
                                    $("#btn-edit-order").prop(
                                        "disabled",
                                        false
                                    );
                                },
                            });
                        } else {
                            $("#btn-editar-order").prop("disabled", false);
                        }
                    });
                } else {
                    swal(
                        "Advertencia",
                        "¡Debe seleccionar sucursal para cada transferencia!",
                        "warning"
                    );
                    $("#btn-editar-order").prop("disabled", false);
                }
            }
        });
}

function editOrderTransfer(id) {
    console.log("editar order");

    $("#editOrder").validator("update");
    $("#editOrder")
        .validator("update")
        .on("submit", function (e) {
            if (e.isDefaultPrevented()) {
            } else {
                e.preventDefault();
                $("#btn-edit-order").prop("disabled", true);

                var info = {
                    data: {
                        id: id,
                        order_state_id: $(
                            " #editOrder select[name='order_state_id']"
                        ).val(),
                        delivery_man_id: $(
                            " #editOrder select[name='delivery_man_id']"
                        ).val(),
                        sucursal_id: $(
                            "#editOrder select[name='sucursal_id']"
                        ).val(),
                        sucursal_origin_id: $(
                            "#editOrder select[name='sucursal_origin_id']"
                        ).val(),
                        express_products: $(
                            "#editOrder textarea[name='express_products']"
                        ).val(),
                    },

                    sucursalsTransf: [],
                    productsTransf: [],
                };
                var sucursals = [];
                var j = 0;
                for (let index = 0; index < 10; index++) {
                    if ($("#st" + index).length) {
                        if ($("#st" + index).val() != "") {
                            sucursals[j] = $("#st" + index).val();
                            j++;
                        }
                    }
                }
                info.sucursalsTransf.push(sucursals);

                var products = [];
                var l = 0;
                for (let i = 0; i < 10; i++) {
                    if ($("#pt" + i).length) {
                        products[l] = $("#pt" + i).val();
                        l++;
                    }
                }
                info.productsTransf.push(products);
                if (sucursals.length == products.length) {
                    swal(Lang.get("messagesClient.orders_tag7"), {
                        buttons: {
                            cancel: "No",
                            Ok: true,
                        },
                    }).then((val) => {
                        if (val == "Ok") {
                            $("#modalLoader").modal("show");
                            $("#modalLoader").css("display", "flex");
                            $.ajax({
                                url: "/orders/update",
                                type: "POST",
                                contentType: "application/json",
                                headers: {
                                    "X-CSRF-TOKEN": $(
                                        'meta[name="csrf-token"]'
                                    ).attr("content"),
                                    "Content-Type": "application/json",
                                },
                                data: JSON.stringify(info),
                                success: function (r) {
                                    $("#modalLoader").modal("hide");
                                    $("#modalLoader").css("display", "none");
                                    console.log(r);
                                    if (r.r) {
                                        swal(
                                            Lang.get(
                                                "messagesClient.orders_tag9"
                                            ),
                                            {
                                                icon: "success",
                                                buttons: {
                                                    Ok: true,
                                                },
                                            }
                                        ).then((val) => {
                                            if (val == "Ok") {
                                                localStorage.setItem(
                                                    "setPageTable",
                                                    true
                                                );
                                                $(location).attr(
                                                    "href",
                                                    "/orders"
                                                );
                                            }
                                        });
                                    } else {
                                        swal(
                                            "Error",
                                            Lang.get(
                                                "messagesClient.orders_tag8"
                                            ),
                                            "error"
                                        );
                                        $("#btn-edit-order").prop(
                                            "disabled",
                                            false
                                        );
                                    }
                                },
                                error: function (e) {
                                    $("#modalLoader").modal("hide");
                                    $("#modalLoader").css("display", "none");
                                    swal(
                                        "Error",
                                        Lang.get("messagesClient.orders_tag8"),
                                        "error"
                                    );
                                    $("#btn-edit-order").prop(
                                        "disabled",
                                        false
                                    );
                                },
                            });
                        } else {
                            $("#btn-edit-order").prop("disabled", false);
                        }
                    });
                } else {
                    swal(
                        "Advertencia",
                        "¡Debe seleccionar sucursal para cada transferencia!",
                        "warning"
                    );
                    $("#btn-edit-order").prop("disabled", false);
                }
            }
        });
}

function editOrderAlliance(id) {
    console.log("editar order");

    $("#editOrder").validator("update");
    $("#editOrder")
        .validator("update")
        .on("submit", function (e) {
            if (e.isDefaultPrevented()) {
            } else {
                e.preventDefault();
                $("#btn-edit-order").prop("disabled", true);

                var info = {
                    data: {
                        id: id,
                        order_state_id: $(
                            " #editOrder select[name='order_state_id']"
                        ).val(),
                        delivery_man_id: $(
                            " #editOrder select[name='delivery_man_id']"
                        ).val(),
                        sucursal_id: $(
                            "#editOrder select[name='sucursal_id']"
                        ).val(),
                        express_products: $(
                            "#editOrder textarea[name='express_products']"
                        ).val(),
                    },
                    sucursalsTransf: [],
                    productsTransf: [],
                };
                var sucursals = [];
                var j = 0;
                for (let index = 0; index < 10; index++) {
                    if ($("#st" + index).length) {
                        if ($("#st" + index).val() != "") {
                            sucursals[j] = $("#st" + index).val();
                            j++;
                        }
                    }
                }
                info.sucursalsTransf.push(sucursals);

                var products = [];
                var l = 0;
                for (let i = 0; i < 10; i++) {
                    if ($("#pt" + i).length) {
                        products[l] = $("#pt" + i).val();
                        l++;
                    }
                }
                info.productsTransf.push(products);
                if (sucursals.length == products.length) {
                    swal(Lang.get("messagesClient.orders_tag7"), {
                        buttons: {
                            cancel: "No",
                            Ok: true,
                        },
                    }).then((val) => {
                        if (val == "Ok") {
                            $("#modalLoader").modal("show");
                            $("#modalLoader").css("display", "flex");
                            $.ajax({
                                url: "/orders/update",
                                type: "POST",
                                contentType: "application/json",
                                headers: {
                                    "X-CSRF-TOKEN": $(
                                        'meta[name="csrf-token"]'
                                    ).attr("content"),
                                    "Content-Type": "application/json",
                                },
                                data: JSON.stringify(info),
                                success: function (r) {
                                    $("#modalLoader").modal("hide");
                                    $("#modalLoader").css("display", "none");
                                    console.log(r);
                                    if (r.r) {
                                        swal(
                                            Lang.get(
                                                "messagesClient.orders_tag9"
                                            ),
                                            {
                                                icon: "success",
                                                buttons: {
                                                    Ok: true,
                                                },
                                            }
                                        ).then((val) => {
                                            if (val == "Ok") {
                                                localStorage.setItem(
                                                    "setPageTable",
                                                    true
                                                );

                                                $(location).attr(
                                                    "href",
                                                    "/orders"
                                                );
                                            }
                                        });
                                    } else {
                                        swal(
                                            "Error",
                                            Lang.get(
                                                "messagesClient.orders_tag8"
                                            ),
                                            "error"
                                        );
                                        $("#btn-edit-order").prop(
                                            "disabled",
                                            false
                                        );
                                    }
                                },
                                error: function (e) {
                                    $("#modalLoader").modal("hide");
                                    $("#modalLoader").css("display", "none");
                                    swal(
                                        "Error",
                                        Lang.get("messagesClient.orders_tag8"),
                                        "error"
                                    );
                                    $("#btn-edit-order").prop(
                                        "disabled",
                                        false
                                    );
                                },
                            });
                        } else {
                            $("#btn-edit-order").prop("disabled", false);
                        }
                    });
                } else {
                    swal(
                        "Advertencia",
                        "¡Debe seleccionar sucursal para cada transferencia!",
                        "warning"
                    );
                    $("#btn-edit-order").prop("disabled", false);
                }
            }
        });
}

function editOrderDiligence(id) {
    console.log("editar order");

    $("#editOrder").validator("update");
    $("#editOrder")
        .validator("update")
        .on("submit", function (e) {
            if (e.isDefaultPrevented()) {
            } else {
                e.preventDefault();
                $("#btn-edit-order").prop("disabled", true);

                var info = {
                    data: {
                        id: id,
                        order_state_id: $(
                            " #editOrder select[name='order_state_id']"
                        ).val(),
                        delivery_man_id: $(
                            " #editOrder select[name='delivery_man_id']"
                        ).val(),
                        sucursal_id: $(
                            "#editOrder select[name='sucursal_id']"
                        ).val(),
                        express_products: $(
                            "#editOrder textarea[name='express_products']"
                        ).val(),
                    },
                    sucursalsTransf: [],
                    productsTransf: [],
                };
                var sucursals = [];
                var j = 0;
                for (let index = 0; index < 10; index++) {
                    if ($("#st" + index).length) {
                        if ($("#st" + index).val() != "") {
                            sucursals[j] = $("#st" + index).val();
                            j++;
                        }
                    }
                }
                info.sucursalsTransf.push(sucursals);

                var products = [];
                var l = 0;
                for (let i = 0; i < 10; i++) {
                    if ($("#pt" + i).length) {
                        products[l] = $("#pt" + i).val();
                        l++;
                    }
                }
                info.productsTransf.push(products);
                if (sucursals.length == products.length) {
                    swal(Lang.get("messagesClient.orders_tag7"), {
                        buttons: {
                            cancel: "No",
                            Ok: true,
                        },
                    }).then((val) => {
                        if (val == "Ok") {
                            $("#modalLoader").modal("show");
                            $("#modalLoader").css("display", "flex");
                            $.ajax({
                                url: "/orders/update",
                                type: "POST",
                                contentType: "application/json",
                                headers: {
                                    "X-CSRF-TOKEN": $(
                                        'meta[name="csrf-token"]'
                                    ).attr("content"),
                                    "Content-Type": "application/json",
                                },
                                data: JSON.stringify(info),
                                success: function (r) {
                                    $("#modalLoader").modal("hide");
                                    $("#modalLoader").css("display", "none");
                                    console.log(r);
                                    if (r.r) {
                                        swal(
                                            Lang.get(
                                                "messagesClient.orders_tag9"
                                            ),
                                            {
                                                icon: "success",
                                                buttons: {
                                                    Ok: true,
                                                },
                                            }
                                        ).then((val) => {
                                            if (val == "Ok") {
                                                localStorage.setItem(
                                                    "setPageTable",
                                                    true
                                                );
                                                $(location).attr(
                                                    "href",
                                                    "/orders"
                                                );
                                            }
                                        });
                                    } else {
                                        swal(
                                            "Error",
                                            Lang.get(
                                                "messagesClient.orders_tag8"
                                            ),
                                            "error"
                                        );
                                        $("#btn-edit-order").prop(
                                            "disabled",
                                            false
                                        );
                                    }
                                },
                                error: function (e) {
                                    $("#modalLoader").modal("hide");
                                    $("#modalLoader").css("display", "none");
                                    swal(
                                        "Error",
                                        Lang.get("messagesClient.orders_tag8"),
                                        "error"
                                    );
                                    $("#btn-edit-order").prop(
                                        "disabled",
                                        false
                                    );
                                },
                            });
                        } else {
                            $("#btn-edit-order").prop("disabled", false);
                        }
                    });
                } else {
                    swal(
                        "Advertencia",
                        "¡Debe seleccionar sucursal para cada transferencia!",
                        "warning"
                    );
                    $("#btn-edit-order").prop("disabled", false);
                }
            }
        });
}

function createSelectDirections(direction) {
    $("#address_id").empty();
    // $('#btn-open-modal-direction-ec').removeClass('disabled');
    var sel = '<option value="">--Seleccione</option>';
    $("#address_id").append(sel);
    for (var i in direction) {
        if (direction[i].last_used == 1) {
            var row =
                '<option value="' +
                direction[i].id +
                '" selected="selected">' +
                direction[i].direction +
                "</option>";
            $("#address_id").append(row);
        } else {
            var row =
                '<option value="' +
                direction[i].id +
                '" >' +
                direction[i].direction +
                "</option>";
            $("#address_id").append(row);
        }
    }
}

function autocompleteDocument(typeOrder) {
    $("#document").keyup(function (e) {
        if (e.keyCode == 8 || e.keyCode == 46 || e.keyCode == 32) {
            $("#user_id").attr("data-id", "");
            document.getElementById("createOrder").reset();
        }
    });
    $("#document").autocomplete({
        source: "/client/autocomplete",
        minLength: 3,
        select: function (event, ui) {
            $("#user_id").val(ui.item.first_name);
            $("#last_name").val(ui.item.last_name);
            $("#user_id").attr("data-id", ui.item.id);
            $("#document").val(ui.item.document);
            $("#phone").val(ui.item.phone);

            direction = ui.item.directions;

            switch (
                typeOrder // segun el tipo de pedido maneja las direcciones
            ) {
                case 1:
                    // console.log(ui);
                    // for (var i in direction) {
                    //     if (direction[i].last_used == 1) {
                    //         console.log(direction[i]);
                    //         $("#direction").val(direction[i].direction);
                    //         $("#direction").attr("data-id", direction[i].id);
                    //         $("#direction").attr("data-lat", direction[i].lat);
                    //         $("#direction").attr("data-long", direction[i].long);
                    //         $("#district").val(direction[i].district);
                    //         $("#indications").val(direction[i].indications);
                    //         $("#city_id").val(direction[i].city_id);
                    //         // calculoCobertura(direction[i].lat, direction[i].long);
                    //     }
                    // }

                    $("#address_id_sales").empty();
                    var sel = '<option value="">--Seleccione</option>';
                    $("#address_id_sales").append(sel);
                    for (var i in direction) {
                        $("#district").val(direction[i].district);
                        $("#indications").val(direction[i].indications);
                        $("#city_id").val(direction[i].city_id);
                        if (direction[i].last_used == 1) {
                            var row =
                                '<option value="' +
                                direction[i].id +
                                '" data-lat="' +
                                direction[i].lat +
                                '"' +
                                ' data-long="' +
                                direction[i].long +
                                '"' +
                                ' indications="' +
                                direction[i].indications +
                                '"' +
                                ' district="' +
                                direction[i].district +
                                '"' +
                                ' selected="selected">' +
                                direction[i].direction +
                                "</option>";
                            $("#address_id_sales").append(row);
                        } else {
                            var row =
                                '<option value="' +
                                direction[i].id +
                                '" data-lat="' +
                                direction[i].lat +
                                '"' +
                                ' data-long="' +
                                direction[i].long +
                                '"' +
                                ' indications="' +
                                direction[i].indications +
                                '"' +
                                ' district="' +
                                direction[i].district +
                                '">' +
                                direction[i].direction +
                                '"' +
                                "</option>";
                            $("#address_id_sales").append(row);
                        }
                    }
                    break;
                case 5:
                    $("#email").val(ui.item.email);
                    createSelectDirections(direction);

                    //descuentos
                    //primero se eliminan los tr del anterior cliente
                    if ($("#tr-discountDelivery").length > 0) {
                        $("#tr-discountDelivery").remove();
                    }
                    if ($("#tr-discountReferred").length > 0) {
                        $("#tr-discountReferred").remove();
                    }
                    if ($("#tr-discountCoupone").length > 0) {
                        $("#tr-discountCoupone").remove();
                    }
                    if ($("#tr-discountCampana").length > 0) {
                        $("#tr-discountCampana").remove();
                    }

                    //envio
                    if (ui.item.is_register_discount_active) {
                        var rDelivery = discountDelivery(
                            ui.item.created_at,
                            ui.item.days_register_discount_delivery
                        );
                        if (rDelivery) {
                            var tr =
                                '<tr id="tr-discountDelivery"><th>Descuento envío:</th><td class="col-label"><h4 id="discountDelivery" class="label-number-order">' +
                                ui.item.register_discount_delivery +
                                "</h4>%</td></tr>";
                            $("#tableTotal >tbody").append(tr);
                        }
                    }

                    // console.log('lastOrders: ', ui.item.lastOrders);

                    if (ui.item.lastOrders && ui.item.lastOrders.length) {
                        for (var i = 0; i < ui.item.lastOrders.length; i++) {
                            for (
                                var j = 0;
                                j < ui.item.lastOrders[i].order_products.length;
                                j++
                            ) {
                                var tr =
                                    `<tr>
                    <td>` +
                                    ui.item.lastOrders[i].order_products[j]
                                        .products.plu +
                                    `</td>
                    <td>` +
                                    ui.item.lastOrders[i].order_products[j]
                                        .products.name +
                                    `</td>
                    <td>` +
                                    ui.item.lastOrders[i].order_products[j]
                                        .products.bar_code +
                                    `</td>
                    <td>` +
                                    ui.item.lastOrders[i].order_products[j]
                                        .price +
                                    `</td>
                    <td>` +
                                    ui.item.lastOrders[i].order_products[j]
                                        .quantity +
                                    `</td>
                  </tr>`;
                                $("#tbodyHistoryProducts").append(tr);
                            }
                        }
                    }

                    //referido
                    if (ui.item.clientRefer != null) {
                        discountReferred(ui.item.discounts);
                    }

                    //campaña
                    discountCampana(ui.item.discounts);

                    //colocar el id en input de cupon
                    $("#discountCoupon").attr("data-id", ui.item.id);
                    break;
            }
        },
    });

    function fillNameClient(idUser, nameUser) {
        $("input[name='user_id']").val(idUser);
        $("input[name='user_id']").attr("data-id", nameUser);
    }

    //metodo de al dar enter en el input cedula se traigan los datos del cliente
    $(function () {
        $("#document").keyup(function () {
            this.value = (this.value + "").replace(/[^0-9]/g, "");
        });

        $("#document").keypress(function (e) {
            if (e.which == 13) {
                cedula = $("#document").val();
                type = $("#document").attr("data-typeOrder");
                console.log(cedula);

                if (cedula.length > 0) {
                    $.ajax({
                        url: "/clients/document/" + cedula,
                        type: "GET",
                        contentType: "application/json",
                        headers: {
                            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr(
                                "content"
                            ),
                            "Content-Type": "application/json",
                        },
                        success: function (r) {
                            if (r.r) {
                                /// modificar
                                $("#user_id").val(r.client.first_name);
                                $("#last_name").val(r.client.last_name);
                                $("#user_id").attr("data-id", r.client.id);
                                $("#document").val(r.client.document);
                                $("#phone").val(r.client.phone);

                                switch (
                                    type // segun el tipo de pedido maneja las direcciones
                                ) {
                                    case "1":
                                        // $("#direction").val(r.direction);
                                        // $("#direction").attr("data-id", r.id);
                                        // $("#direction").attr("data-lat", r.lat);
                                        // $("#direction").attr("data-long", r.long);
                                        // $("#district").val(r.district);
                                        // $("#indications").val(r.indications);
                                        $("#address_id_sales").empty();
                                        var sel =
                                            '<option value="">--Seleccione</option>';
                                        $("#address_id_sales").append(sel);
                                        for (var i in direction) {
                                            $("#district").val(
                                                direction[i].district
                                            );
                                            $("#indications").val(
                                                direction[i].indications
                                            );
                                            $("#city_id").val(
                                                direction[i].city_id
                                            );
                                            if (direction[i].last_used == 1) {
                                                var row =
                                                    '<option value="' +
                                                    direction[i].id +
                                                    '" data-lat="' +
                                                    direction[i].lat +
                                                    '"' +
                                                    ' data-long="' +
                                                    direction[i].long +
                                                    '"' +
                                                    ' indications="' +
                                                    direction[i].indications +
                                                    '"' +
                                                    ' district="' +
                                                    direction[i].district +
                                                    '"' +
                                                    ' selected="selected">' +
                                                    direction[i].direction +
                                                    "</option>";
                                                $("#address_id_sales").append(
                                                    row
                                                );
                                            } else {
                                                var row =
                                                    '<option value="' +
                                                    direction[i].id +
                                                    '" data-lat="' +
                                                    direction[i].lat +
                                                    '"' +
                                                    ' data-long="' +
                                                    direction[i].long +
                                                    ' indications="' +
                                                    direction[i].indications +
                                                    '"' +
                                                    ' district="' +
                                                    direction[i].district +
                                                    '">' +
                                                    direction[i].direction +
                                                    '"' +
                                                    "</option>";
                                                $("#address_id_sales").append(
                                                    row
                                                );
                                            }
                                        }
                                        break;
                                    case "5":
                                        $("#email").val(r.client.email);
                                        $("#address_id").empty();
                                        var sel =
                                            '<option value="">--Seleccione</option>';
                                        $("#address_id").append(sel);
                                        direction = r.addresses;
                                        for (var i in direction) {
                                            if (direction[i].last_used == 1) {
                                                var row =
                                                    '<option value="' +
                                                    direction[i].id +
                                                    '" selected="selected">' +
                                                    direction[i].direction +
                                                    "</option>";
                                                $("#address_id").append(row);
                                            } else {
                                                var row =
                                                    '<option value="' +
                                                    direction[i].id +
                                                    '" >' +
                                                    direction[i].direction +
                                                    "</option>";
                                                $("#address_id").append(row);
                                            }
                                        }
                                        break;
                                }
                            }
                        },
                    });
                }
            }
        });
    });
}

function deleteProductOrder(order_id, order_product_id, state) {
    swal(Lang.get("messagesClient.orders_tag13"), {
        buttons: {
            cancel: "No",
            Ok: true,
        },
    }).then((val) => {
        if (val == "Ok") {
            var info = {
                order_product_id,
                state: !state,
            };
            $.ajax({
                url: "/orders/productAvailable",
                type: "POST",
                contentType: "application/json",
                headers: {
                    "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr(
                        "content"
                    ),
                    "Content-Type": "application/json",
                },
                data: JSON.stringify(info),
                success: function (r) {
                    swal(Lang.get("messagesClient.orders_tag14"), {
                        icon: "success",
                        buttons: {
                            Ok: true,
                        },
                    }).then((val) => {
                        if (val == "Ok") {
                            $(location).attr(
                                "href",
                                "/orders/edit/" + order_id
                            );
                        }
                    });
                },
                error: function (e) {
                    swal(
                        "Error",
                        Lang.get("messagesClient.product_tag3"),
                        "error"
                    );
                },
            });
        }
    });
}

function deleteProducts(order_id, order_product_id) {
    // console.log(order_id, order_product_id, quantity);
    swal(Lang.get("messagesClient.orders_tag21"), {
        buttons: {
            cancel: "No",
            Ok: true,
        },
    }).then((val) => {
        if (val == "Ok") {
            var info = {
                order_id,
                order_product_id
            };
            $.ajax({
                url: "/orders/deleteProduct",
                type: "POST",
                contentType: "application/json",
                headers: {
                    "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr(
                        "content"
                    ),
                    "Content-Type": "application/json",
                },
                data: JSON.stringify(info),
                success: function (r) {
                    console.log('respuesta: ',r);
                    swal(Lang.get("messagesClient.orders_tag22"), {
                        icon: "success",
                        buttons: {
                            Ok: true,
                        },
                    }).then((val) => {
                        if (val == "Ok") {
                            $(location).attr(
                                "href",
                                "/orders/edit/" + order_id
                            );
                        }
                    });
                },
                error: function (e) {
                    swal(
                        "Error",
                        Lang.get("messagesClient.product_tag3"),
                        "error"
                    );
                },
            });
        }
    });
}

function createOrder() {
    var type = $("#select_type_order option:selected").val();
    console.log(type);
    console.log(needToConfirmT);
    switch (type) {
        case "1":
            createSale();
            break;
        case "2":
            createAlliance();
            break;
        case "3":
            createTransfer();
            break;
        case "4":
            createDiligence();
            break;
        case "5":
            createECommerce();
            break;
    }
}

function createECommerce() {
    order_type_id = 5;

    $("#createOrder").validator("update");
    $("#createOrder")
        .validator("update")
        .on("submit", function (e) {
            calculateTotal();
            e.preventDefault();

            $("#btn-create-order").prop("disabled", true);
            valueMinDelivery = $("#btn-create-order").attr(
                "data-valueMinDelivery"
            );
            valueMinDelivery = parseInt(valueMinDelivery);
            var arrayProducts = localStorage.getItem("arrayProducts");
            if (arrayProducts && arrayProducts != "") {
                arrayProducts = JSON.parse(arrayProducts);
            } else {
                arrayProducts = [];
            }

            if (arrayProducts.length > 0) {
                total_price = $("#total_order").html();
                total_price = total_price.replaceAll(",", "");
                total_price = parseFloat(total_price);
                if (total_price < valueMinDelivery) {
                    swal(
                        "Error",
                        Lang.get("messagesClient.orders_tag12"),
                        "warning"
                    );
                    $("#btn-create-order").prop("disabled", false);
                } else {
                    //obtener registro de los descuentos
                    var dCampana = null;
                    var dReferred = null;
                    var dCoupone = null;

                    if ($("#tr-discountCampana").length > 0) {
                        dCampana = $("#tr-discountCampana").attr("data-id");
                    }
                    if ($("#tr-discountReferred").length > 0) {
                        dReferred = $("#tr-discountReferred").attr("data-id");
                    }
                    if ($("#tr-discountCoupone").length > 0) {
                        dCoupone = $("#tr-discountCoupone").attr("data-id");
                    }
                    var city_id = $(
                        "#createOrder select[name='city_id']"
                    ).val();
                    var ec_andres_id = $(
                        "#createOrder select[name='address_id']"
                    ).val();
                    if (ec_andres_id == "") {
                        swal(
                            "Error",
                            Lang.get("messagesClient.orders_tag16"),
                            "warning"
                        );
                        $("#btn-create-order").prop("disabled", false);
                        return;
                    }
                    if (ec_andres_id == 0) {
                        var address_id = parseInt(ec_andres_id);
                        var direction = $(
                            "#createOrder select[name='address_id']"
                        ).attr("ec-data-direction");
                        direction = direction.split(",", 1);
                        var district = $(
                            "#createOrder select[name='address_id']"
                        ).attr("ec-data-district");
                        var instru = $(
                            "#createOrder select[name='address_id']"
                        ).attr("ec-data-instru");
                        var lat = $(
                            "#createOrder select[name='address_id']"
                        ).attr("ec-data-lat");
                        var lng = $(
                            "#createOrder select[name='address_id']"
                        ).attr("ec-data-long");
                        var address_new = {
                            direction: direction[0],
                            district: district,
                            instru: instru,
                            lat: lat,
                            lng: lng,
                        };
                    } else {
                        var address_id = parseInt(ec_andres_id);
                        var address_new = {};
                    }

                    if (city_id == "") {
                        swal(
                            "Error",
                            Lang.get("messagesClient.orders_tag17"),
                            "warning"
                        );
                        $("#btn-create-order").prop("disabled", false);
                        return;
                    }

                    var payment = $(
                        "#createOrder select[name='payment_type_id']"
                    ).val();
                    if (payment == "") {
                        swal(
                            "Error",
                            Lang.get("messagesClient.orders_tag18"),
                            "warning"
                        );
                        $("#btn-create-order").prop("disabled", false);
                        return;
                    }

                    var sucursal_parameter = parseInt(
                        $("#sucursal_parameter").attr("value")
                    );
                    var sucursal = $(
                        "#createOrder select[name='sucursal']"
                    ).val();
                    if (sucursal_parameter) {
                        if (sucursal == "") {
                            swal(
                                "Error",
                                Lang.get("messagesClient.orders_tag20"),
                                "warning"
                            );
                            $("#btn-create-order").prop("disabled", false);
                            return;
                        }
                    }

                    var delivery_man_id = $(
                        "#createOrder select[name='delivery_man_id']"
                    ).val();

                    if (!delivery_man_id || delivery_man_id == "") {
                        delivery_man_id = null;
                    }

                    currentDiscount = $("#total_order_discount").text();
                    currentDiscount = currentDiscount.substring(
                        1,
                        currentDiscount.length
                    );
                    currentDiscount = parseInt(
                        currentDiscount.replace(",", "")
                    );

                    currentTotal = $("#total_order").text();
                    currentTotal = parseInt(currentTotal.replace(",", ""));
                    currentSubtotal = $("#subtotal").text();
                    currentSubtotal = parseInt(
                        currentSubtotal.replace(",", "")
                    );
                    if (currentDiscount) {
                        currentDiscount -= currentTotal;
                    }
                    var info = {
                        data: {
                            first_name: $(
                                " #createOrder input[name='user_id']"
                            ).val(),
                            last_name: $(
                                " #createOrder input[name='last_name']"
                            ).val(),
                            document: $(
                                "#createOrder input[name='document']"
                            ).val(),
                            phone: $(" #createOrder input[name='phone']").val(),
                            email: $(" #createOrder input[name='email']").val(),
                            order_reference: $(
                                " #createOrder input[name='reference']"
                            ).val(),
                            sucursal: $(
                                " #createOrder select[name='sucursal']"
                            ).val(),
                            is_change: $(
                                "#createOrder select[name='is_change']"
                            ).val(),
                            products: arrayProducts,
                            confirmOrder: {
                                observations: "",
                                effectivePayment: "",
                                cellphone: $(
                                    "#createOrder input[name='phone']"
                                ).val(),
                                wayPay: $(
                                    "#createOrder select[name='payment_type_id']"
                                ).val(),
                                address: address_id,
                                address_new: address_new,
                            },
                            dCampana: dCampana,
                            dReferred: dReferred,
                            dCoupone: dCoupone,
                            subtotal: currentSubtotal,
                            discount: currentDiscount,
                            priceDomicile: $("#cost-delivery").text(),
                            total: currentTotal,
                            productsNotFound: $(
                                " #createOrder textarea[name='productsNotFound']"
                            ).val(),
                            order_type_id: order_type_id,
                            client_id: $(
                                " #createOrder input[name='user_id']"
                            ).attr("data-id"),
                            city_id: city_id,
                            delivery_man_id,
                        },
                    };

                    var order_reference = $(
                        " #createOrder input[name='reference']"
                    ).val();
                    if (order_reference == "") {
                        swal(
                            "Error",
                            Lang.get("messagesClient.orders_tag19"),
                            "warning"
                        );
                        $("#btn-create-order").prop("disabled", false);
                        return;
                    }
                    var order_reference_confirm = $(
                        " #createOrder input[name='reference_confirmation']"
                    ).val();

                    if (order_reference != order_reference_confirm) {
                        swal(
                            "Error",
                            Lang.get("messagesClient.orders_tag15"),
                            "warning"
                        );
                        $("#btn-create-order").prop("disabled", false);
                        $(" #createOrder input[name='reference_confirmation']");
                        return;
                    } else {
                        swal(Lang.get("messagesClient.orders_tag4"), {
                            buttons: {
                                cancel: "Cancelar",
                                Ok: true,
                            },
                        }).then((val) => {
                            if (val == "Ok") {
                                $("#modalLoader").modal("show");
                                $("#modalLoader").css("display", "flex");

                                $.ajax({
                                    url: "/orders/create",
                                    type: "POST",
                                    contentType: "application/json",
                                    headers: {
                                        "X-CSRF-TOKEN": $(
                                            'meta[name="csrf-token"]'
                                        ).attr("content"),
                                        "Content-Type": "application/json",
                                    },
                                    data: JSON.stringify(info),
                                    success: function (r) {
                                        console.log(r);
                                        $("#modalLoader").modal("hide");
                                        $("#modalLoader").css(
                                            "display",
                                            "none"
                                        );
                                        if (r.r) {
                                            id = r.id;

                                            localStorage.setItem(
                                                "arrayProducts",
                                                ""
                                            );

                                            swal(
                                                Lang.get(
                                                    "messagesClient.orders.order_created"
                                                ) + r.code,
                                                {
                                                    icon: "success",
                                                    buttons: {
                                                        Ok: "OK",
                                                    },
                                                }
                                            ).then((val) => {
                                                window.onbeforeunload = null;
                                                $(location).attr(
                                                    "href",
                                                    "/orders"
                                                );
                                            });
                                        } else {
                                            $("#modalLoader").modal("hide");
                                            $("#modalLoader").css(
                                                "display",
                                                "none"
                                            );
                                            swal("Error", r.m, "error");
                                            $("#btn-create-order").prop(
                                                "disabled",
                                                false
                                            );
                                        }
                                    },
                                    error: function (error) {
                                        $("#modalLoader").modal("hide");
                                        $("#modalLoader").css(
                                            "display",
                                            "none"
                                        );
                                        swal(
                                            "Error",
                                            Lang.get(
                                                "messagesClient.orders_tag6"
                                            ),
                                            "error"
                                        );
                                        $("#btn-create-order").prop(
                                            "disabled",
                                            false
                                        );
                                    },
                                });
                            } else {
                                $("#btn-create-order").prop("disabled", false);
                            }
                        });
                    }
                }
            } else {
                swal(
                    "Error",
                    Lang.get("messagesClient.orders_tag11"),
                    "warning"
                );
                $("#btn-create-order").prop("disabled", false);
            }
        });
}

var idx = 1;

function addTransfer(sucursals) {
    var lastField = $("#box-transfer div:last");
    var intId =
        (lastField && lastField.length && lastField.data("idx") + 1) || 1;
    var fieldWrapper = $(
        '<div class=" fieldwrapper row" id="field' + intId + '" />'
    );
    fieldWrapper.data("idx", intId);
    var fsucursal = $(
        '<div class="col-xs-3 "><div class="form-group">  <label for="sucursal_id">Sucursal</label> <select class="form-control sucursals" id="st' +
            idx +
            '" name="sucursal_transfer" required> </select></div> </div>'
    );
    var fproduct = $(
        '<div class="col-xs-6 "><div class="form-group">  <label for="products_transfer">Productos</label> <textarea class="form-control products" id="pt' +
            idx +
            '" rows="5" name="products_transfer" placeholder="Enter ..." required></textarea> </div> </div>'
    );
    var removeButton = $(
        '<div class="col-xs-3 delete-product" ><button type="button"  class="remove btn btn-danger fa fa-trash " style="margin-left: 3px; margin-top:25px; height: 34px;" value="" />  </button> </div> '
    );

    removeButton.click(function () {
        $(this).parent().remove();
    });

    fieldWrapper.append(fsucursal);
    fieldWrapper.append(fproduct);
    fieldWrapper.append(removeButton);

    $("#box-transfer").append(fieldWrapper);
    console.log(sucursals);
    r = sucursals;
    var sel = '<option value="">--Seleccionar</option>';
    $("#st" + idx).append(sel);

    for (var i in r) {
        console.log(r[i].name);
        var row =
            '<option value="' +
            r[i].id +
            '">' +
            r[i].code +
            " - " +
            r[i].name +
            "</option>";
        $("#st" + idx).append(row);
    }
    idx++;
}

function addTransferOrder(id) {
    $("#editOrder").validator("update");
    $("#editOrder")
        .validator("update")
        .on("submit", function (e) {
            if (e.isDefaultPrevented()) {
            } else {
                e.preventDefault();

                var info = {
                    id: id,
                    sucursalsTransf: [],
                    productsTransf: [],
                };
                var sucursals = [];
                var j = 0;
                for (let index = 0; index < 10; index++) {
                    if ($("#st" + index).length) {
                        if ($("#st" + index).val() != "") {
                            sucursals[j] = $("#st" + index).val();
                            j++;
                        }
                    }
                }
                info.sucursalsTransf.push(sucursals);

                var products = [];
                var l = 0;
                for (let i = 0; i < 10; i++) {
                    if ($("#pt" + i).length) {
                        products[l] = $("#pt" + i).val();
                        l++;
                    }
                }
                info.productsTransf.push(products);

                if (info.sucursalsTransf[0].length > 0) {
                    if (sucursals.length == products.length) {
                        swal("¿Crear transferencia?", {
                            buttons: {
                                cancel: "No",
                                Ok: true,
                            },
                        }).then((val) => {
                            if (val == "Ok") {
                                $("#modalLoader").modal("show");
                                $("#modalLoader").css("display", "flex");

                                $.ajax({
                                    url: "/orders/add/transfer",
                                    type: "POST",
                                    contentType: "application/json",
                                    headers: {
                                        "X-CSRF-TOKEN": $(
                                            'meta[name="csrf-token"]'
                                        ).attr("content"),
                                        "Content-Type": "application/json",
                                    },
                                    data: JSON.stringify(info),
                                    success: function (r) {
                                        $("#modalLoader").modal("hide");
                                        $("#modalLoader").css(
                                            "display",
                                            "none"
                                        );
                                        console.log(r);
                                        if (r.r) {
                                            swal(
                                                "Transferencias creadas con éxito!",
                                                {
                                                    icon: "success",
                                                    buttons: {
                                                        Ok: true,
                                                    },
                                                }
                                            ).then((val) => {
                                                if (val == "Ok") {
                                                    console.log("creado");
                                                    localStorage.setItem(
                                                        "setPageTable",
                                                        true
                                                    );
                                                    $(location).attr(
                                                        "href",
                                                        "/orders"
                                                    );
                                                }
                                            });
                                        } else {
                                            swal(
                                                "Error",
                                                "¡Error al crear transferencias order",
                                                "error"
                                            );
                                        }
                                    },
                                });
                            }
                        });
                    } else {
                        swal(
                            "Advertencia",
                            "¡Debe seleccionar sucursal para cada transferencia!",
                            "warning"
                        );
                        // $("#btn-edit-order").prop("disabled", false);
                    }
                } else {
                    swal(
                        "Advertencia",
                        "¡Debe realizar al menos una transferencia!",
                        "warning"
                    );
                }
            }
        });
}

//metodo de al dar enter en el input cedula se traigan los datos del cliente
$(function () {
    $("#document").keypress(function (e) {
        console.log(cedula);
        if (e.which == 13) {
            cedula = $("#document").val();
            console.log(cedula);

            if (cedula.length > 0) {
                $.ajax({
                    url: "/clients/document/" + cedula,
                    type: "GET",
                    contentType: "application/json",
                    headers: {
                        "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr(
                            "content"
                        ),
                        "Content-Type": "application/json",
                    },
                    success: function (r) {
                        if (r.r) {
                            /// modificar
                            $("#user_id").val(r.client.first_name);
                            $("#last_name").val(r.client.last_name);
                            $("#user_id").attr("data-id", r.client.id);
                            $("#document").val(r.client.document);
                            $("#phone").val(r.client.phone);

                            // $("#direction").val(r.direction);
                            // $("#direction").attr("data-id", r.id);
                            // $("#direction").attr("data-lat", r.lat);
                            // $("#direction").attr("data-long", r.long);
                            // $("#district").val(r.district);
                            // $("#indications").val(r.indications);
                        }
                    },
                });
            }
        }
    });
});

function setPageTable() {
    localStorage.setItem("setPageTable", true);
    $(location).attr("href", "/orders");
}

function printInvoice(id) {
    $.ajax({
        url: "/orders/info/" + id,
        type: "GET",
        async: false,
        contentType: "application/json",
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
            "Content-Type": "application/json",
        },
        success: function (r) {
            order = r.order;
            transfer = r.transfers;
            name = r.nameCompany;
        },
        error: function (r) {
            // alert('paila');
            return;
        },
    });

    if (order.express_products == null) {
        order.express_products = "No hay productos";
    }

    if (order.code.length > 20) {
        order.code = order.code.match(/.{1,20}/g).join("<br/>");
    }
    if (order.express_products.length > 20) {
        order.express_products = order.express_products
            .match(/.{1,20}/g)
            .join("<br/>");
    }

    var mywindow = window.open("", "my div", "height=400,width=600");
    mywindow.document.write("<html><head><title></title>");
    mywindow.document.write("</head><body >");
    mywindow.document.write("<h1>" + name + "</h1>");
    if (order.sucursal_id != null) {
        mywindow.document.write("<h3>Sede: " + order.sucursal.name + "</h3>");
    }

    mywindow.document.write("</br>--------------------");
    mywindow.document.write("</br>DATOS DEL PEDIDO</br> #" + order.code);
    mywindow.document.write("</br>Fecha de creacion: " + order.creation_date);
    mywindow.document.write("</br>--------------------");
    mywindow.document.write(
        "</br></br>PRODUCTOS</br>" + order.express_products
    );
    mywindow.document.write("</br>--------------------");

    if (transfer.length > 0) {
        mywindow.document.write("</br></br>TRANSFERENCIAS</br>");

        element = "";
        for (let index = 0; index < transfer.length; index++) {
            mywindow.document.write(
                "</br> Sucursal:" + transfer[index].sucursal
            );
            if (transfer[index].description.length > 20) {
                transfer[index].description = transfer[index].description
                    .match(/.{1,20}/g)
                    .join("<br/>");
            }
            mywindow.document.write(
                "</br> Productos:" + transfer[index].description + "</br>"
            );
        }

        mywindow.document.write("</br>--------------------");
    }
    mywindow.document.write("</br>Descuento: " + order.discount);
    mywindow.document.write("</br>Total: " + order.total_price);
    mywindow.document.write("</br></br>DATOS DEL CLIENTE");
    mywindow.document.write("</br>--------------------");
    if (order.client.document != null) {
        mywindow.document.write(
            "</br></br>Documento: " + order.client.document
        );
    }
    mywindow.document.write(
        "</br></br>Nombre: " +
            order.client.first_name +
            " " +
            order.client.last_name
    );
    mywindow.document.write("</br></br>Dirección: " + order.address.direction);
    mywindow.document.write("</br></br>Teléfono: " + order.client.phone);
    mywindow.document.write("</body></html>");

    mywindow.print();
    mywindow.close();
}

function direccionorderexpres() {
    console.log("esta dir order expres");
    //obtener valores modal
    var lat = $("#pac-input").attr("data-lat");
    var long = $("#pac-input").attr("data-long");
    var instru = $("#indications-modal").val();
    var district = $("#district-modal").val();
    var valor = $("#pac-input").val();

    //set valores vista
    $("#direccion").val(valor);
    $("#direccion").attr("data-id", "");
    $("#direccion").attr("data-lat", lat);
    $("#direccion").attr("data-long", long);
    $("#indications").val(instru);
    $("#district").val(district);
    $("#modal-registro-direccion").css("display", "none");
    $(".modal-backdrop").attr("class", "modal fade");
    document.documentElement.style.overflow = "scroll";

    if (lat && long) {
        calculoCobertura(lat, long);
    } else {
        swal("Advertencia", "¡Dirección incorrecta!", "warning");
    }
}

/*
$("#sucursal_id").change(function () {
  valor = $(this).val();
  var info = {
    "id": valor
  }

  $.ajax({
    url: "/Mensajeros/sucursals",
    type: "POST",
    contentType: 'application/json',
    headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
      'Content-Type': 'application/json'
    },
    data: JSON.stringify(info),
    success: function (r) {
      console.log(r);
      if (r[0]["respuesta"]) {
        var mensajeros = r[0]["mensajeros"];

        $('#delivery_man_id').empty();
        var sel = '<option value="ninguna">--Seleccionar</option>';
        $('#delivery_man_id').append(sel);
        for (var i in mensajeros) {
          var row = '<option value="' + mensajeros[i].id + '">' + mensajeros[i].nombre + " " + mensajeros[i].apellido + '</option>';
          $('#delivery_man_id').append(row);
          console.log(mensajeros[i].nombre)
        }
      } else {
        $('#delivery_man_id').empty();
        console.log("no hay nada");
      }
    }
  });
});
*/
function calculoCobertura(lat, long) {
    var myLatlng = new google.maps.LatLng(lat, long);

    $.ajax({
        url: "/coverages/getAll",
        type: "GET",
        contentType: "application/json",
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
            "Content-Type": "application/json",
        },
        success: function (r) {
            if (r.r) {
                // r[0]["coberturas"][0].sucursal;

                for (let index = 0; index < r.c.length; index++) {
                    var polygon = new google.maps.Polygon({
                        paths: r.c[index].coords,
                    });
                    if (
                        google.maps.geometry.poly.containsLocation(
                            myLatlng,
                            polygon
                        )
                    ) {
                        idUser = $("#btn-create-order").attr("data-idSucursal");
                        // idUser=2;
                        if (idUser != r.c[index].id) {
                            swal(
                                "Advertencia",
                                "¡La sucursal mas cercana a la dirección es: " +
                                    r.c[index].name +
                                    "!",
                                "warning"
                            );
                            console.log(r.c[index].name);
                            break;
                        }
                        break;
                    }
                }
            }
        },
    });
}

$("#select_type_order").change(function () {
    valor = $("#select_type_order option:selected").val();
    console.log("type_order: ", valor);
    var info = {
        id: valor,
    };

    $.ajax({
        url: "/orders/typeOrder",
        type: "POST",
        contentType: "application/json",
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
            "Content-Type": "application/json",
        },
        data: JSON.stringify(info),
        success: function (data) {
            // console.log('data select_type_order: ', data);
            $("#content-form").empty();
            $("#content-form").append(data);
            if (valor == 5) {
                orderReferenceValidate();
                viewProductsStorage();
                // $('#btn-open-modal-direction-ec').addClass('disabled');
            }
        },
        error: function (e) {},
    });
});

function orderReferenceValidate() {
    reference_parameter = parseInt($("#reference").attr("info"));
    if (!reference_parameter) {
        $("#ref_id").remove();
        $("#ref_id_conf").remove();
    }
}

function viewProductsStorage() {
    var arrayProducts = localStorage.getItem("arrayProducts");
    if (arrayProducts) {
        arrayProducts = JSON.parse(arrayProducts);
        if (arrayProducts.length > 0) {
            for (let i = 0; i < arrayProducts.length; i++) {
                //eeeee
                var lastField = $("#list-products div:last");
                var intId =
                    (lastField &&
                        lastField.length &&
                        lastField.data("idx") + 1) ||
                    1;

                var fieldWrapper = $(
                    '<div class=" fieldwrapper"  style="display:flex; width:100%; border-top: 2px solid;border-color: #f0f1f0de; padding: 4px;align-items: center; margin-top: 10px;background: #fdfdfd; " id="field' +
                        intId +
                        '" />'
                );
                fieldWrapper.data("idx", intId);
                var dateCurrent = new Date();
                var priceAfterDiscount = 0;
                var priceAfterFlash = 0;
                console.log("fecha actual: " + dateCurrent);
                if (arrayProducts[i].percentage_discount) {
                    // se mira si hay un porcentaje de descuento y se hacen las validaciones del tiempo para ver si aplica
                    var startDiscount = arrayProducts[i].start_discount;
                    var stopDiscount =
                        arrayProducts[i].limit_discount +
                        " " +
                        arrayProducts[i].limit_hour_discount;
                    console.log(
                        "fecha inicio: " +
                            startDiscount +
                            "    fecha fin: " +
                            stopDiscount
                    );
                    if (
                        new Date(startDiscount).getTime() < dateCurrent &&
                        new Date(stopDiscount).getTime() > dateCurrent
                    ) {
                        var priceDiscount =
                            arrayProducts[i].price -
                            (arrayProducts[i].price *
                                arrayProducts[i].percentage_discount) /
                                100; // se calcula el precio
                        var fName = $(
                            '  <div style="width: 33.33333333%; "> <p>' +
                                arrayProducts[i].name +
                                '</p></div> <div style="width: 16.66666667%;"> <p class="p-list-Pedidos plu-list-orders">' +
                                arrayProducts[i].plu +
                                '</p></div> <div style="width: 16.66666667%;"> <div class="form-group"> <input id="p-' +
                                arrayProducts[i].id +
                                '" data-id="' +
                                arrayProducts[i].id +
                                '" onchange="changeQuantity(this)" name="' +
                                arrayProducts[i].id +
                                '" class="cantidadProductos form-control idProducts" maxlength="3"  min="1" type="number" style="margin-top: 10px;" value="' +
                                arrayProducts[i].quantity +
                                '" required></div> </div> <div id="row-' +
                                arrayProducts[i].id +
                                '" style="width: 16.66666667%; display:flex;"> <p style="margin-left: 25px;" name="' +
                                arrayProducts[i].id +
                                '" class="precio_list p-list-Pedidos"><del>$' +
                                arrayProducts[i].price +
                                ' </del> </p> <p class="text-red">$' +
                                priceDiscount +
                                "</p></div>"
                        );

                        priceAfterDiscount = priceDiscount;
                    } else {
                        var fName = $(
                            '  <div style="width: 33.33333333%; "> <p>' +
                                arrayProducts[i].name +
                                '</p></div> <div style="width: 16.66666667%;"> <p class="p-list-Pedidos plu-list-orders">' +
                                arrayProducts[i].plu +
                                '</p></div> <div style="width: 16.66666667%;"> <div class="form-group"> <input id="p-' +
                                arrayProducts[i].id +
                                '" data-id="' +
                                arrayProducts[i].id +
                                '" onchange="changeQuantity(this)" name="' +
                                arrayProducts[i].id +
                                '" class="cantidadProductos form-control idProducts" maxlength="3"  min="1" type="number" style="margin-top: 10px;" value="' +
                                arrayProducts[i].quantity +
                                '" required></div> </div> <div id="row-' +
                                arrayProducts[i].id +
                                '" style="width: 16.66666667%;"> <p style="margin-left: 25px;" name="' +
                                arrayProducts[i].id +
                                '" class="precio_list p-list-Pedidos">$' +
                                arrayProducts[i].price +
                                "</p></div>"
                        );
                    }
                } else if (arrayProducts[i].flash_price) {
                    // se mira si hay un precio relampago y se hacen las validaciones del tiempo para ver si aplica
                    var startFlash = arrayProducts[i].start_flash_discount;
                    var stopFlash =
                        arrayProducts[i].limit_flash_discount +
                        " " +
                        arrayProducts[i].limit_hour_flash_discount;
                    console.log(
                        "fecha inicio flash: " +
                            startFlash +
                            "    fecha fin flash: " +
                            stopFlash
                    );
                    if (
                        new Date(startFlash).getTime() < dateCurrent &&
                        new Date(stopFlash).getTime() > dateCurrent
                    ) {
                        var priceFlash = arrayProducts[i].flash_price; // se calcula el precio
                        var fName = $(
                            '  <div style="width: 33.33333333%; "> <p>' +
                                arrayProducts[i].name +
                                '</p></div> <div style="width: 16.66666667%;"> <p class="p-list-Pedidos plu-list-orders">' +
                                arrayProducts[i].plu +
                                '</p></div> <div style="width: 16.66666667%;"> <div class="form-group"> <input id="p-' +
                                arrayProducts[i].id +
                                '" data-id="' +
                                arrayProducts[i].id +
                                '" onchange="changeQuantity(this)" name="' +
                                arrayProducts[i].id +
                                '" class="cantidadProductos form-control idProducts" maxlength="3"  min="1" type="number" style="margin-top: 10px;" value="' +
                                arrayProducts[i].quantity +
                                '" required></div> </div> <div id="row-' +
                                arrayProducts[i].id +
                                '" style="width: 16.66666667%; display:flex;"> <p style="margin-left: 25px;" name="' +
                                arrayProducts[i].id +
                                '" class="precio_list p-list-Pedidos"><del>$' +
                                arrayProducts[i].price +
                                ' </del> </p> <p class="text-red">$' +
                                priceFlash +
                                "</p></div>"
                        );
                        priceAfterFlash = priceFlash;
                    } else {
                        var fName = $(
                            '  <div style="width: 33.33333333%; "> <p>' +
                                arrayProducts[i].name +
                                '</p></div> <div style="width: 16.66666667%;"> <p class="p-list-Pedidos plu-list-orders">' +
                                arrayProducts[i].plu +
                                '</p></div> <div style="width: 16.66666667%;"> <div class="form-group"> <input id="p-' +
                                arrayProducts[i].id +
                                '" data-id="' +
                                arrayProducts[i].id +
                                '" onchange="changeQuantity(this)" name="' +
                                arrayProducts[i].id +
                                '" class="cantidadProductos form-control idProducts" maxlength="3"  min="1" type="number" style="margin-top: 10px;" value="' +
                                arrayProducts[i].quantity +
                                '" required></div> </div> <div id="row-' +
                                arrayProducts[i].id +
                                '" style="width: 16.66666667%;"> <p style="margin-left: 25px;" name="' +
                                arrayProducts[i].id +
                                '" class="precio_list p-list-Pedidos">$' +
                                arrayProducts[i].price +
                                "</p></div>"
                        );
                    }
                } else {
                    var fName = $(
                        '  <div style="width: 33.33333333%; "> <p>' +
                            arrayProducts[i].name +
                            '</p></div> <div style="width: 16.66666667%;"> <p class="p-list-Pedidos plu-list-orders">' +
                            arrayProducts[i].plu +
                            '</p></div> <div style="width: 16.66666667%;"> <div class="form-group"> <input id="p-' +
                            arrayProducts[i].id +
                            '" data-id="' +
                            arrayProducts[i].id +
                            '" onchange="changeQuantity(this)" name="' +
                            arrayProducts[i].id +
                            '" class="cantidadProductos form-control idProducts" maxlength="3"  min="1" type="number" style="margin-top: 10px;" value="' +
                            arrayProducts[i].quantity +
                            '" required></div> </div> <div id="row-' +
                            arrayProducts[i].id +
                            '" style="width: 16.66666667%;"> <p style="margin-left: 25px;" name="' +
                            arrayProducts[i].id +
                            '" class="precio_list p-list-Pedidos">$' +
                            arrayProducts[i].price +
                            "</p></div>"
                    );
                }

                var removeButton = $(
                    '<div data-id="' +
                        arrayProducts[i].id +
                        '" class="col-xs-2 delete-product" ><button data-id="' +
                        arrayProducts[i].id +
                        '" type="button"  class="remove btn btn-danger fa fa-trash " style="margin-left: 5px; height: 34px; " value="" />  </button> </div> '
                );

                calculateTotal();
                removeButton.click(function () {
                    // elimina el elento de la vista y del array
                    var arrayProducts = localStorage.getItem("arrayProducts");
                    arrayProducts = JSON.parse(arrayProducts);

                    var idObj = $(this).attr("data-id");

                    for (let i = 0; i < arrayProducts.length; i++) {
                        if (arrayProducts[i].id == idObj) {
                            arrayProducts.splice(i, 1);
                        }
                    }
                    arrayProducts = JSON.stringify(arrayProducts);
                    localStorage.setItem("arrayProducts", arrayProducts);

                    calculateTotal();
                    $(this).parent().remove();
                });

                fieldWrapper.append(fName);
                fieldWrapper.append(removeButton);
                $("#list-products").append(fieldWrapper);
            }
        }
    }
}

$("#order_state_id").change(function () {
    valor = $(this).val();
    idnew = $(this).val();
    idpast = $("#order_state_id").attr("data-id");
    idpast = parseInt(idpast);
    idnew = parseInt(idnew);

    console.log("nuevo: " + idnew + "  , pasado:" + idpast);
    switch (idpast) {
        case 1:
            if (idnew == 3 || idnew == 4 || idnew == 5 || idnew == 8) {
                $("#delivery_man_id").prop("disabled", false);
                $("#sucursal_id").prop("disabled", false);
                $("#document").prop("disabled", false);
                $("#user_id").prop("disabled", false);
                $("#last_name").prop("disabled", false);
                $("#direction").prop("disabled", false);
                $("#district").prop("disabled", false);
                $("#indications").prop("disabled", false);
                $("#phone").prop("disabled", false);
                $("#payment_type_id").prop("disabled", false);
                $("#discount").prop("disabled", false);
                $("#total_price").prop("disabled", false);
                $("#express_products").prop("disabled", false);
                $("#add-transfer").prop("disabled", false);
                $("#linea_negocio").prop("disabled", false);
                $("#sales_channel_id").prop("disabled", false);
                swal(
                    "",
                    "Primero se debe aceptar el pedido para asignar este estado",
                    "warning"
                );
                $("#order_state_id").val(idpast);
                return;
            }

            break;

        case 2:
            if (idnew == 4 || idnew == 5 || idnew == 8) {
                swal(
                    "",
                    "Primero se debe recibir el pedido para asignar este estado",
                    "warning"
                );
                $("#order_state_id").val(idpast);
                $("#delivery_man_id").prop("disabled", false);
                $("#sucursal_id").prop("disabled", true);
                $("#document").prop("disabled", true);
                $("#user_id").prop("disabled", true);
                $("#last_name").prop("disabled", true);
                $("#direction").prop("disabled", false);
                $("#district").prop("disabled", false);
                $("#indications").prop("disabled", false);
                $("#phone").prop("disabled", false);
                $("#payment_type_id").prop("disabled", false);
                $("#discount").prop("disabled", false);
                $("#total_price").prop("disabled", false);
                $("#express_products").prop("disabled", false);
                $("#add-transfer").css("display", "block");
                $("#box-transfer").css("display", "block");
                $("#linea_negocio").prop("disabled", false);
                $("#sales_channel_id").prop("disabled", false);
                return;
            }
            break;

        default:
            break;
    }

    if (valor == 1) {
        $("#delivery_man_id").prop("disabled", false);
        $("#sucursal_id").prop("disabled", false);
        $("#document").prop("disabled", false);
        $("#user_id").prop("disabled", false);
        $("#last_name").prop("disabled", false);
        $("#direction").prop("disabled", false);
        $("#district").prop("disabled", false);
        $("#indications").prop("disabled", false);
        $("#phone").prop("disabled", false);
        $("#payment_type_id").prop("disabled", false);
        $("#discount").prop("disabled", false);
        $("#total_price").prop("disabled", false);
        $("#express_products").prop("disabled", false);
        $("#add-transfer").prop("disabled", false);
        $("#line_businesses_id").prop("disabled", false);
        $("#sales_channel_id").prop("disabled", false);
    }
    if (valor == 2) {
        $("#delivery_man_id").prop("disabled", false);
        $("#sucursal_id").prop("disabled", true);
        $("#document").prop("disabled", true);
        $("#user_id").prop("disabled", true);
        $("#last_name").prop("disabled", true);
        $("#direction").prop("disabled", false);
        $("#district").prop("disabled", false);
        $("#indications").prop("disabled", false);
        $("#phone").prop("disabled", false);
        $("#payment_type_id").prop("disabled", false);
        $("#discount").prop("disabled", false);
        $("#total_price").prop("disabled", false);
        $("#express_products").prop("disabled", false);
        $("#line_businesses_id").prop("disabled", false);
        $("#sales_channel_id").prop("disabled", false);
        $("#add-transfer").css("display", "block");
        $("#box-transfer").css("display", "block");
    }
    if (valor == 3) {
        $("#delivery_man_id").prop("disabled", false);
        $("#sucursal_id").prop("disabled", true);
        $("#document").prop("disabled", true);
        $("#user_id").prop("disabled", true);
        $("#last_name").prop("disabled", true);
        $("#direction").prop("disabled", false);
        $("#district").prop("disabled", false);
        $("#indications").prop("disabled", false);
        $("#phone").prop("disabled", false);
        $("#payment_type_id").prop("disabled", false);
        $("#discount").prop("disabled", false);
        $("#total_price").prop("disabled", false);
        $("#express_products").prop("disabled", true);
        $("#add-transfer").css("display", "none");
        $("#box-transfer").css("display", "none");
        $("#line_businesses_id").prop("disabled", false);
        $("#sales_channel_id").prop("disabled", false);
    }
    if (valor == 4 || valor == 5 || valor == 6 || valor == 8) {
        $("#delivery_man_id").prop("disabled", true);
        $("#sucursal_id").prop("disabled", true);
        $("#document").prop("disabled", true);
        $("#user_id").prop("disabled", true);
        $("#last_name").prop("disabled", true);
        $("#direction").prop("disabled", true);
        $("#district").prop("disabled", true);
        $("#indications").prop("disabled", true);
        $("#phone").prop("disabled", true);
        $("#payment_type_id").prop("disabled", true);
        $("#discount").prop("disabled", true);
        $("#total_price").prop("disabled", true);
        $("#express_products").prop("disabled", true);
        $("#line_businesses_id").prop("disabled", true);
        $("#sales_channel_id").prop("disabled", true);
        $("#add-transfer").css("display", "none");
        $("#box-transfer").css("display", "none");
    }
});

var dataStorage = [];

$(document).ready(function () {
    // MODAL VER EVIDENCIA
    $(".view_photo").click(function () {
        var img = $(this).attr("data-img");
        console.log(img);
        // img2 = "{{ url('') }}" +img;
        // console.log(img2);

        $("#imagEvidence").attr("src", img);
        $("#modal-info-evidence").modal();
    });

    /* 1. Visualizing things on Hover - See next part for action on click */
    $("#stars li")
        .on("mouseover", function () {
            var onStar = parseInt($(this).data("value"), 10); // The star currently mouse on

            // Now highlight all the stars that's not after the current hovered star
            $(this)
                .parent()
                .children("li.star")
                .each(function (e) {
                    if (e < onStar) {
                        $(this).addClass("hover");
                    } else {
                        $(this).removeClass("hover");
                    }
                });
        })
        .on("mouseout", function () {
            $(this)
                .parent()
                .children("li.star")
                .each(function (e) {
                    $(this).removeClass("hover");
                });
        });

    /* 2. Action to perform on click */
    $("#stars li").on("click", function () {
        var onStar = parseInt($(this).data("value"), 10); // The star currently selected
        var stars = $(this).parent().children("li.star");
        console.log($(this).parent());

        for (i = 0; i < stars.length; i++) {
            $(stars[i]).removeClass("selected");
        }

        for (i = 0; i < onStar; i++) {
            $(stars[i]).addClass("selected");
        }

        // valor de calificacion
        var ratingValue = parseInt(
            $("#stars li.selected").last().data("value"),
            10
        );
        // segun el valor se cambia el texto
        switch (ratingValue) {
            case 1:
                $("#labelqualification").text("Malo");
                break;
            case 2:
                $("#labelqualification").text("Regular");
                break;
            case 3:
                $("#labelqualification").text("Bueno");
                break;
            case 4:
                $("#labelqualification").text("Muy Bueno");
                break;
            case 5:
                $("#labelqualification").text("Excelente!");
                break;

            default:
                $("#labelqualification").text(" ");

                break;
        }
        console.log(ratingValue);
    });
});

// MODAL CALIFICAR order
function doQualification(id) {
    console.log("calificacion");
    var stars = $("#stars li").parent().children("li.star");

    for (i = 0; i < stars.length; i++) {
        $(stars[i]).removeClass("selected");
        $(stars[i]).removeClass("disabledStar");
    }
    $("#labelQualification").text(" ");
    $("#btnQualification").attr("data-id", id);
    $("#observations_admin").val("");
    $("#btnQualification").prop("disabled", false);
    $("#observations_admin").prop("disabled", false);
    $("#stars").prop("disabled", true);
    $("#modal-qualification").modal("show");
}

function qualificationOrder() {
    var qualification = parseInt(
        $("#stars li.selected").last().data("value"),
        10
    );

    if (qualification) {
        var id = $("#btnQualification").attr("data-id");
        var observation = $("#observations_admin").val();

        var info = {
            id: id,
            observation: observation,
            qualification: qualification,
        };

        $.ajax({
            url: "/orders/qualification",
            type: "POST",
            contentType: "application/json",
            headers: {
                "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
                "Content-Type": "application/json",
            },
            data: JSON.stringify(info),
            success: function (r) {
                if (r.r) {
                    swal("Calificacíon realizada con éxito", {
                        icon: "success",
                        buttons: {
                            Ok: true,
                        },
                    }).then((val) => {
                        if (val == "Ok") {
                            $("#modal-qualification").modal("hide");
                            window.location.href = "/orders";
                        }
                    });
                }
            },
            error: function (e) {
                swal("Error al calificar pedido", "", "error");
            },
        });
    } else {
        swal("Debe indicar un valor para la calificacíon", "", "warning");
        return;
    }
}

function viewQualification(id) {
    $.ajax({
        url: "/orders/qualification/view/" + id,
        type: "GET",
        contentType: "application/json",
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
            "Content-Type": "application/json",
        },
        success: function (res) {
            console.log(res);
            pos = res.qualification_admin;
            var stars = $("#stars li").parent().children("li.star");

            for (i = 0; i < stars.length; i++) {
                $(stars[i]).removeClass("selected");
            }

            for (i = 0; i < pos; i++) {
                $(stars[i]).addClass("selected");
            }

            for (i = 1; i < 6; i++) {
                $("#li" + i).addClass("disabledStar");
            }
            $("#observations_admin").val(res.observations_admin);
            $("#btnQualification").prop("disabled", true);
            $("#observations_admin").prop("disabled", true);
            $("#stars").prop("disabled", true);

            switch (pos) {
                case 1:
                    $("#labelQualification").text("Malo");
                    break;
                case 2:
                    $("#labelQualification").text("Regular");
                    break;
                case 3:
                    $("#labelQualification").text("Bueno");
                    break;
                case 4:
                    $("#labelQualification").text("Muy Bueno");
                    break;
                case 5:
                    $("#labelQualification").text("Excelente!");
                    break;

                default:
                    $("#labelQualification").text(" ");

                    break;
            }

            $("#modal-qualification").modal("show");
        },
        error: function (err) {
            swal("Error", err.responseJSON.message, "error");
        },
    });
}

function freshDeliveryMan() {
    $("#select-delivery_man option").remove();
    var sel = '<option value="">--Seleccionar</option>';
    $("#select-delivery_man").append(sel);
    $("#fresh-deliveryMan").css("display", "block");
    $("#select-delivery_man").css("color", "#ccc");

    $.ajax({
        url: "/deliveryMan/getAll",
        type: "GET",
        contentType: "application/json",
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
            "Content-Type": "application/json",
        },
        success: function (r) {
            $("#select-delivery_man").css("color", "#555");
            $("#fresh-deliveryMan").css("display", "none");
            if (r.r) {
                var deliveryMan = r.m;
                if (deliveryMan.length > 0) {
                    // $('#select-delivery_man').empty();
                    for (var i in deliveryMan) {
                        var row =
                            '<option value="' +
                            deliveryMan[i].id +
                            '">' +
                            deliveryMan[i].first_name +
                            " " +
                            deliveryMan[i].last_name +
                            "</option>";
                        $("#select-delivery_man").append(row);
                    }
                }
            }
        },
        error: function (e) {
            $("#select-delivery_man").css("color", "#555");
            $("#fresh-deliveryMan").css("display", "none");
            console.log(e);
        },
    });
}

$("#modal-registro-direccion").on("showns.bs.modal", function () {
    initAutocomplete();
});

function createSale() {
    order_type_id = 1;
    if ($("#address_id_sales").val().length == 0) {
        $("#address_id_sales").css("border-color", "#dc0000");
    } else {
        $("#address_id_sales").css("border-color", "#d2d6de");
    }

    $("#createOrder").validator("update");
    $("#createOrder")
        .validator("update")
        .on("submit", function (e) {
            if (e.isDefaultPrevented()) {
            } else {
                e.preventDefault();
                $("#btn-create-order").prop("disabled", true);
                var payment_type_id = $(
                    "#createOrder select[name='payment_type_id']"
                ).val();
                var sucursal_id = $(
                    "#createOrder select[name='sucursal_id']"
                ).val();
                var city_id = $("#createOrder select[name='city_id']").val();

                if (sucursal_id == "") {
                    swal(
                        "Advertencia",
                        Lang.get("messagesClient.orders_tag1"),
                        "warning"
                    );
                    $("#btn-create-order").prop("disabled", false);
                } else if (payment_type_id == "") {
                    swal(
                        "Advertencia",
                        Lang.get("messagesClient.orders_tag2"),
                        "warning"
                    );
                    $("#btn-create-order").prop("disabled", false);
                } else if (city_id == "") {
                    swal(
                        "Advertencia",
                        Lang.get("messagesClient.orders_tag10"),
                        "warning"
                    );
                    $("#btn-create-order").prop("disabled", false);
                } else {
                    var info = {
                        data: {
                            client_id: $(
                                " #createOrder input[name='user_id']"
                            ).attr("data-id"),
                            first_name: $(
                                " #createOrder input[name='user_id']"
                            ).val(),
                            last_name: $(
                                " #createOrder input[name='last_name']"
                            ).val(),
                            document: $(
                                "#createOrder input[name='document']"
                            ).val(),
                            direction:
                                document.getElementById("address_id_sales")
                                    .selectedOptions[0].text,
                            direction_id: $("#address_id_sales").val(),
                            lat: $("#address_id_sales option:selected").attr(
                                "data-lat"
                            ),
                            long: $("#address_id_sales option:selected").attr(
                                "data-long"
                            ),
                            delivery_man_id: $(
                                " #createOrder select[name='delivery_man_id']"
                            ).val(),
                            phone: $(" #createOrder input[name='phone']").val(),
                            indications: $(
                                "#address_id_sales option:selected"
                            ).attr("indications"),
                            code: $(" #createOrder input[name='code']").val(),
                            payment_type_id: $(
                                " #createOrder select[name='payment_type_id']"
                            ).val(),
                            line_businesses_id: $(
                                "#createOrder select[name='line_businesses_id']"
                            ).val(),
                            sales_channel_id: $(
                                " #createOrder select[name='sales_channel_id']"
                            ).val(),
                            district: $(
                                "#address_id_sales option:selected"
                            ).attr("district"),
                            sucursal_id: $(
                                "#createOrder select[name='sucursal_id']"
                            ).val(),
                            express_products: $(
                                "#createOrder textarea[name='express_products']"
                            ).val(),
                            total_price: $(
                                "#createOrder input[name='total_price']"
                            ).val(),
                            discount: $(
                                "#createOrder input[name='discount']"
                            ).val(),
                            cost_delivery:
                                $("#btn-create-order").attr("data-delivery"),
                            minimum_order_price: $("#btn-create-order").attr(
                                "data-valueMinDelivery"
                            ),
                            order_type_id: order_type_id,
                            city_id: $(
                                "#createOrder select[name='city_id']"
                            ).val(),
                        },
                        sucursalsTransf: [],
                        productsTransf: [],
                    };

                    var sucursals = [];
                    var j = 0;
                    for (let index = 0; index < 10; index++) {
                        if ($("#st" + index).length) {
                            if ($("#st" + index).val() != "") {
                                sucursals[j] = $("#st" + index).val();
                                j++;
                            }
                        }
                    }
                    info.sucursalsTransf.push(sucursals);

                    var products = [];
                    var l = 0;
                    for (let i = 0; i < 10; i++) {
                        if ($("#pt" + i).length) {
                            products[l] = $("#pt" + i).val();
                            l++;
                        }
                    }
                    info.productsTransf.push(products);

                    if (!sucursals.length == products.length) {
                        swal(
                            "Advertencia",
                            Lang.get("messagesClient.orders_tag3"),
                            "warning"
                        );
                        $("#btn-create-order").prop("disabled", false);
                        return;
                    }

                    swal(Lang.get("messagesClient.orders_tag4"), {
                        buttons: {
                            cancel: "Cancelar",
                            Ok: true,
                        },
                    }).then((val) => {
                        if (val == "Ok") {
                            $("#modalLoader").modal("show");
                            $("#modalLoader").css("display", "flex");

                            $.ajax({
                                url: "/orders/create",
                                type: "POST",
                                contentType: "application/json",
                                headers: {
                                    "X-CSRF-TOKEN": $(
                                        'meta[name="csrf-token"]'
                                    ).attr("content"),
                                    "Content-Type": "application/json",
                                },
                                data: JSON.stringify(info),
                                success: function (r) {
                                    console.log(r);
                                    $("#modalLoader").modal("hide");
                                    $("#modalLoader").css("display", "none");
                                    if (r.r) {
                                        id = r.id;

                                        swal(
                                            Lang.get(
                                                "messagesClient.orders_tag5"
                                            ),
                                            {
                                                icon: "success",
                                                buttons: {
                                                    cancel: "No",
                                                    Ok: "Imprimir",
                                                },
                                            }
                                        ).then((val) => {
                                            if (val == "Ok") {
                                                window.onbeforeunload = null;

                                                printInvoice(id);
                                                $(location).attr(
                                                    "href",
                                                    "/orders"
                                                );
                                            } else {
                                                window.onbeforeunload = null;
                                                $(location).attr(
                                                    "href",
                                                    "/orders"
                                                );
                                            }
                                        });
                                    } else {
                                        $("#modalLoader").modal("hide");
                                        $("#modalLoader").css(
                                            "display",
                                            "none"
                                        );
                                        swal("Error", r.m, "error");
                                        $("#btn-create-order").prop(
                                            "disabled",
                                            false
                                        );
                                    }
                                },
                                error: function (error) {
                                    $("#modalLoader").modal("hide");
                                    $("#modalLoader").css("display", "none");
                                    swal(
                                        "Error",
                                        Lang.get("messagesClient.orders_tag6"),
                                        "error"
                                    );
                                    $("#btn-create-order").prop(
                                        "disabled",
                                        false
                                    );
                                },
                            });
                        } else {
                            $("#btn-create-order").prop("disabled", false);
                        }
                    });
                }
            }
        });
}

function createAlliance() {
    needToConfirmT = false;
    order_type_id = 2;

    $("#createOrder").validator("update");
    $("#createOrder")
        .validator("update")
        .on("submit", function (e) {
            if (e.isDefaultPrevented()) {
            } else {
                e.preventDefault();
                $("#btn-create-order").prop("disabled", true);

                var sucursal = $(
                    "#createOrder select[name='sucursal_id']"
                ).val();

                if (sucursal == "") {
                    swal(
                        "Advertencia",
                        Lang.get("messagesClient.orders_tag1"),
                        "warning"
                    );
                    $("#btn-create-order").prop("disabled", false);
                } else {
                    var info = {
                        data: {
                            code: $("#createOrder input[name='code']").val(),
                            sucursal_id: $(
                                "#createOrder select[name='sucursal_id']"
                            ).val(),
                            delivery_man_id: $(
                                "#createOrder select[name='delivery_man_id']"
                            ).val(),
                            express_products: $(
                                "#createOrder textarea[name='express_products']"
                            ).val(),
                            order_type_id: order_type_id,
                        },
                        sucursalsTransf: [],
                        productsTransf: [],
                    };
                    var sucursals = [];
                    var j = 0;
                    for (let index = 0; index < 10; index++) {
                        if ($("#st" + index).length) {
                            if ($("#st" + index).val() != "") {
                                sucursals[j] = $("#st" + index).val();
                                console.log(sucursals[j]);
                                j++;
                            }
                        }
                    }
                    info.sucursalsTransf.push(sucursals);
                    var products = [];
                    var l = 0;
                    for (let i = 0; i < 10; i++) {
                        if ($("#pt" + i).length) {
                            products[l] = $("#pt" + i).val();
                            l++;
                        }
                    }
                    info.productsTransf.push(products);
                    console.log(
                        "sucu: " +
                            sucursals.length +
                            " produc:" +
                            products.length
                    );

                    if (!sucursals.length == products.length) {
                        swal(
                            "Advertencia",
                            Lang.get("messagesClient.orders_tag3"),
                            "warning"
                        );
                        $("#btn-create-order").prop("disabled", false);
                        return;
                    }

                    swal(Lang.get("messagesClient.orders_tag4"), {
                        buttons: {
                            cancel: "Cancelar",
                            Ok: true,
                        },
                    }).then((val) => {
                        if (val == "Ok") {
                            $("#modalLoader").modal("show");
                            $("#modalLoader").css("display", "flex");

                            $.ajax({
                                url: "/orders/create",
                                type: "POST",
                                contentType: "application/json",
                                headers: {
                                    "X-CSRF-TOKEN": $(
                                        'meta[name="csrf-token"]'
                                    ).attr("content"),
                                    "Content-Type": "application/json",
                                },
                                data: JSON.stringify(info),
                                success: function (r) {
                                    console.log(r);
                                    $("#modalLoader").modal("hide");
                                    $("#modalLoader").css("display", "none");
                                    if (r.r) {
                                        id = r.id;

                                        swal(
                                            Lang.get(
                                                "messagesClient.orders_tag5"
                                            ),
                                            {
                                                icon: "success",
                                                buttons: {
                                                    cancel: "No",
                                                    Ok: "Imprimir",
                                                },
                                            }
                                        ).then((val) => {
                                            if (val == "Ok") {
                                                window.onbeforeunload = null;
                                                printInvoice(id);
                                                $(location).attr(
                                                    "href",
                                                    "/orders"
                                                );
                                            } else {
                                                window.onbeforeunload = null;
                                                $(location).attr(
                                                    "href",
                                                    "/orders"
                                                );
                                            }
                                        });
                                    } else {
                                        $("#modalLoader").modal("hide");
                                        $("#modalLoader").css(
                                            "display",
                                            "none"
                                        );
                                        swal("Error", r.m, "error");
                                        $("#btn-create-order").prop(
                                            "disabled",
                                            false
                                        );
                                    }
                                },
                                error: function (e) {
                                    $("#modalLoader").modal("hide");
                                    $("#modalLoader").css("display", "none");
                                    swal(
                                        "Error",
                                        Lang.get("messagesClient.orders_tag6"),
                                        "error"
                                    );
                                    $("#btn-create-order").prop(
                                        "disabled",
                                        false
                                    );
                                },
                            });
                        } else {
                            $("#btn-create-order").prop("disabled", false);
                        }
                    });
                }
            }
        });
}

function createTransfer() {
    console.log(" order traslado");
    needToConfirmT = false;
    order_type_id = 3;

    $("#createOrder").validator("update");
    $("#createOrder")
        .validator("update")
        .on("submit", function (e) {
            if (e.isDefaultPrevented()) {
            } else {
                e.preventDefault();
                $("#btn-create-order").prop("disabled", true);

                var sucursal = $(
                    "#createOrder select[name='sucursal_id']"
                ).val();

                if (sucursal == "") {
                    swal(
                        "Advertencia",
                        Lang.get("messagesClient.orders_tag1"),
                        "warning"
                    );
                    $("#btn-create-order").prop("disabled", false);
                } else {
                    var info = {
                        data: {
                            code: $("#createOrder input[name='code']").val(),
                            sucursal_id: $(
                                "#createOrder select[name='sucursal_id']"
                            ).val(),
                            sucursal_origin_id: $(
                                "#createOrder select[name='sucursal_origin_id']"
                            ).val(),
                            delivery_man_id: $(
                                "#createOrder select[name='delivery_man_id']"
                            ).val(),
                            express_products: $(
                                "#createOrder textarea[name='express_products']"
                            ).val(),
                            order_type_id: order_type_id,
                        },
                        sucursalsTransf: [],
                        productsTransf: [],
                    };
                    var sucursals = [];
                    var j = 0;
                    for (let index = 0; index < 10; index++) {
                        if ($("#st" + index).length) {
                            if ($("#st" + index).val() != "") {
                                sucursals[j] = $("#st" + index).val();
                                console.log(sucursals[j]);
                                j++;
                            }
                        }
                    }
                    info.sucursalsTransf.push(sucursals);
                    var products = [];
                    var l = 0;
                    for (let i = 0; i < 10; i++) {
                        if ($("#pt" + i).length) {
                            products[l] = $("#pt" + i).val();
                            l++;
                        }
                    }
                    info.productsTransf.push(products);
                    console.log(
                        "sucu: " +
                            sucursals.length +
                            " produc:" +
                            products.length
                    );

                    if (!sucursals.length == products.length) {
                        swal(
                            "Advertencia",
                            Lang.get("messagesClient.orders_tag3"),
                            "warning"
                        );
                        $("#btn-create-order").prop("disabled", false);
                        return;
                    }

                    swal(Lang.get("messagesClient.orders_tag4"), {
                        buttons: {
                            cancel: "Cancelar",
                            Ok: true,
                        },
                    }).then((val) => {
                        if (val == "Ok") {
                            $("#modalLoader").modal("show");
                            $("#modalLoader").css("display", "flex");

                            $.ajax({
                                url: "/orders/create",
                                type: "POST",
                                contentType: "application/json",
                                headers: {
                                    "X-CSRF-TOKEN": $(
                                        'meta[name="csrf-token"]'
                                    ).attr("content"),
                                    "Content-Type": "application/json",
                                },
                                data: JSON.stringify(info),
                                success: function (r) {
                                    console.log("esto es r:" + r);
                                    $("#modalLoader").modal("hide");
                                    $("#modalLoader").css("display", "none");
                                    if (r.r) {
                                        id = r.id;

                                        swal(
                                            Lang.get(
                                                "messagesClient.orders_tag5"
                                            ),
                                            {
                                                icon: "success",
                                                buttons: {
                                                    cancel: "No",
                                                    Ok: "Imprimir",
                                                },
                                            }
                                        ).then((val) => {
                                            if (val == "Ok") {
                                                window.onbeforeunload = null;
                                                printInvoice(id);
                                                $(location).attr(
                                                    "href",
                                                    "/orders"
                                                );
                                            } else {
                                                window.onbeforeunload = null;
                                                $(location).attr(
                                                    "href",
                                                    "/orders"
                                                );
                                            }
                                        });
                                    } else {
                                        $("#modalLoader").modal("hide");
                                        $("#modalLoader").css(
                                            "display",
                                            "none"
                                        );
                                        swal("Error", r.m, "error");
                                        $("#btn-create-order").prop(
                                            "disabled",
                                            false
                                        );
                                    }
                                },
                                error: function (e) {
                                    $("#modalLoader").modal("hide");
                                    $("#modalLoader").css("display", "none");
                                    swal(
                                        "Error",
                                        Lang.get("messagesClient.orders_tag6"),
                                        "error"
                                    );
                                    $("#btn-create-order").prop(
                                        "disabled",
                                        false
                                    );
                                },
                            });
                        } else {
                            $("#btn-create-order").prop("disabled", false);
                        }
                    });
                }
            }
        });
}

function createDiligence() {
    needToConfirmT = false;
    order_type_id = 4;

    $("#createOrder").validator("update");
    $("#createOrder")
        .validator("update")
        .on("submit", function (e) {
            if (e.isDefaultPrevented()) {
            } else {
                e.preventDefault();
                $("#btn-create-order").prop("disabled", true);

                var sucursal = $(
                    "#createOrder select[name='sucursal_id']"
                ).val();

                if (sucursal == "") {
                    swal(
                        "Advertencia",
                        Lang.get("messagesClient.orders_tag1"),
                        "warning"
                    );
                    $("#btn-create-order").prop("disabled", false);
                } else {
                    var info = {
                        data: {
                            code: $("#createOrder input[name='code']").val(),
                            sucursal_id: $(
                                "#createOrder select[name='sucursal_id']"
                            ).val(),
                            delivery_man_id: $(
                                "#createOrder select[name='delivery_man_id']"
                            ).val(),
                            express_products: $(
                                "#createOrder textarea[name='express_products']"
                            ).val(),
                            order_type_id: order_type_id,
                        },
                        sucursalsTransf: [],
                        productsTransf: [],
                    };
                    var sucursals = [];
                    var j = 0;
                    for (let index = 0; index < 10; index++) {
                        if ($("#st" + index).length) {
                            if ($("#st" + index).val() != "") {
                                sucursals[j] = $("#st" + index).val();
                                console.log(sucursals[j]);
                                j++;
                            }
                        }
                    }
                    info.sucursalsTransf.push(sucursals);
                    var products = [];
                    var l = 0;
                    for (let i = 0; i < 10; i++) {
                        if ($("#pt" + i).length) {
                            products[l] = $("#pt" + i).val();
                            l++;
                        }
                    }
                    info.productsTransf.push(products);
                    console.log(
                        "sucu: " +
                            sucursals.length +
                            " produc:" +
                            products.length
                    );

                    if (!sucursals.length == products.length) {
                        swal(
                            "Advertencia",
                            Lang.get("messagesClient.orders_tag3"),
                            "warning"
                        );
                        $("#btn-create-order").prop("disabled", false);
                        return;
                    }

                    swal(Lang.get("messagesClient.orders_tag4"), {
                        buttons: {
                            cancel: "Cancelar",
                            Ok: true,
                            allowOutsideClick: false,
                            closeOnConfirm: false,
                        },
                    }).then((val) => {
                        if (val == "Ok") {
                            $("#modalLoader").modal("show");
                            $("#modalLoader").css("display", "flex");

                            $.ajax({
                                url: "/orders/create",
                                type: "POST",
                                contentType: "application/json",
                                headers: {
                                    "X-CSRF-TOKEN": $(
                                        'meta[name="csrf-token"]'
                                    ).attr("content"),
                                    "Content-Type": "application/json",
                                },
                                data: JSON.stringify(info),
                                success: function (r) {
                                    console.log(r);
                                    $("#modalLoader").modal("hide");
                                    $("#modalLoader").css("display", "none");
                                    if (r.r) {
                                        id = r.id;

                                        swal(
                                            Lang.get(
                                                "messagesClient.orders_tag5"
                                            ),
                                            {
                                                icon: "success",
                                                buttons: {
                                                    cancel: "No",
                                                    Ok: "Imprimir",
                                                },
                                            }
                                        ).then((val) => {
                                            if (val == "Ok") {
                                                window.onbeforeunload = null;
                                                printInvoice(id);
                                                $(location).attr(
                                                    "href",
                                                    "/orders"
                                                );
                                            } else {
                                                window.onbeforeunload = null;
                                                $(location).attr(
                                                    "href",
                                                    "/orders"
                                                );
                                            }
                                        });
                                    } else {
                                        $("#modalLoader").modal("hide");
                                        $("#modalLoader").css(
                                            "display",
                                            "none"
                                        );
                                        swal("Error", r.m, "error");
                                        $("#btn-create-order").prop(
                                            "disabled",
                                            false
                                        );
                                    }
                                },
                                error: function (e) {
                                    $("#modalLoader").modal("hide");
                                    $("#modalLoader").css("display", "none");
                                    swal(
                                        "Error",
                                        Lang.get("messagesClient.orders_tag6"),
                                        "error"
                                    );
                                    $("#btn-create-order").prop(
                                        "disabled",
                                        false
                                    );
                                },
                            });
                        } else {
                            $("#btn-create-order").prop("disabled", false);
                        }
                    });
                }
            }
        });
}

function resetAttributes() {
    var value = $("#product").val();
    if (value == "") {
        $("#containerAttributes").empty();
    }
}

function resetAttr() {
    $("#product").val(null);
    $("#product").removeAttr("data-id");
    $("#product").removeAttr("data-price");
    $("#product").removeAttr("data-plu");
    $("#product").removeAttr("data-maxU");
    $("#product").removeAttr("data-product");
}

//*********************************
/// PEDIDO E-COMMERCE ////
//*********************************

//funcion para filtrar el producto por medio del plu o el nombre
function autocompleteProduct() {
    $("#containerAttributes").empty();
    resetAttributes();
    resetAttr();
    $(function () {
        $("#product").autocomplete({
            source: "/products/autocomplete",
            minLength: 3,
            select: function (event, ui) {
                $("#product").val(ui.item.value);
                $("#product").attr("data-id", ui.item.id);
                $("#product").attr("data-price", ui.item.price);
                $("#product").attr("data-plu", ui.item.plu);
                $("#product").attr("data-maxU", ui.item.max_units_per_order);
                $("#product").attr("data-product", ui.item.data);
                addAttibuttes(ui.item.product_attributes);
            },
        });
    });
}

function initIcheck() {
    $("input").iCheck({
        checkboxClass: "icheckbox_square-green",
        radioClass: "iradio_square-green",
        increaseArea: "20%", // optional
    });
}

function setColor(event) {
    let idDetail = "detail" + event.id.slice(5, event.id.length);
    $("#" + idDetail).text(event.value);
}

function addAttibuttes(attributes, hidden = "", value = false) {
    var formatter = new Intl.NumberFormat("en-US", {
        style: "currency",
        currency: "USD",
        minimumFractionDigits: 0,
    });
    var groupArray = Object.entries(attributes);
    $("#containerAttributes").empty();
    if (groupArray.length) {
        for (let i = 0; i < groupArray.length; i++) {
            if (groupArray[i][1][0].attribute.attribute_type_id != 1) {
                var isRequired = "";
                if (groupArray[i][1][0].attribute.required) {
                    isRequired = " (Requerido)";
                }

                var sel =
                    '<div class="row ' +
                    hidden +
                    '"><div class="titulo2-modal"><label for="exampleInputPassword1" class="label-product-info">' +
                    groupArray[i][1][0].attribute.display_name +
                    isRequired +
                    '</label></div></div><div class="row" style="background-color: #ececec;"> <div class="col-xs-4"><label style="font-weight: 700;">Valor</label></div><div class="col-xs-4"><label style="font-weight: 700;">Precio adicional</label></div> <div class="col-xs-4"><label style="font-weight: 700;"></label></div> ';
                $("#containerAttributes").append(sel);
                for (var v = 0; v < groupArray[i][1].length; v++) {
                    var attribute = groupArray[i][1][v];
                    var currentValue = "";
                    var moreOne = "";
                    var checked = "";
                    if (groupArray[i][1][0].attribute.attribute_type_id == 2) {
                        if (attribute.value == value) {
                            checked = "checked";
                        }
                        currentValue =
                            '<div class="form-group"><label><input ' +
                            checked +
                            ' type="radio" name="radio_' +
                            i +
                            '" id="radio_' +
                            i +
                            "_" +
                            v +
                            '" class="flat-red"> <span class="margin-left-7">' +
                            attribute.value +
                            "</span></label></div>";
                        checked = "";
                    }
                    if (groupArray[i][1][0].attribute.attribute_type_id == 3) {
                        if (attribute.value == value) {
                            checked = "checked";
                        }
                        currentValue =
                            '<div class="form-group"><label><input ' +
                            checked +
                            ' type="checkbox" name="checkbox_' +
                            i +
                            '" id="checkbox_' +
                            i +
                            "_" +
                            v +
                            '"  class="flat-red"> <span class="margin-left-7">' +
                            attribute.value +
                            "</span></label></div>";
                    }

                    if (groupArray[i][1][0].attribute.attribute_type_id == 4) {
                        if (attribute.value == value) {
                            checked = "checked";
                        }
                        currentValue =
                            '<div class="form-group"><label><input ' +
                            checked +
                            ' type="color" name="color_' +
                            i +
                            '" id="color_' +
                            i +
                            "_" +
                            v +
                            '" value="' +
                            attribute.value +
                            '" onchange="setColor(this)" onkeyup="setColor(this)" class="flat-red"> <span class="margin-left-7" id="detail_' +
                            i +
                            "_" +
                            v +
                            '">' +
                            attribute.value +
                            "</span></label></div>";
                    }

                    if (groupArray[i][1][0].attribute.is_more_one) {
                        if (attribute.value == value) {
                            checked = "checked";
                        }
                        moreOne =
                            '<div class="form-group"><input ' +
                            checked +
                            ' type="number" value="1" min="0" step="1" class="form-control width-35" name="input_' +
                            i +
                            '" id="input_' +
                            i +
                            "_" +
                            v +
                            '" ></div>';
                    }
                    var row =
                        '<div class="row ' +
                        hidden +
                        '"> <div class="col-xs-4">' +
                        currentValue +
                        '</div><div class="col-xs-4"><p>' +
                        formatter.format(attribute.price_additional) +
                        '</p></div><div class="col-xs-4"><p>' +
                        moreOne +
                        "</p></div></div></div>";
                    $("#containerAttributes").append(row);
                }
            }
        }
        initIcheck();
    }
}

function getValuesAttributes() {
    let result = [];
    let product_attributes = JSON.parse(
        $("#product").attr("data-product")
    ).product_attributes;
    let attributes = Object.keys(product_attributes);
    let checkerror = false;
    attributes.map(function (key, index) {
        let curentAttribute = product_attributes[key];
        let checkRequired = false;

        if (curentAttribute[0].attribute.required) {
            checkRequired = true;
        }

        let currentAttributeFilled = getValueFromAttribute(
            curentAttribute,
            index
        );

        if (currentAttributeFilled.length == 0 && checkRequired) {
            checkerror = true;
        }

        currentAttributeFilled.map((as) => {
            result.push(as);
        });
    });

    if (checkerror) {
        return false;
    }
    return result;
}

function getValueFromAttribute(attribute, parentIndex) {
    let index = 0;
    let attributesSelected = [];
    attribute.map((sv) => {
        switch (sv.attribute.attribute_type_id) {
            case 2: // Radio
                if ($(`#radio_${parentIndex}_${index}`).is(":checked")) {
                    attribute[index].quantity = 1;
                    attributesSelected.push(attribute[index]);
                }
                break;
            case 3: // Checkbox
                if (sv.attribute.is_more_one) {
                    let quantity = parseInt(
                        $(`#input_${parentIndex}_${index}`).val()
                    );
                    attribute[index].quantity = Math.abs(quantity);
                }
                if ($(`#checkbox_${parentIndex}_${index}`).is(":checked")) {
                    attributesSelected.push(attribute[index]);
                }
                break;
            case 4: // Color picker
                let color = $(`#color_${parentIndex}_${index}`).val();
                attribute[index].value = color;
                attribute[index].quantity = 1;
                attributesSelected.push(attribute[index]);
                break;
            default:
                break;
        }
        index++;
    });

    return attributesSelected;
}

/// agregar productos al listado del pedido
function addProduct() {
    var formatter = new Intl.NumberFormat("en-US", {
        style: "currency",
        currency: "USD",
        minimumFractionDigits: 0,
    });
    $("input[name='quantity']").css("border color", "#d2d6de");
    let valuesAttributes = getValuesAttributes();

    if (!valuesAttributes) {
        swal("", "Por favor indique los valores de los atributos.", "error");
        return;
    }

    aditionalPrice = 0;
    if (valuesAttributes && valuesAttributes.length) {
        for (let i = 0; i < valuesAttributes.length; i++) {
            let attribute = valuesAttributes[i];
            aditionalPrice += attribute.price_additional * attribute.quantity;
        }
    }
    //obtener la data del producto del input el cual viene en forma de array
    data_product = $("#product").attr("data-product");
    if (data_product && data_product != "") {
        data_product = JSON.parse(data_product);

        if (valuesAttributes && valuesAttributes.length) {
            product =
                data_product.id +
                "-" +
                valuesAttributes[0].attribute_id +
                "-" +
                valuesAttributes[0].value; // id
            producto =
                $("#product").val() +
                " - " +
                valuesAttributes[0].attribute.display_name +
                ": " +
                valuesAttributes[0].value; // nombre
        } else {
            product = data_product.id; // id
            producto = $("#product").val(); // nombre
        }

        plu = data_product.plu;
        price = data_product.price;
        priceTotal = parseInt(price) + aditionalPrice;
        max_units_per_order = data_product.max_units_per_order;

        quantity = $("input[name='quantity']").val();
        quantity = parseInt(quantity);

        if (quantity > 0 && product) {
            // si la cantidad del producto es mayor que 0
            if (max_units_per_order && quantity > max_units_per_order) {
                swal(
                    "",
                    "La cantidad supera el limite de unidades por pedido",
                    "warning"
                );
                return;
            }

            var productsArray = localStorage.getItem("arrayProducts");
            if (productsArray) {
                productsArray = JSON.parse(productsArray);
                if ($("#p-" + product).length > 0) {
                    for (let i = 0; i < productsArray.length; i++) {
                        //if(valuesAttributes[0].value == productsArray[i].product_attributes_selected[0].value){
                        //si ya hay productos en el array con el mismo id y con el mismo atributo solo se suma la cantidad  retorna
                        q1 = $("#p-" + product).val();
                        q2 = parseInt(q1) + quantity;
                        $("#p-" + product).val(q2);
                        addQuantity(
                            product,
                            data_product.percentage_discount,
                            data_product.start_discount,
                            data_product.limit_discount,
                            data_product.limit_hour_discount,
                            data_product.flash_price,
                            data_product.start_flash_discount,
                            data_product.limit_flash_discount,
                            data_product.limit_hour_flash_discount
                        ); ///enviar variables de descuento
                        $("#containerAttributes").empty();
                        return;
                        //}
                    }
                }
            }

            priceQuantity = quantity * parseInt(price); // se multimplica el price por la cantidad de productos

            var lastField = $("#list-products div:last");
            var intId =
                (lastField && lastField.length && lastField.data("idx") + 1) ||
                1;

            var fieldWrapper = $(
                '<div class=" fieldwrapper" data-price="' +
                    priceQuantity +
                    '" style="display:flex; width:100%; border-top: 2px solid;border-color: #f0f1f0de; padding: 4px;align-items: center; margin-top: 10px;background: #fdfdfd; " id="field' +
                    intId +
                    '" />'
            );
            fieldWrapper.data("idx", intId);
            var dateCurrent = new Date();
            var priceAfterDiscount = 0;
            var priceAfterFlash = 0;
            if (data_product.percentage_discount) {
                // se mira si hay un porcentaje de descuento y se hacen las validaciones del tiempo para ver si aplica
                var startDiscount = data_product.start_discount;
                var stopDiscount =
                    data_product.limit_discount +
                    " " +
                    data_product.limit_hour_discount;
                if (
                    new Date(startDiscount).getTime() < dateCurrent &&
                    new Date(stopDiscount).getTime() > dateCurrent
                ) {
                    var priceDiscount =
                        data_product.price -
                        (data_product.price *
                            data_product.percentage_discount) /
                            100; // se calcula el precio
                    var fName = $(
                        '  <div style="width: 33.33333333%; "> <p>' +
                            producto +
                            '</p></div> <div style="width: 16.66666667%;"> <p class="p-list-Pedidos plu-list-orders">' +
                            plu +
                            '</p></div> <div style="width: 16.66666667%;"> <div class="form-group"> <input id="p-' +
                            product +
                            '" data-id="' +
                            product +
                            '" onchange="changeQuantity(this)" name="' +
                            product +
                            '" class="cantidadProductos form-control idProducts" maxlength="3"  min="1" type="number" style="margin-top: 10px;" value="' +
                            quantity +
                            '" required></div> </div> <div id="row-' +
                            product +
                            '" style="width: 16.66666667%; display:flex;" > <p style="margin-left: 25px;" name="' +
                            product +
                            '" class="precio_list p-list-Pedidos" ><del>' +
                            formatter.format(priceTotal) +
                            ' </del> </p> <p class="text-red">' +
                            formatter.format(priceDiscount) +
                            "</p></div>"
                    );
                    priceAfterDiscount = priceDiscount;
                } else {
                    var fName = $(
                        '  <div style="width: 33.33333333%; "> <p>' +
                            producto +
                            '</p></div> <div style="width: 16.66666667%;"> <p class="p-list-Pedidos plu-list-orders">' +
                            plu +
                            '</p></div> <div style="width: 16.66666667%;"> <div class="form-group"> <input id="p-' +
                            product +
                            '" data-id="' +
                            product +
                            '" onchange="changeQuantity(this)" name="' +
                            product +
                            '" class="cantidadProductos form-control idProducts" maxlength="3"  min="1" type="number" style="margin-top: 10px;" value="' +
                            quantity +
                            '" required></div> </div> <div id="row-' +
                            product +
                            '" style="width: 16.66666667%;"> <p style="margin-left: 25px;" name="' +
                            product +
                            '" class="precio_list p-list-Pedidos">' +
                            formatter.format(priceTotal) +
                            "</p></div>"
                    );
                }
            } else if (data_product.flash_price) {
                // se mira si hay un precio relampago y se hacen las validaciones del tiempo para ver si aplica
                var startFlash = data_product.start_flash_discount;
                var stopFlash =
                    data_product.limit_flash_discount +
                    " " +
                    data_product.limit_hour_flash_discount;
                if (
                    new Date(startFlash).getTime() < dateCurrent &&
                    new Date(stopFlash).getTime() > dateCurrent
                ) {
                    var priceFlash = data_product.flash_price; // se calcula el precio
                    var fName = $(
                        '  <div style="width: 33.33333333%; "> <p>' +
                            producto +
                            '</p></div> <div style="width: 16.66666667%;"> <p class="p-list-Pedidos plu-list-orders">' +
                            plu +
                            '</p></div> <div style="width: 16.66666667%;"> <div class="form-group"> <input id="p-' +
                            product +
                            '" data-id="' +
                            product +
                            '" onchange="changeQuantity(this)" name="' +
                            product +
                            '" class="cantidadProductos form-control idProducts" maxlength="3"  min="1" type="number" style="margin-top: 10px;" value="' +
                            quantity +
                            '" required></div> </div> <div  id="row-' +
                            product +
                            '" style="width: 16.66666667%; display:flex;" > <p style="margin-left: 25px;" name="' +
                            product +
                            '" class="precio_list p-list-Pedidos" ><del>' +
                            formatter.format(priceTotal) +
                            ' </del> </p> <p class="text-red">' +
                            formatter.format(priceFlash) +
                            "</p></div>"
                    );
                    priceAfterFlash = priceFlash;
                } else {
                    var fName = $(
                        '  <div style="width: 33.33333333%; "> <p>' +
                            producto +
                            '</p></div> <div style="width: 16.66666667%;"> <p class="p-list-Pedidos plu-list-orders">' +
                            plu +
                            '</p></div> <div style="width: 16.66666667%;"> <div class="form-group"> <input id="p-' +
                            product +
                            '" data-id="' +
                            product +
                            '" onchange="changeQuantity(this)" name="' +
                            product +
                            '" class="cantidadProductos form-control idProducts" maxlength="3"  min="1" type="number" style="margin-top: 10px;" value="' +
                            quantity +
                            '" required></div> </div> <div  id="row-' +
                            product +
                            '" style="width: 16.66666667%;"> <p style="margin-left: 25px;" name="' +
                            product +
                            '" class="precio_list p-list-Pedidos">' +
                            formatter.format(priceTotal) +
                            "</p></div>"
                    );
                }
            } else {
                var fName = $(
                    '  <div style="width: 33.33333333%; "> <p>' +
                        producto +
                        '</p></div> <div style="width: 16.66666667%;"> <p class="p-list-Pedidos plu-list-orders">' +
                        plu +
                        '</p></div> <div style="width: 16.66666667%;"> <div class="form-group"> <input id="p-' +
                        product +
                        '" data-id="' +
                        product +
                        '" onchange="changeQuantity(this)" name="' +
                        product +
                        '" class="cantidadProductos form-control idProducts" maxlength="3"  min="1" type="number" style="margin-top: 10px;" value="' +
                        quantity +
                        '" required></div> </div> <div id="row-' +
                        product +
                        '" style="width: 16.66666667%;"> <p style="margin-left: 25px;" name="' +
                        product +
                        '" class="precio_list p-list-Pedidos">' +
                        formatter.format(priceTotal) +
                        "</p></div>"
                );
            }

            var removeButton = $(
                '<div data-id="' +
                    product +
                    '" class="col-xs-2 delete-product" ><button data-id="' +
                    product +
                    '" type="button"  class="remove btn btn-danger fa fa-trash " style="margin-left: 5px; height: 34px; " value="" />  </button> </div> '
            );

            if (priceAfterDiscount) {
                priceTotal = priceAfterDiscount + aditionalPrice;
            }

            if (priceAfterFlash) {
                priceTotal = priceAfterFlash + aditionalPrice;
            }

            if (valuesAttributes && valuesAttributes.length) {
                product = product.split("-", 3)[0];
            }

            //se crea un objeto con los datos para agregar al array de productos
            var element = {
                quantity: quantity,
                max_units_per_order: max_units_per_order,
                price: price,
                priceTotal,
                id: product,
                plu: plu,
                name: producto,
                priceAfterDiscount: priceAfterDiscount,
                priceAfterFlash: priceAfterFlash,
                percentage_discount: data_product.percentage_discount,
                start_discount: data_product.start_discount,
                limit_discount: data_product.limit_discount,
                limit_hour_discount: data_product.limit_hour_discount,
                flash_price: data_product.flash_price,
                start_flash_discount: data_product.start_flash_discount,
                limit_flash_discount: data_product.limit_flash_discount,
                limit_hour_flash_discount:
                    data_product.limit_hour_flash_discount,
                product_attributes_selected: valuesAttributes,
            };
            //guardar en el storage el array deproductos con sus atributos

            var arrayProducts = localStorage.getItem("arrayProducts");

            if (arrayProducts) {
                //si el array existe, agregamos y guardamos
                arrayProducts = JSON.parse(arrayProducts);
                console.log("arrayProducts: ", arrayProducts);
                arrayProducts.push(element);
                arrayProducts = JSON.stringify(arrayProducts);
                localStorage.setItem("arrayProducts", arrayProducts);
            } else {
                // la primera vez el array no existe por lo tanto se crea
                var arrayProducts = new Array();
                arrayProducts.push(element);
                arrayProducts = JSON.stringify(arrayProducts);
                localStorage.setItem("arrayProducts", arrayProducts);
            }

            calculateTotal();

            removeButton.click(function () {
                // elimina el elemento de la vista y del array
                var arrayProducts = localStorage.getItem("arrayProducts");
                arrayProducts = JSON.parse(arrayProducts);

                var idObj = $(this).attr("data-id");

                for (let i = 0; i < arrayProducts.length; i++) {
                    if (arrayProducts[i].id == idObj) {
                        arrayProducts.splice(i, 1);
                    }
                }
                arrayProducts = JSON.stringify(arrayProducts);
                localStorage.setItem("arrayProducts", arrayProducts);

                calculateTotal();
                $(this).parent().remove();
            });

            fieldWrapper.append(fName);
            fieldWrapper.append(removeButton);
            $("#list-products").append(fieldWrapper);
        } else {
            $("input[name='quantity']").css("border color", "red");
        }
    } else {
        swal("Error", "Debes seleccionar un producto", "warning");
        return;
    }
    $("#containerAttributes").empty();
    $("input[name='quantity']").val("1");
    resetAttributes();
    resetAttr();
}

function calculateTotal() {
    var formatter = new Intl.NumberFormat("en-US", {
        style: "currency",
        currency: "USD",
        minimumFractionDigits: 0,
    });

    var arrayProducts = localStorage.getItem("arrayProducts");
    if (arrayProducts && arrayProducts.length) {
        arrayProducts = JSON.parse(arrayProducts);
        var cost_delivery = $("#cost-delivery").text();
        cost_delivery = parseInt(cost_delivery);
        var subtotal = 0;
        var totalSumDiscount = 0;
        var total = 0;
        for (let i = 0; i < arrayProducts.length; i++) {
            var dateCurrent = new Date();
            var priceAfterDiscount = 0;
            var priceAfterFlash = 0;
            if (arrayProducts[i].percentage_discount) {
                // se mira si hay un porcentaje de descuento y se hacen las validaciones del tiempo para ver si aplica
                var startDiscount = arrayProducts[i].start_discount;
                var stopDiscount =
                    arrayProducts[i].limit_discount +
                    " " +
                    arrayProducts[i].limit_hour_discount;

                if (
                    new Date(startDiscount).getTime() < dateCurrent &&
                    new Date(stopDiscount).getTime() > dateCurrent
                ) {
                    var priceDiscount =
                        arrayProducts[i].price -
                        (arrayProducts[i].price *
                            arrayProducts[i].percentage_discount) /
                            100; // se calcula el precio
                    subtotal =
                        subtotal + priceDiscount * arrayProducts[i].quantity;
                    arrayProducts[i].priceAfterDiscount = priceDiscount;
                    priceAfterDiscount = priceDiscount;
                    $("#row-" + arrayProducts[i].id).empty();
                    $("#row-" + arrayProducts[i].id).append(
                        '<p style="margin-left: 25px;" name="' +
                            arrayProducts[i].id +
                            '" class="precio_list p-list-Pedidos" ><del>' +
                            formatter.format(arrayProducts[i].price) +
                            ' </del> </p> <p class="text-red">' +
                            formatter.format(priceDiscount) +
                            "</p>"
                    );
                } else {
                    subtotal =
                        subtotal +
                        arrayProducts[i].price * arrayProducts[i].quantity;
                    $("#row-" + arrayProducts[i].id).empty();
                    $("#row-" + arrayProducts[i].id).append(
                        '<p style="margin-left: 25px;" name="' +
                            arrayProducts[i].id +
                            '" class="precio_list p-list-Pedidos">' +
                            formatter.format(arrayProducts[i].price) +
                            "</p>"
                    );
                }
            } else if (arrayProducts[i].flash_price) {
                // se mira si hay un precio relampago y se hacen las validaciones del tiempo para ver si aplica
                var startFlash = arrayProducts[i].start_flash_discount;
                var stopFlash =
                    arrayProducts[i].limit_flash_discount +
                    " " +
                    arrayProducts[i].limit_hour_flash_discount;
                if (
                    new Date(startFlash).getTime() < dateCurrent &&
                    new Date(stopFlash).getTime() > dateCurrent
                ) {
                    subtotal =
                        subtotal +
                        arrayProducts[i].flash_price *
                            arrayProducts[i].quantity;
                    arrayProducts[i].priceAfterFlash =
                        arrayProducts[i].flash_price;
                    priceAfterFlash = arrayProducts[i].flash_price;
                    $("#row-" + arrayProducts[i].id).empty();
                    $("#row-" + arrayProducts[i].id).append(
                        '<p style="margin-left: 25px;" name="' +
                            arrayProducts[i].id +
                            '" class="precio_list p-list-Pedidos" ><del>' +
                            formatter.format(arrayProducts[i].price) +
                            ' </del> </p> <p class="text-red">' +
                            formatter.format(arrayProducts[i].flash_price) +
                            "</p>"
                    );
                    if (
                        new Date(startFlash).getTime() < dateCurrent &&
                        new Date(stopFlash).getTime() > dateCurrent
                    ) {
                        subtotal =
                            subtotal +
                            arrayProducts[i].flash_price *
                                arrayProducts[i].quantity;
                        arrayProducts[i].priceAfterFlash =
                            arrayProducts[i].flash_price;
                        $("#row-" + arrayProducts[i].id).empty();
                        $("#row-" + arrayProducts[i].id).append(
                            '<p style="margin-left: 25px;" name="' +
                                arrayProducts[i].id +
                                '" class="precio_list p-list-Pedidos" ><del>$' +
                                arrayProducts[i].price +
                                ' </del> </p> <p class="text-red">$' +
                                arrayProducts[i].flash_price +
                                "</p>"
                        );
                    } else {
                        subtotal =
                            subtotal +
                            arrayProducts[i].price * arrayProducts[i].quantity;
                        $("#row-" + arrayProducts[i].id).empty();
                        $("#row-" + arrayProducts[i].id).append(
                            '<p style="margin-left: 25px;" name="' +
                                arrayProducts[i].id +
                                '" class="precio_list p-list-Pedidos">$' +
                                arrayProducts[i].price +
                                "</p>"
                        );
                    }
                } else {
                    subtotal =
                        subtotal +
                        arrayProducts[i].price * arrayProducts[i].quantity;
                    $("#row-" + arrayProducts[i].id).empty();
                    $("#row-" + arrayProducts[i].id).append(
                        '<p style="margin-left: 25px;" name="' +
                            arrayProducts[i].id +
                            '" class="precio_list p-list-Pedidos">' +
                            formatter.format(arrayProducts[i].price) +
                            "</p>"
                    );
                }
            } else {
                subtotal =
                    subtotal +
                    arrayProducts[i].priceTotal * arrayProducts[i].quantity;
                $("#row-" + arrayProducts[i].id).empty();
                $("#row-" + arrayProducts[i].id).append(
                    '<p style="margin-left: 25px;" name="' +
                        arrayProducts[i].id +
                        '" class="precio_list p-list-Pedidos">' +
                        formatter.format(arrayProducts[i].priceTotal) +
                        "</p>"
                );
            }

            if (priceAfterDiscount) {
                totalSumDiscount +=
                    (arrayProducts[i].price - priceAfterDiscount) *
                    arrayProducts[i].quantity;
            }

            if (priceAfterFlash) {
                totalSumDiscount +=
                    (arrayProducts[i].price - priceAfterFlash) *
                    arrayProducts[i].quantity;
            }
        }

        //descuento envio
        if ($("#tr-discountDelivery").length > 0) {
            var discountDelivery = $("#discountDelivery").text();
            discountDelivery = parseInt(discountDelivery);
            cost_delivery =
                cost_delivery - (cost_delivery * discountDelivery) / 100;
        }

        //descuento referido
        var subtotalBefore = subtotal;
        if ($("#tr-discountReferred").length > 0) {
            valueMin = $("#tr-discountReferred").attr("data-value");
            valueMin = parseInt(valueMin);
            if (subtotal >= valueMin) {
                if ($("#discountReferredPercentage").length > 0) {
                    var discountReferred = $(
                        "#discountReferredPercentage"
                    ).text();
                    discountReferred = parseInt(discountReferred);
                    subtotal = subtotal - (subtotal * discountReferred) / 100;
                } else {
                    $("#discountReferredPrice").text();
                    var discountReferred = $("#discountReferredPrice").text();
                    discountReferred = parseInt(discountReferred);
                    subtotal = subtotal - discountReferred;
                }
            }
        }

        //descuento campaña

        if ($("#tr-discountCampana").length > 0) {
            valueMin = $("#tr-discountCampana").attr("data-value");
            valueMin = parseInt(valueMin);
            if (subtotal >= valueMin) {
                if ($("#discountCampanaPercentage").length > 0) {
                    var discountCampana = $(
                        "#discountCampanaPercentage"
                    ).text();
                    discountCampana = parseInt(discountCampana);
                    subtotal = subtotal - (subtotal * discountCampana) / 100;
                } else {
                    $("#discountCampanaPrice").text();
                    var discountCampana = $("#discountCampanaPrice").text();
                    discountCampana = parseInt(discountCampana);
                    subtotal = subtotal - discountCampana;
                }
            }
        }

        // cupon discountCoupone

        if ($("#tr-discountCoupone").length > 0) {
            valueMin = $("#tr-discountCoupone").attr("data-value");
            valueMin = parseInt(valueMin);
            if (subtotal >= valueMin) {
                if ($("#discountCouponePercentage").length > 0) {
                    var discountCoupone = $(
                        "#discountCouponePercentage"
                    ).text();
                    discountCoupone = parseInt(discountCoupone);
                    subtotal = subtotal - (subtotal * discountCoupone) / 100;
                } else {
                    $("#discountCouponePrice").text();
                    var discountCoupone = $("#discountCouponePrice").text();
                    discountCoupone = parseInt(discountCoupone);
                    subtotal = subtotal - discountCoupone;
                }
            }
        }

        total = subtotal + cost_delivery;

        if (totalSumDiscount) {
            let totalWithDiscount = total + totalSumDiscount;
            $("#total_order_discount").removeClass("displayNone");
            $("#total_order_discount").text(
                formatter.format(totalWithDiscount)
            );
        } else {
            $("#total_order_discount").text(formatter.format(0));
            $("#total_order_discount").addClass("displayNone");
        }

        arrayProducts = JSON.stringify(arrayProducts);
        localStorage.setItem("arrayProducts", arrayProducts);
        $("#subtotal").text(formatNumber(subtotalBefore));
        $("#total_order").text(formatNumber(total));
    }
}

function changeQuantity(event) {
    var arrayProducts = localStorage.getItem("arrayProducts");
    arrayProducts = JSON.parse(arrayProducts);

    var idObj = event.name;
    var value = event.value;
    $("#" + event.name).css("border color", "#d2d6de");

    if (parseInt(value) > 0 && product) {
        for (let i = 0; i < arrayProducts.length; i++) {
            if (arrayProducts[i].id == idObj) {
                if (
                    arrayProducts[i].max_units_per_order &&
                    value > arrayProducts[i].max_units_per_order
                ) {
                    swal(
                        "",
                        "La cantidad supera el limite de unidades por pedido",
                        "warning"
                    );
                    return;
                } else {
                    arrayProducts[i].quantity = value;
                }
            }
        }
        arrayProducts = JSON.stringify(arrayProducts);
        localStorage.setItem("arrayProducts", arrayProducts);

        calculateTotal();
    } else {
        $("#" + event.name).css("border color", "red");
    }
}

function addQuantity(
    id,
    percentage_discount,
    start_discount,
    limit_discount,
    limit_hour_discount,
    flash_price,
    start_flash_discount,
    limit_flash_discount,
    limit_hour_flash_discount
) {
    var arrayProducts = localStorage.getItem("arrayProducts");
    arrayProducts = JSON.parse(arrayProducts);

    var idObj = $("#p-" + id).attr("data-id");
    var value = $("#p-" + id).val();

    for (let i = 0; i < arrayProducts.length; i++) {
        if (arrayProducts[i].id == idObj) {
            arrayProducts[i].quantity = value;
            arrayProducts[i].percentage_discount = percentage_discount;
            arrayProducts[i].start_discount = start_discount;
            arrayProducts[i].limit_discount = limit_discount;
            arrayProducts[i].limit_hour_discount = limit_hour_discount;
            arrayProducts[i].flash_price = flash_price;
            arrayProducts[i].start_flash_discount = start_flash_discount;
            arrayProducts[i].limit_flash_discount = limit_flash_discount;
            arrayProducts[i].limit_hour_flash_discount =
                limit_hour_flash_discount;
        }
    }
    arrayProducts = JSON.stringify(arrayProducts);
    localStorage.setItem("arrayProducts", arrayProducts);

    calculateTotal();
}

function autocompleteEmail() {
    $("#email").keyup(function (e) {
        if (e.keyCode == 8 || e.keyCode == 46 || e.keyCode == 32) {
            $("#user_id").attr("data-id", "");
            document.getElementById("createOrder").reset();
        }
    });
    $("#email").autocomplete({
        source: "/client/autocomplete/mail",
        minLength: 3,
        select: function (event, ui) {
            $("#user_id").val(ui.item.first_name);
            $("#last_name").val(ui.item.last_name);
            $("#user_id").attr("data-id", ui.item.id);
            $("#email").val(ui.item.email);
            $("#document").val(ui.item.document);
            $("#phone").val(ui.item.phone);

            direction = ui.item.directions;

            $("#address_id").empty();
            var sel = '<option value="">--Seleccione</option>';
            $("#address_id").append(sel);
            for (var i in direction) {
                if (direction[i].last_used == 1) {
                    var row =
                        '<option value="' +
                        direction[i].id +
                        '" data-lat="' +
                        direction[i].lat +
                        '"' +
                        ' data-long="' +
                        direction[i].long +
                        '"' +
                        ' indications="' +
                        direction[i].indications +
                        '"' +
                        ' district="' +
                        direction[i].district +
                        '"' +
                        ' selected="selected">' +
                        direction[i].direction +
                        "</option>";
                    $("#address_id_sales").append(row);
                } else {
                    var row =
                        '<option value="' +
                        direction[i].id +
                        '" data-lat="' +
                        direction[i].lat +
                        '"' +
                        ' data-long="' +
                        direction[i].long +
                        '"' +
                        ' indications="' +
                        direction[i].indications +
                        '"' +
                        ' district="' +
                        direction[i].district +
                        '">' +
                        direction[i].direction +
                        '"' +
                        "</option>";
                    $("#address_id_sales").append(row);
                }
            }
            //descuentos
            //primero se eliminan los tr del anterior cliente
            if ($("#tr-discountDelivery").length > 0) {
                $("#tr-discountDelivery").remove();
            }
            if ($("#tr-discountReferred").length > 0) {
                $("#tr-discountReferred").remove();
            }
            if ($("#tr-discountCampana").length > 0) {
                $("#tr-discountCampana").remove();
            }
            if ($("#tr-discountCoupone").length > 0) {
                $("#tr-discountCoupone").remove();
            }

            //envio
            if (ui.item.is_register_discount_active) {
                var rDelivery = discountDelivery(
                    ui.item.created_at,
                    ui.item.days_register_discount_delivery
                );
                if (rDelivery) {
                    var tr =
                        '<tr id="tr-discountDelivery"><th>Descuento envío:</th><td class="col-label"><h4 id="discountDelivery" class="label-number-order">' +
                        ui.item.register_discount_delivery +
                        "</h4>%</td></tr>";
                    $("#tableTotal >tbody").append(tr);
                }
            }

            //referido
            if (ui.item.clientRefer != null) {
                discountReferred(ui.item.discounts, ui.item.clientRefer);
            }

            //campaña
            discountCampana(ui.item.discounts);

            //colocar el id en input de cupon
            $("#discountCoupon").attr("data-id", ui.item.id);
        },
    });
}

function discountDelivery(registerClient, limit_discount) {
    var registerClient = new Date(registerClient);
    var dateCurrent = new Date();

    var day_as_milliseconds = 86400000;
    var diff_in_millisenconds = dateCurrent - registerClient;
    var diff_in_days = diff_in_millisenconds / day_as_milliseconds;

    console.log(diff_in_days);
    if (limit_discount <= diff_in_days) {
        return false;
    } else {
        return true;
    }
}

function discountReferred(discounts, idRefered) {
    discounts = JSON.parse(discounts);

    for (let i = 0; i < discounts.length; i++) {
        // el array ya trae los descuentos que esten vigentes segun la fecha actual
        if (discounts[i].discount_type_id == 8) {
            // se busca si hay decuentos tipo referido

            if (discounts[i].is_cumulative_another_discounts == 1) {
                if (discounts[i].price_discount != null) {
                    var tr =
                        '<tr id="tr-discountReferred" data-id="' +
                        idRefered +
                        '" data-value="' +
                        discounts[i].value_for_win +
                        '"><th>Descuento referido (monto minimo $' +
                        discounts[i].value_for_win +
                        '):</th><td class="col-label">$<h4 id="discountReferredPrice"  class="label-number-order">' +
                        discounts[i].price_discount +
                        "</h4></td></tr>";
                    $("#tableTotal >tbody").append(tr);
                } else {
                    var tr =
                        '<tr id="tr-discountReferred" data-id="' +
                        idRefered +
                        '"  data-value="' +
                        discounts[i].value_for_win +
                        '"><th>Descuento referido (monto minimo $' +
                        discounts[i].value_for_win +
                        '):</th><td class="col-label"><h4 id="discountReferredPercentage" class="label-number-order">' +
                        discounts[i].percentage_discount +
                        "</h4>%</td></tr>";
                    $("#tableTotal >tbody").append(tr);
                }
            } else {
                if (
                    $("#tr-discountDelivery").length > 0 ||
                    $("#tr-discountCampana").length > 0 ||
                    $("#tr-discountCoupone").length > 0
                ) {
                } else {
                    if (discounts[i].price_discount != null) {
                        var tr =
                            '<tr id="tr-discountReferred" data-id="' +
                            idRefered +
                            '"  data-value="' +
                            discounts[i].value_for_win +
                            '"><th>Descuento referido (monto minimo $' +
                            discounts[i].value_for_win +
                            '):</th><td class="col-label">$<h4 id="discountReferredPrice" class="label-number-order">' +
                            discounts[i].price_discount +
                            "</h4></td></tr>";
                        $("#tableTotal >tbody").append(tr);
                    } else {
                        var tr =
                            '<tr id="tr-discountReferred" data-id="' +
                            idRefered +
                            '"  data-value="' +
                            discounts[i].value_for_win +
                            '"><th>Descuento referido (monto minimo $' +
                            discounts[i].value_for_win +
                            '):</th><td class="col-label"><h4 id="discountReferredPercentage" class="label-number-order">' +
                            discounts[i].percentage_discount +
                            "</h4>%</td></tr>";
                        $("#tableTotal >tbody").append(tr);
                    }
                }
            }
        }
    }
}

function discountCampana(discounts) {
    discounts = JSON.parse(discounts);

    for (let i = 0; i < discounts.length; i++) {
        // el array ya trae los descuentos que esten vigentes segun la fecha actual
        if (discounts[i].discount_type_id == 3) {
            // se busca si hay decuentos tipo campaña

            if (discounts[i].is_cumulative_another_discounts == 1) {
                if (discounts[i].price_discount != null) {
                    var tr =
                        '<tr id="tr-discountCampana" data-id="' +
                        discounts[i].id +
                        '"  data-value="' +
                        discounts[i].value_for_win +
                        '"><th>Descuento campaña (monto minimo $' +
                        discounts[i].value_for_win +
                        '):</th><td class="col-label">$<h4 id="discountCampanaPrice" class="label-number-order">' +
                        discounts[i].price_discount +
                        "</h4></td></tr>";
                    $("#tableTotal >tbody").append(tr);
                } else {
                    var tr =
                        '<tr id="tr-discountCampana" data-id="' +
                        discounts[i].id +
                        '" data-value="' +
                        discounts[i].value_for_win +
                        '"><th>Descuento campaña (monto minimo $' +
                        discounts[i].value_for_win +
                        '):</th><td class="col-label"><h4 id="discountCampanaPercentage" class="label-number-order">' +
                        discounts[i].percentage_discount +
                        "</h4>%</td></tr>";
                    $("#tableTotal >tbody").append(tr);
                }
            } else {
                if (
                    $("#tr-discountDelivery").length > 0 ||
                    $("#tr-discountReferred").length > 0 ||
                    $("#tr-discountCoupone").length > 0
                ) {
                } else {
                    if (discounts[i].price_discount != null) {
                        var tr =
                            '<tr id="tr-discountCampana" data-id="' +
                            discounts[i].id +
                            '" data-value="' +
                            discounts[i].value_for_win +
                            '"><th>Descuento campaña (monto minimo $' +
                            discounts[i].value_for_win +
                            '):</th><td class="col-label">$<h4 id="discountCampanaPrice" class="label-number-order">' +
                            discounts[i].price_discount +
                            "</h4></td></tr>";
                        $("#tableTotal >tbody").append(tr);
                    } else {
                        var tr =
                            '<tr id="tr-discountCampana" data-id="' +
                            discounts[i].id +
                            '" data-value="' +
                            discounts[i].value_for_win +
                            '"><th>Descuento campaña (monto minimo $' +
                            discounts[i].value_for_win +
                            '):</th><td class="col-label"><h4 id="discountCampanaPercentage" class="label-number-order">' +
                            discounts[i].percentage_discount +
                            "</h4>%</td></tr>";
                        $("#tableTotal >tbody").append(tr);
                    }
                }
            }
        }
    }
}

function addCoupone() {
    console.log("cupon");
    if ($("#tr-discountCoupone").length > 0) {
        $("#tr-discountCoupone").remove();
    }
    $("#message-discount").css("display", "none");
    var id = $("#discountCoupon").attr("data-id");
    var code = $("#discountCoupon").val();

    if (id.length > 0) {
        $.ajax({
            url: "/clients/coupone/" + id + "/" + code,
            type: "GET",
            contentType: "application/json",
            headers: {
                "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
                "Content-Type": "application/json",
            },
            success: function (r) {
                if (r.r) {
                    if (r.d.is_cumulative_another_discounts == 1) {
                        if (r.d.price_discount != null) {
                            var tr =
                                '<tr id="tr-discountCoupone" data-id="' +
                                r.d.id +
                                '" data-value="' +
                                r.d.value_for_win +
                                '"><th>Descuento cupón (monto minimo $' +
                                r.d.value_for_win +
                                '):</th><td class="col-label">$<h4 id="discountCouponePrice" class="label-number-order">' +
                                r.d.price_discount +
                                "</h4></td></tr>";
                            $("#tableTotal >tbody").append(tr);
                        } else {
                            var tr =
                                '<tr id="tr-discountCoupone" data-id="' +
                                r.d.id +
                                '" data-value="' +
                                r.d.value_for_win +
                                '"><th>Descuento cupón (monto minimo $' +
                                r.d.value_for_win +
                                '):</th><td class="col-label"><h4 id="discountCouponePercentage" class="label-number-order">' +
                                r.d.percentage_discount +
                                "</h4>%</td></tr>";
                            $("#tableTotal >tbody").append(tr);
                        }
                    } else {
                        if (
                            $("#tr-discountDelivery").length > 0 ||
                            $("#tr-discountReferred").length > 0 ||
                            $("#tr-discountCampana").length > 0
                        ) {
                        } else {
                            if (r.d.price_discount != null) {
                                var tr =
                                    '<tr id="tr-discountCoupone" data-id="' +
                                    r.d.id +
                                    '" data-value="' +
                                    r.d.value_for_win +
                                    '"><th>Descuento cupón (monto minimo $' +
                                    r.d.value_for_win +
                                    '):</th><td class="col-label">$<h4 id="discountCouponePrice" class="label-number-order">' +
                                    r.d.price_discount +
                                    "</h4></td></tr>";
                                $("#tableTotal >tbody").append(tr);
                            } else {
                                var tr =
                                    '<tr id="tr-discountCoupone" data-id="' +
                                    r.d.id +
                                    '" data-value="' +
                                    r.d.value_for_win +
                                    '"><th>Descuento cupón (monto minimo $' +
                                    r.d.value_for_win +
                                    '):</th><td class="col-label"><h4 id="discountCouponePercentage" class="label-number-order">' +
                                    r.d.percentage_discount +
                                    "</h4>%</td></tr>";
                                $("#tableTotal >tbody").append(tr);
                            }
                        }
                    }

                    calculateTotal();
                } else {
                    $("#message-discount-text").empty();
                    $("#message-discount").css("display", "block");
                    $("#message-discount-text").append(r.m);
                    calculateTotal();
                }
            },
        });
    }
}

function fillNameClient(idUser, nameUser) {
    $("input[name='user_id']").val(idUser);
    $("input[name='user_id']").attr("data-id", nameUser);
}

//metodo de al dar enter en el input cedula se traigan los datos del cliente
$(function () {
    $("#document").keyup(function () {
        this.value = (this.value + "").replace(/[^0-9]/g, "");
    });

    $("#document").keypress(function (e) {
        if (e.which == 13) {
            cedula = $("#document").val();
            console.log(cedula);

            if (cedula.length > 0) {
                $.ajax({
                    url: "/clients/document/" + cedula,
                    type: "GET",
                    contentType: "application/json",
                    headers: {
                        "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr(
                            "content"
                        ),
                        "Content-Type": "application/json",
                    },
                    success: function (r) {
                        if (r.r) {
                            /// modificar
                            $("#user_id").val(r.client.first_name);
                            $("#last_name").val(r.client.last_name);
                            $("#user_id").attr("data-id", r.client.id);
                            $("#document").val(r.client.document);
                            $("#phone").val(r.client.phone);

                            $("#direction").val(r.direction);
                            $("#direction").attr("data-id", r.id);
                            $("#district").val(r.district);
                            $("#indications").val(r.indications);
                            $("#direction").attr("data-lat", r.lat);
                            $("#direction").attr("data-long", r.long);
                        }
                    },
                });
            }
        }
    });
});