$("#general_information").click(function() {
    showTabClickError();
});
$("#parent_details_information").click(function() {
    showTabClickError();
});
$("#breeding_information").click(function() {
    showTabClickError();
});

function showTabClickError() {
    let tabClickErrorMessage = '<div class="alert alert-danger alert-dismissible fade show" role="alert">Tab is disable. You can go next tab only fillup all the required field.<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>';
    document.getElementById("tab-click-error").insertAdjacentHTML("afterend", tabClickErrorMessage);
    $('.alert-dismissible').delay(2000).fadeOut(600);
}

//When old value selected
$(document).ready(function($) {
    $('.select2-multiple').select2();
    let breedingStatus = $('input[name="breeding_status"]:checked').val();
    let reproductionStatus = $('input[name="reproduction_status"]:checked').val();
    breedingStatusView(breedingStatus);
    reproductionView(reproductionStatus);
    // getHerd();
});

function breedingStatusView(status) {
    if (status === 'milking') {
        $('#milking1').removeClass('d-none');
        $('#milking2').removeClass('d-none');
        $('#dry1').addClass('d-none');
        $('#dry2').addClass('d-none');
    } else if (status === 'dry') {
        $('#dry1').removeClass('d-none');
        $('#dry2').removeClass('d-none');
        $('#milking1').addClass('d-none');
        $('#milking2').addClass('d-none');
    } else {
        $('#milking1').addClass('d-none');
        $('#milking2').addClass('d-none');
        $('#dry1').addClass('d-none');
        $('#dry2').addClass('d-none');
    }
}

function reproductionView(status) {
    if (status === 'pregnant') {
        $('#pregnancy').removeClass('d-none');
        $('#common_ai_pre').removeClass('d-none');
        $('#ai_no').addClass('d-none');
    } else if (status === 'AI') {
        $('#ai_no').removeClass('d-none');
        $('#common_ai_pre').removeClass('d-none');
        $('#pregnancy').addClass('d-none');
    } else {
        $('#ai_no').addClass('d-none');
        $('#pregnancy').addClass('d-none');
        $('#common_ai_pre').addClass('d-none');
    }
}


function getHerd() {
    alert('ok')
    let str = '';
    let val = $('#organization').val();
    $.ajax({
        type: "GET",
        url: url + "/get-herd-list",
        data: 'organization_id=' + val,
        success: function(res) {
            if (val) {
                $('#herd').prop("disabled", false);
            }
            if (res) {
                $("#herd").empty().html(res);
            } else {
                $("#herd").empty();
            }
        }
    });
}

function getLot() {
    let val = $('#herd').val();
    $.ajax({
        type: "GET",
        url: url + "/get-lot-list",
        data: 'herd_id=' + val,
        success: function(res) {
            if (val) {
                $('#lot').prop("disabled", false);
            }
            if (res) {
                $("#lot").empty().html(res);
            } else {
                $("#lot").empty();
            }
        }
    });
}

//Validation remove
function changeLot() {
    if ($('#lot').val()) {
        $('#error_lot').text('');
    }
}

function changeBreed() {
    if ($('#breed_id').val()) {
        $('#error_breed').text('');
    }
}

function changeTagId() {
    if ($('#tag_id').val()) {
        $('#error_tag').text('');
    }
}

function changeSpecies() {
    if ($('#species').val()) {
        $('#error_species').text('');
    }
}

function changeSex() {
    if ($('#sex').val()) {
        $('#error_sex').text('');
    }
}

function changeBirthDate() {
    if ($('#birth_date').val()) {
        isBirthDate();
    }
}

function isBirthDate() {
    $('#error_birth').text('');
    $('#error_age').text('');
    $('#error_status').text('');
}

function changeAge() {
    if ($('#age').val()) {
        isBirthDate();
    }
}

function changeStatus() {
    if ($('#employeestatus').val()) {
        $('#error_status').text('');
    }
}

function sireChange() {
    if ($('#sire').val()) {
        $('#error_sire').text('');
    }
}

function changeDamId() {
    if ($('#m_id').val()) {
        $('#error_mother').text('');
    }
}

function damInput() {
    if ($('#dam1').val()) {
        $('#error_dam').text('');
    }
}

function changeDateFormat(dateValue) {
    const dateComponents = dateValue.split("-");
    const day = dateComponents[0],
        month = dateComponents[1],
        year = dateComponents[2];
    return `${month}-${day}-${year}`;
}


$(function() {
    $(".birth_date.year").datepicker({
        changeMonth: true,
        changeYear: true,
        showAnim: 'slideDown',
        autoHide: true,
        endDate: "today",
        format: "yyyy",
        viewMode: "years",
        minViewMode: "years"
    })
    $(".birth_date.month").datepicker({
        changeMonth: true,
        changeYear: true,
        showAnim: 'slideDown',
        autoHide: true,
        endDate: "today",
        format: "mm",
        viewMode: "months",
        minViewMode: "months",
    })
    $(".birth_date.date").datepicker({
        changeMonth: true,
        changeYear: true,
        showAnim: 'slideDown',
        autoHide: true,
        endDate: "today",
        format: "dd",
    })

    $('.birth_date').on('change', function() {
        let year = $('.birth_date.year').val() || 0,
            month = $('.birth_date.month').val() || 0,
            day = $('.birth_date.date').val() || 0,
            startDate = changeDateFormat(`${day}-${month}-${year}`);
        if (startDate) {
            isBirthDate();
        }
        let today = new Date().toISOString().slice(0, 10)
        const diffInMs = new Date(today) - new Date(startDate)
        const age = Math.round(diffInMs / (1000 * 60 * 60 * 24));
        $('#age').val(age);
        $('#birth_day_hidden_field').val(`${day}-${month}-${year}`);
    });
    //Age Date Calculate
    $("#age").on("change paste keyup", function() {
        let ageDays = parseInt($(this).val());
        let birthDate = new Date(new Date().getTime() - (ageDays * 24 * 60 * 60 * 1000));
        $('#birth_day_hidden_field').val(birthDate.getDate() + '-' + (birthDate.getMonth() + 1) + '-' + birthDate
            .getFullYear());
        $('.birth_date.year').val(birthDate.getFullYear())
        $('.birth_date.month').val(birthDate.getMonth() + 1)
        $('.birth_date.date').val(birthDate.getDate())
    });

    function getAgeDays(dateVal) {
        let date = changeDateFormat(dateVal),
            birthdayDate = new Date(date),
            todayDate = new Date(),
            diff = new Date(todayDate - birthdayDate),
            day = 1000 * 60 * 60 * 24,
            totalDays = Math.floor(diff / day);
        return Math.floor(totalDays);
    }

    let oned = 24 * 60 * 60 * 1000;
    let ctoday = new Date();
    $("#purchase_date").datepicker({
        autoHide: true,
        endDate: "today",
        format: 'dd-mm-yyyy',
    });
    $("#last_calving_date").datepicker({
        autoHide: true,
        endDate: "today",
        format: 'dd-mm-yyyy',
    }).on('change', function() {
        let startDate = changeDateFormat(this.value);
        let calving_date = new Date(startDate);
        let milk_in_days = Math.ceil((ctoday - calving_date) / oned);
        $('#days_in_milk').val(milk_in_days);
    });
    $("#drying_date").datepicker({
        autoHide: true,
        endDate: "today",
        format: 'dd-mm-yyyy',
    }).on('change', function() {
        let startDate = changeDateFormat(this.value);
        let dry_date = new Date(startDate);
        let d_days = Math.ceil((ctoday - dry_date) / oned);
        $('#days_in_dry').val(d_days);
    });
    $("#ai_date").datepicker({
        autoHide: true,
        endDate: "today",
        format: 'dd-mm-yyyy',
    }).on('change', function() {
        let startDate = changeDateFormat(this.value);
        let ai_date = new Date(startDate);
        let ai_ays = Math.ceil((ctoday - ai_date) / oned);
        $('#ai_days').val(ai_ays);
    });
    $("#pd_check_date").datepicker({
        autoHide: true,
        endDate: "today",
        format: 'dd-mm-yyyy',
    }).on('change', function() {
        let startDate = changeDateFormat(this.value);
        let pd_date = new Date(startDate);
        let pd_days = Math.ceil((ctoday - pd_date) / oned);
        $('#pregnancy_days').val(pd_days);
    });
    $('#source').change(function() {
        let source = $(this).val();
        if (source === 'purchased') {
            $('#p_date').removeClass('d-none');
            $('#purchase_rate').removeClass('d-none');
        } else {
            $('#p_date').addClass('d-none');
            $('#purchase_rate').addClass('d-none');
        }
    });
    $('#sex').change(function() {
        let sex = $(this).val();
        let status = $('#employeestatus').val();
        if (sex === 'male' || status === 'calf' || status === 'heifer') {
            $('.male_selected').prop("disabled", true);
            $('.male_selected2').attr("disabled", true);
            $("#employeestatus option[value='heifer']").hide();
            $("#employeestatus option[value='bull']").show();
            $("#employeestatus option[value='open_unbred']").hide();
            $("#employeestatus option[value='open_bred']").hide();
            $("#employeestatus option[value='pregnant']").hide();
            $("#employeestatus option[value='milking']").hide();
            $("#employeestatus option[value='pregnant_milking']").hide();
            $("#employeestatus option[value='pregnant_dry']").hide();
            $("#employeestatus option[value='dry']").hide();
            $("#employeestatus option[value='reproduction_stage']").show();
        } else {
            $('.male_selected').prop("disabled", false);
            $('.male_selected2').attr("disabled", false);
            $("#employeestatus option[value='bull']").hide();
            $("#employeestatus option[value='heifer']").show();
            $("#employeestatus option[value='reproduction_stage']").hide();
            $("#employeestatus option[value='open_unbred']").show();
            $("#employeestatus option[value='open_bred']").show();
            $("#employeestatus option[value='pregnant']").show();
            $("#employeestatus option[value='milking']").show();
            $("#employeestatus option[value='pregnant_milking']").show();
            $("#employeestatus option[value='pregnant_dry']").show();
            $("#employeestatus option[value='dry']").show();
        }
    });
    $('#employeestatus').change(function() {
        let status = $(this).val();
        let sex = $('#sex').val();
        if (sex === 'male' || status === 'calf' || status === 'bull') {
            $('.male_selected').prop("disabled", true);
            $('.male_selected2').attr("disabled", true);
        } else {
            $('.male_selected').prop("disabled", false);
            $('.male_selected2').attr("disabled", false);
        }
    });
    $("input[name$='sire_source']").click(function() {
        let sire_source = $(this).val();
        if (sire_source === 'purchased') {
            $('#sire_id').removeClass('d-none');
            $('#father_id').addClass('d-none');
        } else {
            $('#father_id').removeClass('d-none');
            $('#sire_id').addClass('d-none');
        }
    });
    $("input[name$='dam_source']").click(function() {
        let dam_source = $(this).val();
        if (dam_source === 'purchased') {
            $('#dam').removeClass('d-none');
            $('#mother_id_block').addClass('d-none');
        } else {
            $('#mother_id_block').removeClass('d-none');
            $('#dam').addClass('d-none');
        }
    });
    $("input[name$='breeding_status']").click(function() {
        let breeding_status = $(this).val();
        breedingStatusView(breeding_status);
    });
    $("input[name$='reproduction_status']").click(function() {
        let reproduction_status = $(this).val();
        reproductionView(reproduction_status);
    });
    $('#days_in_milk').prop("disabled", true);
    $("input[name$='milk']").click(function() {
        let milk = $(this).val();
        if (milk === 'milk_date') {
            $('#days_in_milk').prop("disabled", true);
            $('#last_calving_date').prop("disabled", false);
        } else {
            $('#last_calving_date').prop("disabled", true);
            $('#days_in_milk').prop("disabled", false);
        }
    });
    $('#days_in_dry').prop("disabled", true);
    $("input[name$='dy']").click(function() {
        let dy = $(this).val();
        if (dy === 'dy_date') {
            $('#days_in_dry').prop("disabled", true);
            $('#drying_date').prop("disabled", false);
        } else {
            $('#drying_date').prop("disabled", true);
            $('#days_in_dry').prop("disabled", false);
        }
    });
    $('#ai_days').prop("disabled", true);
    $("input[name$='arti']").click(function() {
        let arti = $(this).val();
        if (arti === 'arti_date') {
            $('#ai_days').prop("disabled", true);
            $('#ai_date').prop("disabled", false);
        } else {
            $('#ai_date').prop("disabled", true);
            $('#ai_days').prop("disabled", false);
        }
    });
    $('#pregnancy_days').prop("disabled", true);
    $("input[name$='preg']").click(function() {
        let preg = $(this).val();
        if (preg === 'preg_date') {
            $('#pregnancy_days').prop("disabled", true);
            $('#pd_check_date').prop("disabled", false);
        } else {
            $('#pd_check_date').prop("disabled", true);
            $('#pregnancy_days').prop("disabled", false);
        }
    });
    //Milking Date Calculate
    $("#days_in_milk").on("change paste keyup", function() {
        let milkDays = $(this).val();
        let calvingDate = new Date(new Date().getTime() - (milkDays * 24 * 60 * 60 * 1000));
        $('#last_calving_date').val(calvingDate.getDate() + '-' + (calvingDate.getMonth() + 1) + '-' +
            calvingDate.getFullYear());
    });
    //Dry Date Calculate
    $("#days_in_dry").on("change paste keyup", function() {
        let dryDays = $(this).val();
        let dryDate = new Date(new Date().getTime() - (dryDays * 24 * 60 * 60 * 1000));
        $('#drying_date').val(dryDate.getDate() + '-' + (dryDate.getMonth() + 1) + '-' + dryDate
            .getFullYear());
    });
    //Pregnant Date Calculate
    $("#pregnancy_days").on("change paste keyup", function() {
        let pdDays = $(this).val();
        let pdDate = new Date(new Date().getTime() - (pdDays * 24 * 60 * 60 * 1000));
        $('#pd_check_date').val(pdDate.getDate() + '-' + (pdDate.getMonth() + 1) + '-' + pdDate
            .getFullYear());
    });
    //AI Date Calculate
    $("#ai_days").on("change paste keyup", function() {
        let aiDays = $(this).val();
        let aiDate = new Date(new Date().getTime() - (aiDays * 24 * 60 * 60 * 1000));
        $('#ai_date').val(aiDate.getDate() + '-' + (aiDate.getMonth() + 1) + '-' + aiDate
            .getFullYear());
    });
});

$('body').on('click', '.previous-tab', function() {
    $('.nav-tabs > .nav-item > .active').parent().prev('li').find('a').tab('show');
});

$('.next-button').click(function() {
    let target = $(this).attr('target'),
        previews, pass = 'not';
    let invalid = false;
    $.each($('.tab-pane'), function() {
        if ($(this).hasClass('active')) {
            previews = $('[data-target="#' + $(this).attr('id') + '"]');
            $.each($(this).find('.requiredField'), function() {
                if ($(this).val() === '' || $(this).val() === undefined || $(this).val() === null) {
                    $(this).addClass('is-invalid');
                    if ($(this).hasClass('select2c')) {
                        $('.select2-container').css({ 'border': '1px solid #dc3545', 'border-radius': '5px' });
                    }
                } else {
                    $(this).removeClass('is-invalid');
                    if ($(this).hasClass('select2c')) {
                        $('.select2-container').css({ 'border': '1px solid #dee2e6', 'border-radius': '5px' });
                    }
                    pass = 'passed';
                }
            })

        }
    })
    if ($('.is-invalid').length < 1) {
        nextTab(target, previews)
    }
});

$('.nav-link').click(function() {
    let target = $(this).attr('data-target'),
        thisButton = $(this),
        previews = $('.nav-item').eq($(this).parent('.nav-item').index() - 1).find('.nav-link');
    let invalid = false;
    if ($(thisButton).attr('next') !== 'passed') {
        if ($(previews).attr('next') !== 'passed') {
            target = $(previews).attr('data-target');
        }
        $.each($('.tab-pane'), function() {
            if ($(this).hasClass('active')) {
                $(thisButton).removeClass('active')
                $('[data-target="#' + $(this).attr('id') + '"]').addClass('active');
                $.each($(this).find('.requiredField'), function() {
                    if ($(this).val() === '' || $(this).val() === undefined || $(this).val() === null) {
                        $(this).addClass('is-invalid');
                        if ($(this).hasClass('select2c')) {
                            $('.select2-container').css('border', '1px solid red');
                        }
                        invalid = true;
                    } else {
                        $(this).removeClass('is-invalid');
                        if ($(this).hasClass('select2c')) {
                            $('.select2-container').css({ 'border': '1px solid #dee2e6', 'border-radius': '5px' });
                        }
                        invalid = false;
                    }
                })
            }
        });
    } else {
        invalid = false;
    }
    if (invalid !== true) {
        nextTab(target, previews)
    }
})
$('.prev-button').click(function() {
    let target = $(this).attr('target');
    nextTab(target)
})

function nextTab(target, previews = null) {
    $(previews).attr('next', 'passed');
    $('.tab-pane').removeClass('active show');
    $(target).addClass('active show');
    $('.nav-link').removeClass('active');
    $('[data-target="' + target + '"]').addClass('active')
}

$('form').submit(function() {
    let submitButton = $(this).find('button[type="submit"], input[type="submit"]');
    $(submitButton).prop('disabled', true).prepend('<div class="spinner-border text-white submit-button-spinner" role="status">\n' +
        '<span class="visually-hidden">Loading...</span>\n' +
        '</div>');
});