/******************************************************************************
 *   ______                                                                   *
 *  /       \                                                                 *
 * /$$$$$$  | ________  __    __   ______    ______                           *
 * $$ |__$$ |/        |/  |  /  | /      \  /      \                          *
 * $$    $$ |$$$$$$$$/ $$ |  $$ |/$$$$$$  |/$$$$$$  |                         *
 * $$$$$$$$ |  /  $$/  $$ |  $$ |$$ |  $$/ $$    $$ |                         *
 * $$ |  $$ | /$$$$/__ $$ \__$$ |$$ |      $$$$$$$$/                          *
 * $$ |  $$ |/$$      |$$    $$/ $$ |      $$       |                         *
 * $$/   $$/ $$$$$$$$/  $$$$$$/  $$/        $$$$$$$/                          *
 *                                                                            *
 * @PROJECT    : 3D Preview Extension [Magetop.com]                           *
 * @AUTHOR     : Azure - Developer                                            *
 * @COPYRIGHT  : © 2019  Magetop.com                                          *
 * @LINK       : https://Magetop.com                                          *
 * @CREATED    :  10/01/2022                                                  *
 ******************************************************************************/

define([
    'jquery',
    'Magento_Ui/js/modal/confirm',
    'Magento_Ui/js/modal/modal',
    'Magento_Ui/js/modal/alert',
    'mgt_advance_preview_helper',
],function ($,confirmation,modal,alert,helper) {
    var productPreview = {};
    productPreview = {
        version : '2.5.6',
        tier_prices: [],
        extra_price: '',
        customer_group: 0,
        is_3d: false,
        custom_discount_url: '',
        custom_tierprice_url: '',
        add_wishlist_url: '',
        tier_first_min_qty: 0,
        tier_first_max_qty: 0,
        is_limit_qty: false,
        media_url: '',
        product_id: 0,
        item_id: 0,
        generate_project_name: '',
        login_url: '',
        is_offer: false,
        preview_option_url: '',
        is_added_offer: false,
        cur_qty: 0,
        cur_project_name: '',
        is_upload_design_item: 0,
        initData : function () {
            var self = this;
            // self.media_url = $('#txt-opd-media-url').val();
            var tierPrice = $('#txt-tier-prices').val();
            if(tierPrice) {
                self.tier_prices = JSON.parse(tierPrice);
                // console.log(self.tier_prices);
            }
            var extraPriceUrl = $('#txt-preview-url-extra-price').val();
            self.extra_price = extraPriceUrl;
            var customerGroup = $('#txt-customer-group').val();
            self.customer_group = parseInt(customerGroup);
            var is3D = parseInt($('#txt-is-3d').val());
            self.is_3d = is3D === 1 ? true : false;
            if(self.is_3d) {
                $('.gallery-placeholder').css('display','none');
            }
            // console.log(self.customer_group);

            self.custom_discount_url = $('#txt-custom-discount-url').val();
            self.custom_tierprice_url = $('#txt-custom-tierprice-url').val();
            self.add_wishlist_url = $('#txt-custom-add-wishlist-url').val();
            self.tier_first_min_qty = parseInt($('#txt-tier-fist-min-qty').val());
            self.tier_first_max_qty = parseInt($('#txt-tier-fist-max-qty').val());
            self.media_url = $('#txt-custom-media-url').val();
            self.product_id = parseInt($('#txt-model-product-id').val());
            self.generate_project_name = $('#txt-custom-gengerate-id').val();
            var itemId = $('#txt-preview-item-id').val();
            itemId = parseInt(itemId);
            self.item_id = itemId;
            self.login_url = $('#txt-custom-redirect-login-url').val();
            var tmpOffer = $('#txt-is-offer').val();
            if(tmpOffer === '1') {
                self.is_offer = true;
            }
            self.preview_option_url = $('#txt-preview-option-url').val();
            var isUpdateDesign =  $('#txt-re-update-design-item').val();
            self.is_upload_design_item = parseInt(isUpdateDesign);
        },
        showTierPriceByQty : function(qty) {
            var self = this;
            var tierPrices = self.tier_prices;
            var activeId = 0;
            if(tierPrices !== undefined && tierPrices.length && tierPrices.length > 0) {
                let lastItem = tierPrices[tierPrices.length - 1];
                if(qty >= lastItem.price_qty) {
                    activeId = parseInt(lastItem.price_qty);
                }
                else {
                    for(var i = 0; i < tierPrices.length; i++) {
                        if(i + 1 < tierPrices.length) {
                            var currentTeir = tierPrices[i];
                            var nextTier = tierPrices[i + 1];
                            // console.log(currentTeir, i);
                            var currentTierQty = parseInt(currentTeir.price_qty);
                            var nextTierQty = parseInt(nextTier.price_qty);
                            if(qty >= currentTierQty && qty < nextTierQty) {
                                activeId = currentTierQty;
                            }
                        }
                    }
                }
                $('.custom-tier-price-item').removeClass('custom-tier-price-item-active');
                if(activeId > 0 ) {

                    $('#custom-tier-price-item-'+activeId).addClass('custom-tier-price-item-active');
                }

            }
            // console.log(activeId);
        },
        getExtraPrice : function() {
            var self = this;
            var url = self.extra_price;
            let data = $('#product_addtocart_form').serialize();
            helper.doRequest(url,data,'','',function (response) {
                // console.log(response);
                if(response.status === 'success') {
                    $('#preview-total-price-value').html(response.final_price);
                    $('#txt-project-final-price').val(response.real_price);
                }
            })
        },
        getPreviewOptions : function(previewId) {
            console.log("Get Preview option", previewId);
            var self = this;
            var url = self.preview_option_url;
            let data = {
                preview_id: previewId,
            };
            helper.doRequest(url,data,'','',function (response) {
                console.log(response);
                if(response.status === 'success') {
                    $('#preview-custom-option-values').html(response.html);
                }
            })
        },

        download : function (source){
            console.log(source);
            const fileName = source.split('/').pop();
            var el = document.createElement("a");
            el.setAttribute("href", source);
            el.setAttribute("download", fileName);
            document.body.appendChild(el);
            el.click();
            el.remove();
        },
        updateCustomDiscount : function() {
            // change discount price
            // qty = parseInt(qty);
            var self = this;
            var url = self.custom_discount_url;
            let data = $('#product_addtocart_form').serialize();
            helper.doRequest(url,data,'advance-preview-loading','',function (response) {
                // console.log(response);
                if(response.status === 'success') {
                    $('#mgt-project-discount-options').html(response.html);
                    setTimeout(function () {
                        self.getExtraPrice();
                    },200);
                }
            })
        },
        getCustomTierPrice : function() {
            // change discount price
            // qty = parseInt(qty);
            var self = this;
            var url = self.custom_tierprice_url;
            let data = $('#product_addtocart_form').serialize();
            var qty = $('#mgt-custom-qty').val();
            $('#qty').val(qty);
            helper.doRequest(url,data,'advance-preview-loading','',function (response) {
                // console.log(response);
                if(response.status === 'success') {
                    $('#custom-tier-prices-content').html(response.html);
                    if(self.is_offer) {
                        $('#mgt-custom-qty').prop('disabled',true);
                    }
                }
            })
        },
        setLimitQty : function(isCheck) {
            var self = this;
            var currentQty = $('#mgt-custom-qty').val();
            currentQty = parseInt(currentQty);
            console.log(isCheck, self.customer_group );
            if(isCheck) {
                self.is_limit_qty = true;
                if(currentQty > self.tier_first_max_qty || currentQty < self.tier_first_min_qty) {
                    $('#mgt-custom-qty').val(self.tier_first_min_qty);
                }
                if(self.customer_group > 0) {
                    $('#product-preview-request-offer').prop('disabled',true);
                }


            }
            else {
                self.is_limit_qty = false;
                if(self.customer_group > 0 && !self.is_offer) {
                    $('#product-preview-request-offer').prop('disabled',false);
                }
            }

        },
        addProductToWishList: function() {
            var self = this;
            var url = self.add_wishlist_url;
            var pId = $('input[name="product"]').val();
            /*let data = {
                product_id: pId
            }*/
            var data = $('#product_addtocart_form').serialize();
            helper.doRequest(url,data,'advance-preview-loading','',function (response) {
                 console.log(response);
                self.is_added_offer = true;
                $('#mgt-custom-project-name').val('');
                $('#txt-project-generate').val(0);
                if(response.status === 'success') {
                    alert({
                        title: 'Success',
                        content: response.message,
                    })
                    window.location.href = response.export_url;
                }
                else {
                    alert({
                        title: 'Error',
                        content: response.message,
                    })
                }
                $('#preivew-product-addtocart-button').prop('disabled',true);
            })
        },
        validatePorjectName: function() {
            var self = this;
          var porjectName = $('#mgt-custom-project-name').val();
            porjectName = $.trim(porjectName);
            console.log("Project name ", porjectName);
            if(porjectName === '') {
                $('#preivew-product-addtocart-button').prop('disabled',true);
                $('#product-preview-request-offer').prop('disabled',true);
                console.log('1');
            }
            else {
                var qty = $('#mgt-custom-qty').val();
                qty = parseInt(qty);
                if(!self.is_added_offer) {
                    self.cur_qty = qty;
                    self.cur_project_name = porjectName;
                    $('#preivew-product-addtocart-button').prop('disabled',false);
                    if(qty > 3 && !self.is_offer) {
                        $('#product-preview-request-offer').prop('disabled',false);
                    }
                }
                else {
                    if(qty !== self.cur_qty && porjectName !== self.cur_project_name) {
                        $('#preivew-product-addtocart-button').prop('disabled',false);
                        self.is_added_offer = false;
                        self.cur_qty = qty;
                        self.cur_project_name = porjectName;
                        if(qty > 3 && !self.is_offer) {
                            $('#product-preview-request-offer').prop('disabled',false);
                        }
                    }
                }

                console.log('2');
            }
        },
        generateNewestProjectName : function(type) {
            // change discount price
            // qty = parseInt(qty);
            var self = this;
            var url = self.generate_project_name;
            let data = $('#product_addtocart_form').serialize();
            var qty = $('#mgt-custom-qty').val();
            $('#qty').val(qty);
            var loginUrl = self.login_url;
            helper.doRequest(url,data,'advance-preview-loading','',function (response) {
                 console.log(response);
                 if(response.is_login !== 'yes') {
                     confirmation({
                         title: $.mage.__('Please Login or Register'),
                         content: $.mage.__('Before adding product to the cart.'),
                         actions: {
                             confirm: function(){
                                 window.location.href = loginUrl;
                             },
                             cancel: function(){},
                             always: function(){
                                 window.location.href = loginUrl;
                             }
                         }
                     })
                 }
                 else {
                     if(response.project_id && response.project_id !== undefined) {
                         console.log("OK rui, add product thui ", type);
                         $('#txt-project-generate').val(response.project_id);
                         setTimeout(function () {
                             if(type === 1) {
                                 $('#product-addtocart-button').click();
                             }
                             else {
                                 self.addProductToWishList();
                             }

                         },100)
                     }
                 }


            })
        },
        init : function () {
            var self = this;
            self.initData();
            // console.log("PRODUCT REVIEW");
            $('#mgt-custom-qty').change(function () {
                var qty = $(this).val();
                qty = parseInt(qty);
               /* if(self.is_limit_qty) {
                    if(qty > self.tier_first_max_qty || qty < self.tier_first_min_qty) {
                        qty = self.tier_first_min_qty;
                    }
                    $(this).val(qty);
                }*/
                var projectName = $('#mgt-custom-project-name').val();
                if(!self.is_added_offer) {
                    self.cur_qty = qty;
                    self.cur_project_name = projectName;
                    if(qty < 4) {
                        $('#txt-is-request-sample').prop('checked',true);
                        $('#product-preview-request-offer').prop('disabled',true);
                    }
                    else {
                        $('#txt-is-request-sample').prop('checked',false);

                        if($.trim(projectName) !== '' && !self.is_offer) {
                            $('#product-preview-request-offer').prop('disabled',false);
                        }
                    }
                    if(projectName !== '') {
                        $('#preivew-product-addtocart-button').prop('disabled',false);
                        $('#preivew-product-addtocart-button').prop('disabled',false);
                    }
                    else {
                        $('#product-updatecart-button').prop('disabled',true);
                        $('#preivew-product-addtocart-button').prop('disabled',true);
                    }

                }
                else {
                    if(self.cur_qty !== qty && projectName !== self.cur_project_name && projectName !== '') {
                        self.is_added_offer = false;
                        self.cur_qty = qty;
                        self.cur_project_name = projectName;
                        if(qty < 4) {
                            $('#txt-is-request-sample').prop('checked',true);
                            $('#product-preview-request-offer').prop('disabled',true);
                        }
                        else {
                            $('#txt-is-request-sample').prop('checked',false);

                            if($.trim(projectName) !== '' && !self.is_offer) {
                                $('#product-preview-request-offer').prop('disabled',false);
                            }
                        }
                        $('#product-updatecart-button').prop('disabled',false);
                        $('#preivew-product-addtocart-button').prop('disabled',false);
                    }
                }
                // $('#qty').val(qty);
                // self.showTierPriceByQty(qty);
                self.getCustomTierPrice();
                self.updateCustomDiscount();
                setTimeout(function () {
                    self.getExtraPrice();
                },100);
            })
            $('.mgt-custom-preview-information-tab a').click(function (e) {
                var tab = $(this).attr('tab');
                $('.mgt-custom-preview-information-tab').removeClass('mgt-custom-preview-information-tab-active');
                $(this).parent('li').addClass('mgt-custom-preview-information-tab-active');
                $('.mgt-custom-preview-information-content-tab').hide();
                $('#mgt-custom-preview-information-content-'+tab).show();
                // console.log('#mgt-custom-preview-information-content-'+tab);
                e.preventDefault();
            });
            $('input.txt-preview-extra-option').click(function () {

                // self.getExtraPrice();
                var isShowDesignSericeNote = false;
                var isDesignService = $(this).attr('is-desing-service');
                if(isDesignService === '1') {
                    if($(this).is(":checked")) {
                        $('#txt-preview-is-design-service').val(1);
                        isShowDesignSericeNote = true;
                    }
                    else {
                        $('#txt-preview-is-design-service').val(0);
                    }
					if(isShowDesignSericeNote) {
                         $('#txt-design-service-note').css('display','block');
						// $('.yourdesign-upload-btn-wrapper').css('display','none');
						// $('#form-upload-custom-design button').prop('disabled',true);
						// $('#txt-preview-upload-custom-design').prop('disabled',true);
					}
					else {
                        $('#txt-design-service-note').css('display','none');
						// $('.yourdesign-upload-btn-wrapper').css('display','block');
						// $('#form-upload-custom-design button').prop('disabled',false);
						// $('#txt-preview-upload-custom-design').prop('disabled',false);
					}
                }

                self.updateCustomDiscount();

            })
            $('#btn-prview-standrad-design').click(function () {
                // console.log("standrad Design")
                // $('#preview-project-extra-options').css('display','none');
                $('#txt-preview-type').val(1);
                $('#preview-project-extra-options').hide();
                // $('.mgt-project-price-option-col-percent').hide();
                $('.mgt-project-preview-action-middle').hide();
                $('.mgt-project-preview-action-right').hide();
                $('#preview-standard-list-designs').show();
                $('#txt-custom-preview-design-type').val(0);
                setTimeout(function () {
                    // self.getExtraPrice();
                    self.updateCustomDiscount();
                },100)

            })
            $('#btn-prview-own-design').click(function () {
                // $('#preview-project-extra-options').css('display','block');
                $('#preview-project-extra-options').show();
                // $('#mgt-project-discount-options').hide('display','none');
                if(self.customer_group > 1) {
                    // $('.mgt-project-price-option-col-percent').show();
                }
                $('.mgt-project-preview-action-middle').show();
                $('.mgt-project-preview-action-right').show();
                $('#txt-preview-type').val(2);
                $('#preview-standard-list-designs').hide();
                $('#txt-custom-preview-design-type').val(1);
                var previewId = $('#txt-default-preview-id').val();
                setTimeout(function () {
                    // self.getExtraPrice();
                    self.updateCustomDiscount();
                    // self.getPreviewOptions(previewId);


                },100)


            })
          /*  $('.mgt-project-preview-action-middle-one-icon').click(function (e) {
                console.log("CLCIk")
                e.preventDefault();
                // window.location.href = 'http://myfitmixdemo.com/media/advancepreview/textures/Barra_baseColor.png';
                self.download('http://myfitmixdemo.com/media/advancepreview/textures/Barra_baseColor.png')
            })*/

            $('#txt-is-request-sample').click(function () {
               /* var isCheck = false;
                var qty = $('#mgt-custom-qty').val();
                qty = parseInt(qty);
                if(qty > 3 && $(this).is(":checked")) {
                    if(qty > 3) {
                        $('#mgt-custom-qty').val(1);
                        $('#product-preview-request-offer').prop('disabled',true);
                    }
                    self.getCustomTierPrice();
                    self.updateCustomDiscount();
                    setTimeout(function () {
                        self.getExtraPrice();
                    },100);
                }
                else if(qty <= 3) {
                    isCheck = true;
                    $('#txt-is-request-sample').prop('checked',true);
                }
                else {
                    if(porjectName === '') {
                        $('#product-preview-request-offer').prop('disabled',true);
                    }
                    else if(!self.is_offer){
                        $('#product-preview-request-offer').prop('disabled',false);
                    }
                }*/
                if($(this).is(":checked")) {
                    $('#mgt-custom-qty').val(1);
                    $('#product-preview-request-offer').prop('disabled',true);
                }
                else {
                    var porjectName = $('#mgt-custom-project-name').val();
                    $('#mgt-custom-qty').val(4);
                    if(porjectName === '') {
                        $('#product-preview-request-offer').prop('disabled',true);
                    }
                    else if(!self.is_offer){
                        $('#product-preview-request-offer').prop('disabled',false);
                    }
                }
                self.getCustomTierPrice();
                self.updateCustomDiscount();
                setTimeout(function () {
                    self.getExtraPrice();
                },100);
                // self.setLimitQty(isCheck);

            })
            $('#btn-own-design-pdf-download').click(function () {
                // var url = self.media_url + 'advancepreview/custom_previews/product_id_'+self.product_id+'/own_pdf/own_design.pdf';
                if(self.is_3d) {
                    var url = $('#txt-preview-sample-pdf-file').val();
                    if(url.trim() !== '') {
                        self.download(url);
                    }
                    else {
                        alert({
                            title: 'Error',
                            content: 'Sample file not found, Please try again or contact admin'
                        })
                    }
                }

            })
            $('#btn-own-design-ai-download').click(function () {
                // var url = self.media_url + 'advancepreview/custom_previews/product_id_'+self.product_id+'/own_pdf/own_design.pdf';
                if(self.is_3d) {
                    var url = $('#txt-preview-sample-ai-file').val();
                    if(url.trim() !== '') {
                        self.download(url);
                    }
                    else {
                        alert({
                            title: 'Error',
                            content: 'Sample file not found, Please try again or contact admin'
                        })
                    }
                }

            })
            $('#product-preview-request-offer').click(function () {
                 // $('.towishlist').click();
                if(self.customer_group > 0) {
                    // if($(this).attr('is-disable'))
                   /*  let isDisable = $(this).attr('is-disable');
                    if(isDisable === '1') {
                        console.log('Is diable rtui');
                    }
                    else {
                        $('#product-addtocart-button').prop('disabled',true);
                        // $('#product-preview-request-offer').prop('disabled',true);
                        $(this).attr('is-disable','1');
                        $(this).css('opacity','0.5');
                        self.generateNewestProjectName(2);

                    } */
					// $('#product-addtocart-button').prop('disabled',true);
					$('#product-preview-request-offer').prop('disabled',true);
					// $(this).attr('is-disable','1');
					// $(this).css('opacity','0.5');
					self.generateNewestProjectName(2);

                }
                else {
                    alert({
                        title: 'Please Login or Register',
                        content: 'Before add a product to REQUEST FOR OFFER'
                    })
                }

            })
            $('#mgt-custom-project-name').change(function () {
                var porjectName = $('#mgt-custom-project-name').val();
                porjectName = $.trim(porjectName);
                console.log("Project name ", porjectName);
                if(porjectName === '') {
                     $('#preivew-product-addtocart-button').prop('disabled',true);
                     $('#product-preview-request-offer').prop('disabled',true);
                     $('#product-updatecart-button').prop('disabled',true);
                     console.log('1');
                }
                else {
                    var qty = $('#mgt-custom-qty').val();
                    qty = parseInt(qty);
                    if(!self.is_added_offer) {
                        self.cur_qty = qty;
                        self.cur_project_name = porjectName;
                        $('#preivew-product-addtocart-button').prop('disabled',false);
                        $('#product-updatecart-button').prop('disabled',false);
                        if(qty > 3 && !self.is_offer) {
                            $('#product-preview-request-offer').prop('disabled',false);
                        }
                    }
                    else {
                        if(porjectName !== self.cur_project_name) { // remove conditon qty !== self.cur_qty &&
                            self.is_added_offer = false;
                            self.cur_qty = qty;
                            self.cur_project_name = porjectName;
                            $('#preivew-product-addtocart-button').prop('disabled',false);
                            $('#product-updatecart-button').prop('disabled',false);
                            if(qty > 3 && !self.is_offer) {
                                $('#product-preview-request-offer').prop('disabled',false);
                            }
                        }
                    }
                    console.log('3');
                }

            })
            $('#preivew-product-addtocart-button').click(function () {
                var projectName = $('#txt-project-generate').val();
                self.generateNewestProjectName(1);

            })
            $('#txt-daily-shipping').change(function () {
                console.log("can vl");
                self.getCustomTierPrice();
                self.updateCustomDiscount();
                setTimeout(function () {
                    self.getExtraPrice();
                },100);
            })
           /* $('.img-preview-standard-model-item').click(function () {
                var previewId = $(this).attr('preview-id');
                self.getPreviewOptions(previewId);
            })*/


            helper.showLoading();
            setTimeout(function () {
                console.log("set Time out");

                 self.validatePorjectName();
                self.getCustomTierPrice();
                self.updateCustomDiscount();
                var designType = $('#txt-custom-preview-design-type').val();
                helper.hideLoading();
                if(self.item_id > 0 && designType === '1') {
                    $('#btn-prview-own-design').click();
                }
                var defaultQty = $('#mgt-custom-qty').val();
                console.log(defaultQty);
                $('#qty').val(defaultQty);
                 // $('.minicart-wrapper .total-mini-cart-price .price').html('19000');
              /*  var defaultPreviewId = $('#txt-default-preview-id').val();
                self.getPreviewOptions(defaultPreviewId);*/
				var curProjectName = $('#mgt-custom-project-name').val();
				if($.trim(curProjectName) === '') {
					  $('#preivew-product-addtocart-button').prop('disabled',true);
                     $('#product-preview-request-offer').prop('disabled',true);
                     $('#product-updatecart-button').prop('disabled',true);
				}
				else {
					$('#preivew-product-addtocart-button').prop('disabled',false);
                    $('#product-updatecart-button').prop('disabled',false);
                    var qty = $('#mgt-custom-qty').val();
                    qty = parseInt(qty);
                    if(qty > 3 && !self.is_offer) {
                        $('#product-preview-request-offer').prop('disabled',false);
                    }
				}
				if(self.is_upload_design_item > 0) {
				    console.log('UPlaod Design ', self.is_upload_design_item);
				    $('.box-tocart').css('display','none');
                }
            },1000);
            $('#mgt-custom-qty, #mgt-custom-project-name').keypress(
                function(event){
                    if (event.which == '13') {
                        event.preventDefault();
                    }
                });
            // $('[data-toggle="preview-tooltip"]').tooltip();
            /*$('.minicart-wrapper .showcart').click(function () {
                console.log("testsete");
                // $('#minicart-content-wrapper .block-content .price-wrapper .price').html('9000')
            })*/
        }
    }
    return productPreview;
})
