(function ($) {
    "use strict";


    let lang = window._locale;
    let baseURL = $("#url").val();

    function setSoftFileInput() {
        let product_type = $('input[name="productType"]:checked').val();
        let virtualProducts = $('.virtualProduct');
        let physicalProduct = $('.physicalProduct');
        if (product_type == '1') {
            physicalProduct.fadeOut();
            virtualProducts.fadeIn();
        } else {
            physicalProduct.fadeIn();
            virtualProducts.fadeOut();
        }
    }

    function setProductOption() {
        let product_type = $('input[name="productOption"]:checked').val();
        let singleProduct = $('.singleProduct');
        let variantProduct = $('.variantProduct');
        if (product_type != '1') {
            singleProduct.fadeIn();
            variantProduct.fadeOut();
        } else {
            singleProduct.fadeOut();
            variantProduct.fadeIn();
        }
    }

    function getAttributeData(a_id) {

        $.ajax({
            type: "GET",
            data: {
                id: a_id,
            },
            dataType: "json",
            url: baseURL + "/" + "store/product/getAttributeValues",
            success: function (data) {

                let model = $("#choice_options");

                model.empty();
                model.append(new Option('Select One', ''));

                for (var i = 0; i < data.length; i++) {
                    model.append(new Option(data[i].value, data[i].id));
                }
                model.niceSelect('update');


            },
            error: function (data) {
            },
        });
    }


    function hideShowStockManage() {
        if ($('#isStockManaged').is(':checked')) {
            $('.hasStockManage').fadeIn();

        } else {
            $('.hasStockManage').fadeOut();
        }
    }

    function checkIsFreeStatus() {
        if ($('#is_free').is(':checked')) {
            $('.must_price').addClass('d-none');
        } else {
            $('.must_price').removeClass('d-none');
        }
    }

    function showAttributeValue() {
        $('.selectAttribute').each(function () {
            let id = $(this).val();
            if ($(this).is(':checked')) {
                $('#attributeValueDiv' + id).removeClass('d-none');
            } else {
                $('#attributeValueDiv' + id).addClass('d-none');
            }
        });
    }


    function applySKUCombination() {
        let product_id = $('.product_id').val()
        let stock_manage = $('#stock_quantity').is(':checked') ? 1 : 0;
        let selectAttribute = $('.selectAttribute:checked').map(function () {
            return $(this).val();
        }).get();

        let selectAttributeValue = [];
        $('.selectAttribute').each(function () {
            let id = $(this).val();
            if ($(this).is(':checked')) {
                selectAttributeValue['attribute_values_' + id] = $('#attributeValueDiv' + id).find('.selectAttributeValue:checked').map(function () {
                    return $(this).val();
                }).get();
            }
        });


        let data = {
            'product_id': product_id,
            "stock_manage": stock_manage,
            "attributes": selectAttribute,
            ...selectAttributeValue
        };


        $.ajax({
            type: "GET",
            data: data,
            dataType: "html",
            url: baseURL + "/" + "store/product/sku_combination",
            success: function (data) {
                $('#valueTable').html(data);
                hideShowStockManage();
                checkIsFreeStatus();
            },
            error: function (request, status, error) {
                toastr.error('Something Went Wrong', 'Error');

            }
        });

    }


    $(document).ready(function () {

        setSoftFileInput();
        setProductOption();
        checkIsFreeStatus()
        hideShowStockManage();
        showAttributeValue();
        applySKUCombination();

        $(document).on('change', '.selectAttribute', function () {
            showAttributeValue();
        });
        $(document).on('change', '.selectProductType', function () {
            setSoftFileInput();
        });

        $(document).on('change', '.selectProductOption', function () {
            setProductOption();
        });

        $(document).on('change', '#is_free', function () {
            checkIsFreeStatus();
        });

        $(document).on('change', '#isStockManaged', function () {
            hideShowStockManage();
        });

        $(document).on('click', '.remove_variant_whole_sale', function () {
            $(this).parents('.variant_whole_sale_price_list').remove();
        });


        $(document).on('change', '.sku_combination', function () {
            applySKUCombination();
        });

        $(document).on('change', '#category_id', function () {

            $.ajax({
                type: "GET",
                data: {
                    id: $(this).val(),
                },
                dataType: "json",
                url: baseURL + "/" + "store/product/ajaxGetProductSubCategory",
                success: function (data) {

                    let model = $("#subcategory_id");
                    model.empty();
                    for (var i = 0; i < data.length; i++) {
                        model.append(new Option(data[i].title.en, data[i].id));
                    }

                    model.niceSelect('update');
                },
                error: function (data) {
                },
            });
        });


        $(document).on('change', '#choice_attributes', function () {
            let a_id = $(this).val();
            let exsist = $('#attribute_id_' + a_id).length;
            if (exsist > 0) {
                toastr.error("{{__('marketing.this_item_already_added_to_list')}}");
                $('.preloader').addClass('d-none');
                $('#choice_attributes').val('');
                $('#choice_attributes').niceSelect('update');
                return false;
            }
            getAttributeData(a_id);

        });


        $(document).on('change', '#choice_options', function () {

            let id = $(this).val();
            $(this).niceSelect('reset');

            if (id == '') {
                toastr.info("Select a attribute Value");
                return false;
            }
            let isDuplicate = false;
            $('.attributeValueId').each(function () {
                if (id === $(this).val()) {
                    isDuplicate = true;
                    return false;
                }
            });

            if (isDuplicate) {
                toastr.warning("Already exist in list");
                return false;
            }

            let name = $('#choice_options :selected').text();

            let model = $("#valueTable");


            model.append(`<div class="col-lg-12 variant_whole_sale_price_list">
    <div class="row mt-2 mb_30">

        <input type="hidden" class="attributeValueId" name="attributeValueId[]"  value="${id}">

        <div class="col">
            <input type="text" class="form-control primary_input_field" placeholder="Attribute Value" readonly name="attributeValue" value="${name}">
        </div>

        <div class="col must_price">
            <input type="text" class="form-control primary_input_field" placeholder="Price" name="Value_price[]">
        </div>

        <div class="col">
            <button type="button" class="mt-3 style_plus_icon remove_variant_whole_sale border-0">
                <i class="ti-trash"></i>
            </button>
        </div>
    </div>
</div>`);
            hideShowStockManage();

        });


    });

})(jQuery);


