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

define([
    'jquery',
    'mage/translate',
    'mage/validation',
    'Magento_Ui/js/modal/confirm',
    'Magento_Ui/js/modal/modal',
    'Magento_Ui/js/modal/alert',
    'mgt_advance_preview_helper',
    'product_preview_pro'
],function ($,$t,validate,confirmation,modal,alert,helper,productPreviewPro) {
    var previewCustomOrder = {};
    previewCustomOrder = {
        version: '2.0.0',
        update_status_url: '',
        update_custom_print_status_url: '',
        order_detail_url: '',
        customer_email: '',
        customer_name: '',
        customer_id: 0,
        upload_proof_url: '',
        tracking_items_url: '',
        tracking_edit_url: '',
        tracking_save_url: '',
        tracking_delete_url: '',
        update_paid_status: '',
        iframe_url: '',
        updateItemStatus : function(itemId, status,productName,txtOrder) {
            var self = this;
            var url = self.update_status_url;
            var loading = 'advance-preview-loading';
            var tracking = '';
            if(status === 'shipped') {
                tracking = $('#txt-tracking-item-'+itemId).val();
            }
            var elemtItemId = '#btn-update-standard-status-'+itemId;
            var orderId = $(elemtItemId).attr('order-id');


            var data = {
                item_id: itemId,
                status: status,
                customer_name: self.customer_name,
                customer_email: self.customer_email,
                product_name: productName,
                tracking_info: tracking,
                txt_order: txtOrder,
                customer_id: self.customer_id,
                order_id: orderId
            };
            if(status === 'delivered') {

                var total = $(elemtItemId).attr('order-id');
                var qty = $(elemtItemId).attr('qty');
                // data.order_id = orderId;
                qty.qty = qty;
                data.total = total;
            }
            console.log(data);
            // $('#product-custom-order-message').css('display','none');
            helper.doRequest(url,data,loading,'',function (response) {
                if(response.status === 'success') {
                    // $('#preview-project-item-status-' + itemId).html(response.item_status);
                    window.location.href = self.order_detail_url
                }
            })
        },
        updateCustomPrintStatus : function(itemId, status,productName, dowloadurl, txtOrder) {
            var self = this;
            var url = self.update_custom_print_status_url;
            var loading = 'advance-preview-loading';
            var data = {
                item_id: itemId,
                status: status,
                customer_name: self.customer_name,
                customer_email: self.customer_email,
                product_name: productName,
                txt_order: txtOrder,
                customer_id: self.customer_id
            };
            // $('#product-custom-order-message').css('display','none');
            var messageId = status === 'downloading' ? 'product-custom-order-message' : '';
            helper.doRequest(url,data,loading,messageId,function (response) {
                if(response.status === 'success') {
                    $('#preview-project-item-status-' + itemId).html(response.item_status);
                    if(status === 'downloading' && dowloadurl !== '') {
                         // window.location.href = dowloadurl;
                         console.log(dowloadurl);
                        $('#btn-download-custom-design-'+itemId).css('display','none');
                        $('#btn-download-custom-design-failed-'+itemId).css('display','inline-block');
                        $('#btn-download-custom-design-approved-'+itemId).css('display','inline-block');
                        window.location.href = dowloadurl;
                       /* var win = window.open(dowloadurl, '_blank');
                        if (win) {
                            //Browser has allowed it to be opened
                            win.focus();
                        } else {
                            //Browser has blocked it
                            alert('Please allow popups for this website');
                        }*/
                    }
                    else {
                        $('#btn-download-custom-design-failed-'+itemId).css('display','none');
                        $('#btn-download-custom-design-approved-'+itemId).css('display','none');
                        window.location.href = self.order_detail_url
                    }
                }
            })
        },
        uploadProofImage : function(itemId) {
            var self = this;
            var data = new FormData($('#form-upload-custom-design-item-' + itemId)[0]);
            var url = self.upload_proof_url;
            // $('#demo-3d-test').html('');

            helper.uploadImages(url, data, 'advance-preview-loading', '', function (response) {
                console.log(response);
                if(response.status === 'success') {
                 /*   let previewData = response.preview_filed || null;
                    if(previewData) {
                        helper.showLoading('advance-preview-loading')
                        $('#preview-custom-order-preview-item-'+itemId).html('');
                        var elementId = 'preview-custom-order-preview-item-'+itemId;
                        var namePreview = previewData.name_preview;
                        var light = previewData.light;
                        var zoom = previewData.zoom
                        var modelPreview = previewData.model_preview;
                        var productId = previewData.product_id
                        // light = parseInt(light);
                        // zoom = parseInt(zoom);

                        var defaultModel = 'product_id_'+productId+'/'+modelPreview+'/'+namePreview;
                        console.log(elementId,namePreview,light,zoom,defaultModel);
                        productPreviewPro.productPreviewImage(defaultModel, zoom, light,elementId);
                        setTimeout(function () {
                            window.location.href = self.order_detail_url;
                        },100)
                    }*/
                    setTimeout(function () {
                        window.location.href = self.order_detail_url;
                    },100)
                }
                else {
                    alert({
                        title: 'Error',
                        content: 'Your upload file is not allow, Please check again'
                    })
                }
            })
        },
        getOrderTrackingItems : function(itemId) {
            var self = this;
            var data = {
                item_id: itemId
            };
            var url = self.tracking_items_url;
            console.log(url, itemId);
            var loading = 'advance-preview-loading';
            helper.doRequest(url,data,loading,'',function (response) {
                console.log(response);
                if(response.status === 'success') {
                   $('#preview-order-tracking-lists-'+itemId).html(response.html);
                }
            })
        },
        editOrderTrackingItem : function(itemId,productId,orderId,callback) {
            var self = this;
            var data = {
                item_id: itemId,
                product_id: productId,
                order_id: orderId
            };
            var loading = 'advance-preview-loading';
            var url = self.tracking_edit_url;
            helper.doRequest(url,data,loading,'product-custom-order-message',function (response) {
                if(response.status === 'success') {
                   $('#preview-add-tracking-modal').html(response.html);
                    callback()
                }
            })
        },
        saveOrderTrackingItem : function() {
            var self = this;
            var data = $('#form-add-tracking-item').serialize();
            var loading = 'advance-preview-loading';
            var url = self.tracking_save_url;
            helper.doRequest(url,data,loading,'product-custom-order-message',function (response) {
                if(response.status === 'success') {
                    // $('#preview-order-tracking-lists-'+itemId).html(response.html);
                    window.location.href = self.order_detail_url;
                }
            })
        },
        initAddTrackingModal : function() {
            var self = this;
            var options = {
                type: 'popup', // popup hoặc slide
                responsive: true,
                title: $t('Tracking'),
                buttons: [{
                    text: $t('Close'),
                    class: 'modal-close',
                    click: function () {
                        this.closeModal(); // Đóng modal
                    }
                }]
            };

            var popup = modal(options, $('#preview-add-tracking-modal'));
            $(".btn-preview-tracking-item").click(function() {
                var itemId = $(this).attr('item-id');
                var productId = $(this).attr('product-id');
                var orderId = $(this).attr('order-id');
                self.editOrderTrackingItem(itemId, productId,orderId,function () {
                    $('#preview-add-tracking-modal').modal('openModal');
                });

            });
        },
        updatePayStatus: function(itemId, status) {
            var self = this;
            var url = self.update_paid_status;
            var loading  = 'advance-preview-loading';
            var data = {
                item_id: itemId,
                pay_status: status
            }
            helper.doRequest(url , data, loading, '',function (response) {
                // $('#txt-change-pay-status-'+itemId).prop('disabled', true);
                $('#btn-update-pay-status-' + itemId).css('display','none');
                alert({
                    title: response.title,
                    content: response.message
                })
            })
        },
        initData : function() {
          var self = this;
          self.update_status_url = $('#txt-update-status-url').val();
          self.order_detail_url = $('#txt-custom-order-detail').val();
          self.customer_name = $('#txt-customer-name').val();
          self.customer_id = $('#txt-customer-id').val();
          self.customer_email = $('#txt-customer-email').val();
          self.upload_proof_url = $('#txt-upload-proof-url').val();
          self.update_custom_print_status_url = $('#txt-update-custom-print-status-url').val();
          self.tracking_items_url = $('#txt-tracking-items-url').val();
          self.tracking_edit_url = $('#txt-tracking-edit-url').val();
          self.tracking_save_url = $('#txt-tracking-save-url').val();
          self.tracking_delete_url = $('#txt-tracking-dell-url').val();
          self.update_paid_status = $('#txt-tracking-update-paid').val();
        },
        init: function () {
            var self = this;
            self.initData();
            self.initAddTrackingModal();
            console.log("previewCustomOrder LOADER");
            // disabled old 3d
            /*$('.custom-order-items-3d').each(function () {
                var elementId = $(this).attr('id');
                var namePreview = $(this).attr('preview-file-name');
                var light = $(this).attr('preview-light');
                var zoom = $(this).attr('preview-zoom');
                var modelPreview = $(this).attr('model-preview');
                var productId = $(this).attr('product-id');
                light = parseInt(light);
                zoom = parseInt(zoom);
                if(elementId === undefined || namePreview === undefined || light === undefined || productId === undefined || modelPreview === undefined) {
                    console.log("Model not found");
                }
                else {
                    var defaultModel = 'product_id_'+productId+'/'+modelPreview+'/'+namePreview;
                    console.log(elementId,namePreview,light,zoom,defaultModel);
                    productPreviewPro.productPreviewImage(defaultModel, zoom, light,elementId);
                }

            })*/
            // item status
            $('.btn-update-standard-status').click(function () {
                var itemId = $(this).attr('item-id');
                var status = $(this).attr('txt-status');
                var productName = $(this).attr('txt-product-name');
                var txtOrder = $(this).attr('txt-order');
                self.updateItemStatus(itemId,status,productName,txtOrder);
            })
            // custom design with upload pinting
            $('.btn-download-custom-design').click(function () {
                var itemId = $(this).attr('item-id');
                var status = $(this).attr('txt-status');
                var productName = $(this).attr('txt-product-name');
                var dowloadurl = $(this).attr('url-download');
                var txtOrder = $(this).attr('txt-order');
                self.updateCustomPrintStatus(itemId,status,productName,dowloadurl,txtOrder);
            })
            $('.btn-download-custom-design-approved').click(function () {
                var itemId = $(this).attr('item-id');
                var status = $(this).attr('txt-status');
                var productName = $(this).attr('txt-product-name');
                var dowloadurl = '';
                var txtOrder = $(this).attr('txt-order');
                self.updateCustomPrintStatus(itemId,status,productName,dowloadurl,txtOrder);
            })
            $('.btn-download-custom-design-failed').click(function () {
                var itemId = $(this).attr('item-id');
                var status = $(this).attr('txt-status');
                var productName = $(this).attr('txt-product-name');
                var dowloadurl = '';
                var txtOrder = $(this).attr('txt-order');
                self.updateCustomPrintStatus(itemId,status,productName,dowloadurl,txtOrder);
            })
            $('.txt-preview-upload-custom-design').change(function() {
                var itemId = $(this).attr('item-id');
                console.log('#txt-preview-upload-custom-design-'+itemId);
                self.uploadProofImage(itemId);
            })
            $('.btn-preview-upload-custom-design').click(function() {
                var itemId = $(this).attr('item-id');
                // self.uploadProofImage(itemId);
                // console.log('#txt-preview-upload-custom-design-'+itemId);
                $('#txt-preview-upload-custom-design-'+itemId).click();
            })
            $('.btn-update-pay-status').click(function () {
                // var status = $(this).val();
                var elementId = $(this).attr('id');
                var itemId = elementId.replace('btn-update-pay-status-','');
                var status = $('#txt-change-pay-status-'+itemId).val();
                self.updatePayStatus(itemId, status)
            })
            $('.txt-change-pay-status').change(function () {
                var elementId = $(this).attr('id');
                var itemId = elementId.replace('txt-change-pay-status-','');
                $('#btn-update-pay-status-' + itemId).css('display','inline-block');


            })
          /*  setTimeout(function () {
                $('.preview-custom-order-item').each(function () {
                    var status = $(this).attr('status');
                    if(status === 'shipping') {
                        var itemId = $(this).attr('item-id');
                        self.getOrderTrackingItems(itemId);
                    }
                })
            },1000)*/
           /* $('.btn-preview-tracking-item').click(function () {

            })*/
           /* $('#preview-add-tracking-modal').on("click","#btn-save-tracking",function () {
                self.saveOrderTrackingItem();
            })*/
        }
    }
    return previewCustomOrder;
})
