system.directive('fulfillproluxury', function () {
    return {
        controller: function ($scope, $http, Upload, $q) {
            this.__proto__ = new BaseFulfillController($scope, $http);
            $scope.proLuxuryProducts = [
                "3D Hoodies",
                "Ugly Sweaters",
                "Hawaii Shirts",
                "Hawaii Shirts With Pocket",
                "3D Zip Hoodies",
                "Leggings",
                "Embroidered Sweaters",
                "Drawstring Bags"
            ];

            $scope.proLuxurySizes = [
                "XS",
                "S",
                "M",
                "L",
                "XL",
                "2XL",
                "3XL",
                "4XL",
                "5XL",
                "One Size",
                "Mix",
                "Universal"
            ];

            $scope.debug = false;
            if (user_email == 'tienanhbui0597@gmail.com') $scope.debug = true;

            $scope.proLuxuryCurrentOrder = {};
            $scope.proLuxury = {
                initialized: false,
                products: []
            };

            function safeApply() {
                if ($scope.$root.$$phase !== '$apply' && $scope.$root.$$phase !== '$digest') {
                    $scope.$apply();
                }
            }

            const initializeProLuxury = async function () {
                return new Promise((resolve) => {
                    Promise.all([getProducts()]).then(() => {
                        resolve();
                    });
                });
            }

            const getSingleProfile = function(orderItem)
            {
                const profiles = buildProfiles(angular.copy($scope.proLuxuryCurrentOrder));

                const filteredProfiles = profiles.filter(profile => {
                    return profile.order_item_id == orderItem.id 
                });

                if (filteredProfiles.length) return filteredProfiles[0];
            }

            const applySingleProfile = async function(profile, orderItem)
            {
                const profileOptions = profile.options;
            }

            const getProducts = () => {
                return $http.get('/print-suppliers/proluxury/products').then((response) => {
                    if (response.data) {
                        $scope.proLuxury.products = response.data;
                    }
                }); 
            }

            const getSkus = (item) => {
                if (item.proLuxury.product) {
                    return $http.get('/print-suppliers/proluxury/skus?product_name=' + item.proLuxury.product).then((response) => {
                        if (response.data) {
                            item.proLuxury.skus = response.data;
                        }
                    }); 
                }
            }

            const postToProLuxury = (proLuxuryOrder) => 
            {
                toastr.options.positionClass = "toast-bottom-left";
                
                const requestObj = $scope.buildLocaleData('/print-suppliers/print-logistic/api?method=POST&end_point=order/add ', proLuxuryOrder, $scope.fulFillLocale);

                $http.post(requestObj.url, { params: requestObj.params }).then(function (response)
                {
                    if (response.data.status == 'Success') {
                        toastr.success('Successfully');
                        $('#modalFulfillProLuxury').modal('hide');
                    } else {
                        toastr.error('Has an Error! Please contact technical team.  | ' + JSON.stringify(response.data));
                    }

                    const mapItemPrintProvider = {};
                    const printervalOrder = angular.copy($scope.proLuxuryCurrentOrder);
                    for (let index = 0; index < printervalOrder.items.length; index++) {
                        const item = printervalOrder.items[index];
                        mapItemPrintProvider[item.id] = 'PRINTLOGISTIC';
                    }

                    afterFulfillAction(proLuxuryOrder, {mapItemPrintProvider});

                    stopLoadingButton('#btnPostProLuxuryOrder');
                    
                }).catch(function(error) {
                    toastr.error('Has an Error! Please contact technical team. | ' + JSON.stringify(error));
                    $('#modalFulfillProLuxury').modal('hide');
                    stopLoadingButton('#btnPostProLuxuryOrder');
                });
            }

            const orderProLuxury = () => 
            {
                safeApply();

                const printervalOrder = angular.copy($scope.proLuxuryCurrentOrder);
            
                if (proLuxury_validateItem(printervalOrder.items).validated) 
                {
                    const proLuxuryOrderBody = buildFulfillOrderBody(printervalOrder);

                    const param = {
                        title: 'Create Order',
                        customText: 'Post order to Print Logistic!',
                        confirmButtonText: 'Ok',
                        cancelButtonText: 'Back'
                    };

                    swal({
                        title: param.title,
                        html: param.customText,
                        type: "warning",
                        showConfirmButton: true,
                        showCancelButton: true,
                        confirmButtonText: param.confirmButtonText,
                        cancelButtonText: param.cancelButtonText
                    }).then(async function (isConfirm) 
                    {
                        if (isConfirm.value) {
                        
                            loadingButton('#btnPostProLuxuryOrder');

                            // postProfiles(printervalOrder);

                            // postToProLuxury(proLuxuryOrderBody);

                        } else {
                            console.log(proLuxuryOrderBody);
                        }

                    });

                } else  { // show error validate
                    document.getElementById("errorModalProLuxury").style.display = "block";
                }
            }

            const proLuxury_validateItem = (items) =>
            {
                let validated = true;
                let messages = {};

                for (let i = 0; i < items.length; i++) {
                    const itemData = items[i];
                    messages[itemData.product_sku_id] = [];

                    if (!itemData.proLuxury.product) {
                        validated = false;
                        messages[itemData.product_sku_id].push(itemData.name + ' || Missing Proluxury Product.');
                    }

                    if (!itemData.proLuxury.sku) {
                        validated = false;
                        messages[itemData.product_sku_id].push(itemData.name + ' || Missing Proluxury SKU.');
                    }

                    if (!itemData.proLuxury.designUrl) {
                        validated = false;
                        messages[itemData.product_sku_id].push(itemData.name + ' || Missing Proluxury designUrl.');
                    }
                }

                $scope.proLuxury.messages = messages;

                return {
                    validated,
                    messages
                };
            }

            const buildFulfillOrderBody = (currentOrder) => 
            {
                const fullName = currentOrder.customer.full_name;
                const partsName = fullName.split(' ');
                const lengthName = partsName.length;

                const lastName = partsName.pop();
                let firstName = partsName.join(' ');

                if (lengthName < 2) {
                    firstName = lastName;
                }

                let city = ' ';
                if (currentOrder.city_name) {
                    city = currentOrder.city_name;
                }

                const inventoryItems = getInventoryItems(currentOrder);

                let orderReferenceId = "API";
                if (printerval_locate && printerval_locate !== '') {
                    orderReferenceId += "_" + printerval_locate.toUpperCase();
                }
                orderReferenceId += "_" + currentOrder.code;

                const orderBody = {
                    "addr1": currentOrder.delivery_address,
                    "addr2": currentOrder.optional_address,
                    "city": city,
                    "consignee": firstName + ' ' + lastName,
                    "country": currentOrder.country.iso,
                    "phone": currentOrder.customer.phone,
                    // "currency_code": "USD",
                    "items": inventoryItems,
                    "order_no": orderReferenceId,
                    "post_code": currentOrder.zip_code,
                    "request_id": orderReferenceId + '_' + new Date().getTime().toString().substr(-4)
                };

                return orderBody;
            }

            const buildProfiles = (order) =>
            {
                const profiles = [];
                for (let i = 0; i < order.items.length; i++) 
                {
                    const item = order.items[i];
                    const options = {
                        artworks: item.proLuxury.artworks,
                        color: item.proLuxury.color,
                        type: item.proLuxury.type,
                        size: item.proLuxury.size,
                        sku: getPrintSku(item)
                    }

                    profiles.push({
                        product_id: item.product_id,
                        is_template_product: isTemplateProduct(item.product_id),
                        product_sku_id: item.product_sku_id,
                        order_id: item.id,
                        order_item_id: item.id,
                        options,
                        type: 'print-logistic'
                    });
                }
                return profiles;
            }

            /* const afterFulfillAction = async function (fulfillOrderPayload, additionalData = {}) 
            {
                logPrintifyFulFill(fulfillOrderPayload);

                const orderMeta = {
                    order_id: $scope.proLuxuryCurrentOrder.id,
                };

                if (additionalData && typeof additionalData.mapItemPrintProvider) {
                    orderMeta.print_provider = additionalData.mapItemPrintProvider;
                }

                requestObj = $scope.buildLocaleData('/print-suppliers/fulfill/attach-order-meta', orderMeta, $scope.fulFillLocale);
                
                return $http.post(requestObj.url, requestObj.params);
            }

            const logPrintifyFulFill = function(plOrder, isLogData = false) 
            {
                let logData;

                if (!isLogData) {
                    plOrder.printify_shop_id = $scope.printifyAccount.shop_id;
                    logData = {
                        actor_email: user_email,
                        event_type: 'PRINTLOGISTIC-FULFILLMENT',
                        target_id: $scope.proLuxuryCurrentOrder.id,
                        data: plOrder
                    };

                } else {
                    logData = plOrder;
                }

                const requestObj = $scope.buildLocaleData('/print-suppliers/fulfill/log', logData, $scope.fulFillLocale);
                $http.post(requestObj.url, requestObj.params).then(() => {});

            } */

            const isTemplateProduct = (productId) => {
                return productTemplateIds.includes(productId);
            }

            const getInventoryItems = (order) =>
            {
                const items = [];
            
                for (let i = 0; i < order.items.length; i++) 
                {
                    const item = order.items[i];
                    items.push({
                        "pcs": item.quantity,
                        "price": 0,
                        "print_spaces": [
                            {
                                "design_url": item.proLuxury.designUrl,
                                "position": "",
                                "preview_url": item.image_url
                            }
                        ],
                        "sku": item.proLuxury.sku,
                        "sku_name": item.proLuxury.product,
                        "variant_id": item.product_sku_id
                    });
                }

                return items;
            }

            const loadingButton = function (selector, text = 'Processing...') {
                $(selector).attr('dt-text', $(selector).text());
                $(selector).text(text);
                $(selector).attr("disabled", true);
            }

            const stopLoadingButton = function (selector) {
                $(selector).html($(selector).attr('dt-text'));
                $(selector).attr("disabled", false);
            }

            $scope.orderProLuxury = orderProLuxury;

            $scope.proLuxury_openFulfillForm = async function (orderOrCard) 
            {
                let order = angular.copy(orderOrCard);

                if (typeof orderOrCard.order_id != 'undefined') 
                {
                    $scope.loadingOrderInfo = true; 
                    order = await $scope.loadOrderInfo(orderOrCard.order_id, orderOrCard.locale_code);
                    $scope.loadingOrderInfo = false;

                    $scope.fulFillLocale = orderOrCard.locale_code;

                    safeApply();

                    if (!order) return toastr.error('Error! Cannot find order infomation...');

                } else {
                    if (typeof order.location != 'undefined' && order.location !== '') {
                        $scope.fulFillLocale = angular.copy(order.location);
                    } else {
                        $scope.fulFillLocale = null;
                    }
                }

                if (!$scope.proLuxury.initialized) {
                    await initializeProLuxury();
                    $scope.proLuxury.initialized = true;
                }

                $scope.proLuxuryCurrentOrder = angular.copy(order);
                $scope.getSuggestsPrinting($scope.proLuxuryCurrentOrder.code);
                if ($scope.proLuxuryCurrentOrder.attributes.customer_info) {
                    $scope.proLuxuryCurrentOrder.customer.phone = $scope.proLuxuryCurrentOrder.attributes.customer_info.phone;
                    $scope.proLuxuryCurrentOrder.customer.full_name = $scope.proLuxuryCurrentOrder.attributes.customer_info.full_name;
                }

                if ($scope.proLuxuryCurrentOrder.shipping_type != 'express') {
                    $scope.proLuxuryCurrentOrder.shipping_type = 'standard';
                }

                if ($scope.proLuxuryCurrentOrder.customer) {

                    if (typeof $scope.proLuxuryCurrentOrder.attributes.gift_info != 'undefined' && $scope.proLuxuryCurrentOrder.attributes.gift_info.name) {
                        $scope.proLuxuryCurrentOrder.customer.full_name = $scope.proLuxuryCurrentOrder.attributes.gift_info.name;
                        if ($scope.proLuxuryCurrentOrder.attributes.gift_info.phone) {
                            $scope.proLuxuryCurrentOrder.customer.phone = $scope.proLuxuryCurrentOrder.attributes.gift_info.phone;
                        }
                    }

                    $scope.proLuxuryCurrentOrder.customer.full_name = $scope.capitalizeFirstLetter($scope.proLuxuryCurrentOrder.customer.full_name);
                    if (window.user_email) {
                        $scope.proLuxuryCurrentOrder.customer.email = window.user_email;
                    }
                }

                // init print logistic attr
                for (let i = 0; i < $scope.proLuxuryCurrentOrder.items.length; i++) {
                    $scope.proLuxuryCurrentOrder.items[i].proLuxury = {
                        product: '',
                        size: '',
                        designUrl: ''
                    };
                }

                // fetchProfiles();

                safeApply();

                $('#modalFulfillProLuxury').modal({
                    modal: true,
                    persist: true,
                    position: [30, 0],
                    autoPosition: true
                });
            }

            $scope.changeProLuxuryProductOption = (orderItem) => {
                getSkus(orderItem);
            }

            $scope.changeProLuxurySKUOption = () => {

            }
        }
    };
});
