/******************************************************************************
 *   ______                                                                   *
 *  /       \                                                                 *
 * /$$$$$$  | ________  __    __   ______    ______                           *
 * $$ |__$$ |/        |/  |  /  | /      \  /      \                          *
 * $$    $$ |$$$$$$$$/ $$ |  $$ |/$$$$$$  |/$$$$$$  |                         *
 * $$$$$$$$ |  /  $$/  $$ |  $$ |$$ |  $$/ $$    $$ |                         *
 * $$ |  $$ | /$$$$/__ $$ \__$$ |$$ |      $$$$$$$$/                          *
 * $$ |  $$ |/$$      |$$    $$/ $$ |      $$       |                         *
 * $$/   $$/ $$$$$$$$/  $$$$$$/  $$/        $$$$$$$/                          *
 *                                                                            *
 * @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,
        upload_custom_url: '',
        custom_discount_url: '',
        custom_tierprice_url: '',
        tier_first_min_qty: 0,
        tier_first_max_qty: 0,
        is_limit_qty: false,
        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.upload_custom_url = $('#txt-upload-custom-url').val();
            self.custom_discount_url = $('#txt-custom-discount-url').val();
            self.custom_tierprice_url = $('#txt-custom-tierprice-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());
        },
        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);
                }
            })
        },
        uploadImage : function() {
            var self = this;
            var data = new FormData($('#form-upload-custom-design')[0]);
            var url = self.upload_custom_url;
            helper.uploadImages(url, data, 'advance-preview-loading', '', function (response) {
                // console.log(response)
                // window.location.reload();
                window.location.href=window.location.href
            })
        },
        download : function (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();
            helper.doRequest(url,data,'advance-preview-loading','',function (response) {
                // console.log(response);
                if(response.status === 'success') {
                    $('#custom-tier-prices-content').html(response.html);
                }
            })
        },
        setLimitQty : function(isCheck) {
            var self = this;
            var currentQty = $('#mgt-custom-qty').val();
            currentQty = parseInt(currentQty);
            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) {
                    $('#product-preview-request-offer').prop('disabled',false);
                }
            }

        },
        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);
                }
                $('#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();
                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);
                setTimeout(function () {
                    // self.getExtraPrice();
                    self.updateCustomDiscount();
                },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-preview-upload-custom-design').change(function () {
                console.log("Upload Image choi")
                self.uploadImage();
            })
            $('#txt-is-request-sample').click(function () {
                var isCheck = false;
                if($(this).is(":checked")) {
                    isCheck = true;
                }
                self.setLimitQty(isCheck);
            })
            setTimeout(function () {
                console.log("set Time out");

                self.getCustomTierPrice();
                self.updateCustomDiscount();
            },100);
            // $('[data-toggle="preview-tooltip"]').tooltip();
        }
    }
    return productPreview;
})
