<script src="/js/plugins/chosen/chosen.jquery.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>

<script>
    $(document).ready(function () {

        @if ($errors -> count() > 0)
            $("#addDepartmentHardwareMapping").modal({ show: true });
        @endif

        $('.modal').on('show.bs.modal', function (e) {
            $(".alert-danger").hide();
            $(".errorText").hide();
        });

        $('.chosen-select').chosen({ width: "100%" });
        $('.footable').footable();


        /** Modal - department hardware mapping form submit */

        $('#submit').click(function () {
            $('#addDepartmentHardwareMapping .hardwareError #error').html('');
            $('.hardwareError').hide();
            if (!validateAllInputs()) {
                return false;
            }
            $('#add-department-hardware-mapping-form').submit();

        });



        /** filter form submit */
        $(".chosen-select-filter").on('change', function () {
            $('#department-hardware-mapping-filter-form').submit();
        });

        /* Add new hardware mapping to department opens the modal*/

        $('.add-hardware-mapping').click(function () {
            $('#addDepartmentHardwareMapping .hardwareError #error').html('');
            $('.hardwareError').hide();
            $('#department_id_form').val("").trigger("chosen:updated");
            $(".hardware-kit-box").not(':first').remove();
            $("#add-department-hardware-mapping-form :disabled").removeAttr('disabled');

            $(".hardware-kit-box:last").find("select").select2({
                dropdownParent: $('#addDepartmentHardwareMapping')
            }).val('').trigger('change');
            $(".tech-spec-value-field").val('');
            $('#action_type').val('add');

            $(".hardware-kit-box:last .minus-btn").html('<a href="#" class="add-hardwarekit-row-btn" id="add-hardwarekit-row"  title="add another row" onclick="add_hardware_mapping_row(``,``,``)"><i class="icon icon-e-add"></i></a>');

            $('#department-select-container').css('pointer-events', 'auto');
            $("#addDepartmentHardwareMapping").modal({ show: true });
        });

        // Opens modal when edit is clicked

        $(document).on("click", ".edit-hardware-mapping", function () {
            $('#addDepartmentHardwareMapping .hardwareError #error').html('');
            $('.hardwareError').hide();
            $('#department_id_form').val("").trigger("chosen:updated");
            $('#action_type').val('update');
            let departmentId = $(this).data("department-id");
            $('#department_id_form').val(departmentId).trigger("chosen:updated");
            $.ajax({
                type: "GET",
                url: "/hardware-kits-edit-data/" + departmentId,
                success: function (data) {
                    $('.ajax-loader').hide();
                    $("#row-container").html(data.hardWareKits);
                    $(".hardware-kit-box").find("select").select2({
                        dropdownParent: $('#addDepartmentHardwareMapping')
                    });
                    $("#addDepartmentHardwareMapping").modal({ show: true });

                },
            }).fail(function () {
                $('.ajax-loader').hide();
            });

        })

        //Filter form submit function
        $('#department-hardware-mapping-filter-form').submit(function (e) {
            e.preventDefault();
            $('.ajax-loader').show();
            var formData = $(this).serializeArray();

            $.ajax({
                type: "POST",
                url: "/hardware-kits-search",
                data: formData,
                success: function (value) {
                    $('.ajax-loader').hide();
                    $('#department-hardware-mapping-table tbody').html(value.hardwaremapping);
                    $('#hardware-standard-table').Tabledit({
                    }),
                        $('.footable').data('page-size', 50);
                    $('.footable').trigger('footable_initialized');

                },
            }).done(function () {
                $('.ajax-loader').hide();
            });

        });

        $('.tech-spec-dropdown').select2({
            dropdownParent: $('#addDepartmentHardwareMapping')
        });
        $('.make-and-model-dropdown').select2({
            dropdownParent: $('#addDepartmentHardwareMapping')
        });
    });

    $(document).on('change', 'select.make-and-model-dropdown', function (e) {
        var imake_model = $(this);
        if ($(this).val() != '' && $(this).val() != '--Select--' && $(this).val() != '0') {
            try {
                $.ajax({
                    type: "POST",
                    data: { id: $(this).val() },
                    url: "{{route('assets-create.listtechnics')}}",
                    success: function (data) {
                        var tech_spec = imake_model.parents(".hardware-kit-box").find(".tech-spec-dropdown");
                        tech_spec.empty();
                        tech_spec.append($('<option>', {
                            value: 0,
                            text: "--Select--"
                        })).trigger('change');

                        $.each(data, function (key, value) {
                            let cost = 0;
                            if (value.new_value != "") {
                                cost = value.new_value;
                            }
                            tech_spec.append($('<option>', {
                                value: value.id,
                                text: value.details
                            }).attr('data-value', ''));
                        });
                        var attr = imake_model.find(':selected').data('techspec-id');
                        var attr_cost = imake_model.find(':selected').data('cost-value');
                        if (attr != '') {
                            tech_spec.select2().val(attr).trigger('change');
                            imake_model.parents(".hardware-kit-box").find(".tech-spec-value-field").val(attr_cost);
                        }
                    },
                    error: function (value) {

                    }
                });
            } catch (err) {

            }
        }
    });

    $(document).on('change', 'select.tech-spec-dropdown', function (e) {
        var tech_spec_cost = $(this).parents(".hardware-kit-box").find(".tech-spec-value-field");
        if (parseFloat($(this).find(':selected').attr('data-value')) > 0)
            tech_spec_cost.val(parseFloat($(this).find(':selected').attr('data-value')));
        else
            tech_spec_cost.val('');
    });


    /**
     * Checks all fields in the form is filled or not
     * @return [type]
     */
    function validateAllInputs() {
        var errors = 0;
        $('.errorText').text('');
        $(".hardware-kit-box :input").each(function () {
            if (!$(this).val() || $(this).val() == undefined || $(this).val() == null || $(this).val() == '') {
                if ($(this).is('input')) {
                    $(this).parent().parent().find('.errorText').text('Please select a value');
                } else {
                    $(this).parent().find('.errorText').text('Please select a value');
                }
                $('.hardwareError #error').html('You can\'t add more rows without complete existing one');
                $('.hardwareError').show();
                errors++;
            }
        });
        if (!$("#department_id_form").val()) {
            $("#department_id_form").parent().find('.errorText').text('Please select a department');
            errors++;
        }
        if (errors) {
            return false;
        }
        return true;
    }


    /**
     * Adds new row when + button is clicked
     * @param string make_and_model_id
     * @param string tech_spec_id
     * @param int cost
     *
     * @return [type]
     */
    function add_hardware_mapping_row(make_and_model_id = '', tech_spec_id = '', cost = 0) {
        $('.hardwareError #error').html('');
        $('.hardwareError').hide();

        if (!validateAllInputs()) {
            return false;
        }
        var $select = $('select').select2();
        $select.each(function (i, item) {
            $(item).select2("destroy");
        });
        $(".hardware-kit-box:last .minus-btn").html('<a href="#" class="delete-row row-button" title="delete row of asset" ><i class="icon icon-e-delete text-danger "></i></a>');
        $(".hardware-kit-box:last").clone().appendTo("#row-container");

        $(".hardware-kit-box:last .minus-btn").html('<a href="#" class="delete-row row-button" title="add another row of asset" ><i class="icon icon-e-delete text-danger "></i></a><a class="add-hardwarekit-row-btn" href="#" id="add-hardwarekit-row"  title="add another row" onclick="add_hardware_mapping_row(``,``,``)"><i class="icon icon-e-add"></i></a>');
        $(".hardware-kit-box").find("select").select2({
            dropdownParent: $('#addDepartmentHardwareMapping')
        });
        $(".hardware-kit-box:last").find("select").select2({
            dropdownParent: $('#addDepartmentHardwareMapping')
        }).val('').trigger('change');

    }

    // Removes the current  - buton clicked row
    $(document).on('click', '.delete-row', function (e) {
        $('#addDepartmentHardwareMapping .hardwareError #error').html('');
        $('.hardwareError').hide();
        $(this).parents(".hardware-kit-box").remove();

        if ($('.hardware-kit-box').length == 1) {
            $(".hardware-kit-box:last .minus-btn").html('<a href="#" id="add-hardwarekit-row"  title="add another row" onclick="add_hardware_mapping_row(``,``,``)"><i class="icon icon-e-add"></i></a>');
        }
    });
</script>