var confirmText = $("#Confirm").val();
var cancelText = $("#Cancel").val();
var confirmDeleteText = $("#ConfirmDeleteMessage").val();
var generalErrorText = $("#GeneralError").val();
var saveDailyWage = "saveDailyWageBtn";
var dailyWageValueType = "dailyWageValue";

function initializeDailyWages() {
    let url = window.location.href;
    let splitted = url.split('=');
    let id = decodeURI(splitted[splitted.length - 1]);

    $dataTable = $('#mainGrid');

    $(".selectpicker-dropdown").on("hide.bs.dropdown", function () {
        $dataTable.DataTable().ajax.reload();
    });

    $dataTable.DataTable({
        ajax: {
            url: $dataTable.attr('data-url'),
            data: function (d) {
                d.Keywords = $("#Keywords").val();
            }
        },
        columns: [
            { data: "DailyAllow", name: "acDailyAllow", filtertype: "text", render: $.fn.dataTable.render.link("DailyAllow") },
            { data: "Name", name: "acName", filtertype: "text" },
            { data: "PriceTo", name: "anPriceTo", filtertype: "text", render: $.fn.dataTable.render.number('.', ',', 2), className: 'dt-body-right' },
            { data: "PriceAbove", name: "anPriceAbove", filtertype: "text", render: $.fn.dataTable.render.number('.', ',', 2), className: 'dt-body-right' },
            { data: "Currency", name: "acCurrency", filtertype: "text" },
            { data: "Date", name: "adDate", filtertype: "text", render: function (data) {
                    if (data === null) {
                        return "";
                    } else {
                        return moment(data).format('DD.MM.YYYY');
                    }
                }
            },
        ],
        "createdRow": function (row, data, dataIndex) {
            if (data.DailyAllow == id) {
                $(row).addClass('side-menu-item-active').children(":first").addClass('side-menu-item-active');
            }
        }
    });

    var typingTimer;
    var doneTypingInterval = 600;
    $('#Keywords').off('keyup');
    $('#Keywords').on('keyup', function () {
        clearTimeout(typingTimer);
        typingTimer = setTimeout(function () { $.fn.dataTable.reload($dataTable); }, doneTypingInterval);
    });
}

/*Daily Wages*/
function addDailyWage(rowId, actionMethod, buttonId) {
    let dailyAllow = $("#DailyAllow").val();

    if (!dailyAllow) {
        $("#DailyAllow").addClass("validation-error-border");
        return;
    } else {
        $("#DailyAllow").removeClass("validation-error-border");
    }

    if (actionMethod == "Create") {
        createDailyWage(dailyAllow);
    } else if (actionMethod == "Edit") {
        if (buttonId === saveDailyWage) {
            editDailyWage(dailyAllow);
        } else {
            addDailyWageValue(rowId, dailyAllow);
        }
    }
}

function createDailyWage(dailyAllow) {
    var dailyWages = [];

    if ($("#dailyWageDate").val()) {
        dailyWages = [{
            DailyAllow: dailyAllow,
            Date: $("#dailyWageDate").val(),
            PriceTo: removeDots($("#dailyWagePriceTo").val()),
            PriceAbove: removeDots($("#dailyWagePriceAbove").val()),
            Currency: $("#dailyWageCurrency").val()
        }]
    }

    $.ajax({
        url: $("#CreateDailyWageUrl").val(),
        type: "POST",
        dataType: "json",
        data: {
            DailyAllow: dailyAllow,
            Name: $("#Name").val(),
            DailyWages: dailyWages
        },
        success: function (data) {
            if (data.Status == false) {
                openPrimaryKeyExistModal();
            }
            else {
                window.location = $("#EditDailyWageUrl").val() + "?dailyWageCode=" + dailyAllow + "&created=true";
            }
        }
    });
}

function editDailyWage(dailyAllow) {
    $.ajax({
        url: $("#UpdateDailyWageUrl").val(),
        type: "PUT",
        dataType: "json",
        data: {
            DailyAllow: dailyAllow,
            Name: $("#Name").val(),
        },
        success: function (data) {
            if (data.Status == false) {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "alert",
                    text: generalErrorText,
                    buttons: [{
                        icon: 'fa fa-check',
                        text: confirmText,
                        closeOnAction: true,
                        type: 'primary'
                    }]
                });
            }
            else {
                location.reload();
            }
        }
    });
}

function deleteDailyWage(dailyWageCode) {
    $(document).ready(function () {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "question",
            text: confirmDeleteText,
            buttons: [{
                icon: 'fa fa-times',
                text: cancelText,
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                text: confirmText,
                closeOnAction: true,
                action: async function () {
                    removeDailyWage(dailyWageCode);
                },
                closeOnAction: true,
                type: 'primary'
            }]
        });
    });
}

function removeDailyWage(dailyWageCode) {
    $.ajax({
        url: $("#DeleteDailyWageUrl").val(),
        type: 'POST',
        data: { dailyWageCode: dailyWageCode },
        success: function (data) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: $("#DailyWageWasDeleted").val(),
                buttons: [
                {
                    icon: 'fa fa-check',
                    text: confirmText,
                    closeOnAction: true,
                    action: async function () {
                        window.location.href = $("#DailyWagesUrl").val();
                    },
                    closeOnAction: true,
                    type: 'primary'
                }]
            });
        }
    });
}

/*Daily Wage Values*/
function addDailyWageValue(rowId, dailyAllow) {
    if (!validateRow(rowId)) {
        return;
    }

    $.ajax({
        url: $("#AddDailyWageValueUrl").val(),
        type: "POST",
        data: {
            DailyAllow: dailyAllow,
            Date: $("#dailyWageDate").val(),
            PriceTo: removeDots($("#dailyWagePriceTo").val()),
            PriceAbove: removeDots($("#dailyWagePriceAbove").val()),
            Currency: $("#dailyWageCurrency").val()
        },
        success: function (data) {
            if (data.Status == false) {
                openPrimaryKeyExistModal();
            }
            else {
                location.reload();
            }
        }
    })
}

function updateDailyWageValue(rowId, rowNum) {
    if (!validateRow(rowId)) {
        return;
    }

    const dailyAllow = $("#DailyAllow").val();
    const date = $("#dailyWageHiddenDate-" + rowNum).val();
    const dailyWageValue = {
        DailyAllow: dailyAllow,
        Date: $("#dailyWageDate-" + rowNum).val(),
        PriceTo: removeDots($("#dailyWagePriceTo-" + rowNum).val()),
        PriceAbove: removeDots($("#dailyWagePriceAbove-" + rowNum).val()),
        Currency: $("#dailyWageCurrency-" + rowNum).val()
    }
    const data = {
        date,
        dailyWageValue
    };

    $.ajax({
        url: $("#UpdateDailyWageValueUrl").val(),
        type: "PUT",
        data: data,
        success: function (data) {
            if (data.Status == false && data.Message == dailyWageValue.Date) {
                openPrimaryKeyExistModal();
            }
            else {
                location.reload();
            }
        }
    })
}

function deleteDailyWageValue(date) {
    const data = {
        date,
        dailyAllow: $("#DailyAllow").val()
    };

    $.ajax({
        url: $("#DeleteDailyWageValueUrl").val(),
        type: "DELETE",
        data: data,            
        success: function () {
            location.reload();
        }
    });
}

/*Mileage*/
function addMileage(rowId) {
    if (!validateRow(rowId)) {
        return;
    }

    let url = $("#AddMileageUrl").val();
    let model = {
        Date: $("#mileageDate").val(),
        PriceTo: removeDots($("#mileagePriceTo").val()),
        Km: removeDots($("#mileageKm").val()),
        PriceAbove: removeDots($("#mileagePriceAbove").val()),
        Currency: $("#mileageCurrency").val()
    }
   
    $.ajax({
        url: url,
        type: "POST",
        data: model,
        success: function (data) {
            if (data.Status == false && data.Message == model.Date) {
                openPrimaryKeyExistModal();
            }
            else {
               location.reload();
            }
        }
    });
}

function updateMileage(rowId, rowNum) {
    if (!validateRow(rowId)) {
        return;
    }

    const url = $("#UpdateMileageUrl").val();
    const model = {
        Date: $("#mileageDate-" + rowNum).val(),
        PriceTo: removeDots($("#mileagePriceTo-" + rowNum).val()),
        Km: removeDots($("#mileageKm-" + rowNum).val()),
        PriceAbove: removeDots($("#mileagePriceAbove-" + rowNum).val()),
        Currency: $("#mileageCurrency-" + rowNum).val()
    }
    const data = {
        date: $("#mileageHiddenDate-" + rowNum).val(),
        mileage: model
    };

    $.ajax({
        url: url,
        type: "PUT",
        data: data,
        success: function (data) {
            if (data.Status == false && data.Message == model.Date) {
                openPrimaryKeyExistModal();
            }
            else {
                location.reload();
            }
        }
    });
}

function deleteMileage(date) {
    const data = { date };

    $.ajax({
        url: $("#DeleteMileageUrl").val(),
        type: "DELETE",
        data: data,
        success: function (data) {
            location.reload();
        }
    });
}

/*Modals*/
function openDeleteModal(date, type) {
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "question",
        text: confirmDeleteText,
        buttons: [{
            icon: 'fa fa-times',
            text: cancelText,
            closeOnAction: true,
            type: 'ghost'
        },
        {
            icon: 'fa fa-check',
            text: confirmText,
            closeOnAction: true,
            action: async function () {
                if (type === dailyWageValueType) {
                    deleteDailyWageValue(date);
                } else {
                    deleteMileage(date);
                }
            },
            closeOnAction: true,
            type: 'primary'
        }]
    });
}

function openPrimaryKeyExistModal() {
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "alert",
        text: $("#PrimaryKeyExists").val(),
        buttons: [
            {
                icon: 'fa fa-check',
                text: confirmText,
                closeOnAction: true,
                type: 'primary'
            }]
    });
}

function validateRow(rowId) {
    let valid = true;
    $("#" + rowId).each(function () {
        $(this)
            .find(':input')
            .each(function () {
                let required = $(this).attr('required');
                let value = $(this).val();
                let hiddenCol = $(this).parent().hasClass("hidden-column");

                if (required && !value && !hiddenCol) {
                    valid = false;
                    $(this).parents('td').last().addClass("validation-error-border");
                }
                else {
                    $(this).parents('td').last().removeClass("validation-error-border");
                }

            });
    });
    return valid;
}