system.directive('fulfillbondre', function () {
    return {
        controller: function ($scope, $http, Upload, $q) {
            this.__proto__ = new BaseFulfillController($scope, $http);
            $scope.debug = false;
            if (user_email == 'tienanhbui0597@gmail.com') $scope.debug = true;

            $scope.bondreCurrentOrder = {};
            $scope.bondreSkus = [];
            $scope.bondreProductTypes = {
                names: {},
                materials: {},
                sizes: {},
                printLocals: {}
            };
            $scope.bonderItems = [];
            $scope.bondreStates = {
                initialized: false,
                product_types: []
            };

            let productTemplateIds = [];

            const getProductTypes = () => {
                const requestObj = $scope.buildLocaleData('/print-suppliers/bondre/get-product-sku', {}, $scope.fulFillLocale);
                return $http.get(requestObj.url, {
                    params: requestObj.params
                }).then((response) => {
                    if (response.data) {
                        $scope.bondreSkus = response.data;
                        $scope.bondreSkus.forEach(sku => {
                            if (!$scope.bondreProductTypes.names[sku.name]) {
                                $scope.bondreProductTypes.names[sku.name] = sku.name;
                            }
                            if (!$scope.bondreProductTypes.materials[sku.material]) {
                                $scope.bondreProductTypes.materials[sku.material] = sku.material;
                            }

                            if (!$scope.bondreProductTypes.sizes[sku.size]) {
                                $scope.bondreProductTypes.sizes[sku.size] = sku.size;
                            }

                            if (!$scope.bondreProductTypes.printLocals[sku.print_location]) {
                                $scope.bondreProductTypes.printLocals[sku.print_location] = sku.print_location;
                            }
                        });
                        
                        // $scope.bonderItems = angular.copy($scope.bondreSkus);
                    }
                });
            }
          
            const initializeBondre = async function () {
                return new Promise((resolve) => {
                    Promise.all([getProductTypes()]).then(() => {
                        resolve();
                    });
                });
            }

            $scope.chooseFilterOption = function (option, item) {
                item.bondreItems = angular.copy($scope.bondreSkus);
                Object.entries(item.bondreSku).forEach(([type, value]) => {
                    if (value) {
                        item.bondreItems = item.bondreItems.filter(function (item) {
                            return item[type] === value;
                        });
                    }
                });
            }

            const buildProfiles = (order) =>
            {
                const profiles = [];
                for (let i = 0; i < order.items.length; i++) 
                {
                    const item = order.items[i];
                    const options = {
                        artworks: item.bondre.artworks,
                        color: item.bondre.color,
                        type: item.bondre.type,
                        size: item.bondre.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 fetchProfiles = () =>
            {
                $scope.getDesignJobOrder($scope.bondreCurrentOrder);

                const requestObj = $scope.buildLocaleData('/print-suppliers/get-profile', {
                    type: 'bondre',
                    order_items: $scope.bondreCurrentOrder.items
                }, $scope.fulFillLocale);

                $http.post(requestObj.url, requestObj.params).then(function(response) {
                    if (response.data.status === 'successful') {
                        $scope.profiles = {
                            profiles: response.data.profiles,
                            designs: response.data.designs
                        };
                        productTemplateIds = response.data.product_template_ids;
                        applyProfiles();
                    }
                }, function(error) {
                    toastr.error('Error load profiles!');
                });
            }

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

            const applyProfiles = async () => 
            {
                $scope.bondreCurrentOrder.items.forEach(async printOrderItem => {

                    let profile = null;
                    let designs;

                    if (!printOrderItem.bondre.profile) {
                        printOrderItem.bondre.profile = {};
                    }

                    if (isTemplateProduct(printOrderItem.product_id)) {
                        profile = $scope.profiles.profiles.find(function (item) {
                            return parseInt(item.product_id) === parseInt(printOrderItem.product_id) && item.is_template_product;
                        });
                        designs = $scope.findDesign(printOrderItem, true, $scope.profiles.designs);
                    } else {
                        profile = $scope.profiles.profiles.find(function (item) {
                            return parseInt(item.product_sku_id) === parseInt(printOrderItem.product_sku_id) && !item.is_template_product;
                        });
                        designs =  $scope.findDesign(printOrderItem, false, $scope.profiles.designs);
                    }

                    printOrderItem.bondre.patternDesigns = [];
                    if(designs && designs.length) {
                        printOrderItem.bondre.patternDesigns = designs;

                        setTimeout(() => {
                            $('[data-magnify=gallery]').magnify({
                                zIndex: 10000
                            });
                        }, 500);
                    }

                    if(profile) 
                    {
                        const profileOptions = profile.options;
                    }

                    console.log('bondre', designs);

                });
            }

            $scope.bondre_openFilfillForm = 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.bondreStates.initialized) {
                    await initializeBondre();
                    $scope.bondreStates.initialized = true;
                }

                $scope.bondreCurrentOrder = angular.copy(order);
                $scope.getSuggestsPrinting($scope.bondreCurrentOrder.code);
                $scope.bondreCurrentOrder.items.forEach(item => {
                    item.bondreItems = angular.copy($scope.bondreSkus);
                });

                /* if ($scope.bondreCurrentOrder.attributes.customer_info) {
                    $scope.bondreCurrentOrder.customer.phone = $scope.bondreCurrentOrder.attributes.customer_info.phone;
                    $scope.bondreCurrentOrder.customer.full_name = $scope.bondreCurrentOrder.attributes.customer_info.full_name;
                } */

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

                if ($scope.bondreCurrentOrder.customer) {

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

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

                // init print logistic attr
                for (let i = 0; i < $scope.bondreCurrentOrder.items.length; i++) {
                    $scope.bondreCurrentOrder.items[i].bondre = {
                        artworks: {
                            front: {
                                location: 'front',
                            },
                            back: {
                                location: 'back',
                            },
                        },
                        product_types: [],
                        product_colors: [],
                        skus: [],
                        states: {}
                    };
                }

                for (let i = 0; i < $scope.bondreCurrentOrder.items.length; i++) {
                    $scope.getCustomConfigs($scope.bondreCurrentOrder.items[i]);
                }

                fetchProfiles();

                $scope.checkEstimateCosts($scope.bondreCurrentOrder, toastr);

                safeApply();

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

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

            $scope.chooseBondreSku = function (item, sku_id) {
                var sku = item.bondreItems.find(sku => sku.id === sku_id);
                item.bondreItems.forEach(element => {
                    if (element.id === sku_id) {
                        element.selected = true;
                    } else {
                        element.selected = false;
                    }
                });
                item.sku_seleted = sku;
            }

            $scope.orderToBondre = function () {
                var url = '/print-suppliers/bondre/auto-fulfill';
                var data = {
                    order_id: $scope.bondreCurrentOrder.id,
                    matching_skus: []
                };
                var check = true;
                $scope.bondreCurrentOrder.items.forEach(element => {
                    if (element.sku_seleted) {
                        data.matching_skus.push({
                            order_item_id: element.id,
                            sku: element.sku_seleted.sku,
                            artworks: element.bondre.artworks
                        });
                    } else {
                        toastr.error('Please choose sku for all items');
                        check = false;
                        return;
                    }
                });

                if (check) {
                    $http.post(url, data).then(function (response) {
                        if (response.data.status === 'successful') {
                            toastr.success('Order sent to Bondre');
                            $('#modalFulfillBondre').modal('hide');
                        } else {
                            toastr.error('Error! Cannot send order to Bondre');
                        }
                    }), function (error) {
                        console.log(error);
                    }
                }
            }

            $scope.bondre_uploadImages = async function (files, item, designFile) {
                let supportedFilesType = ['image/png', 'image/jpg', 'image/jpeg', 'image/gif'];
                let supportedFilesExtensions = ['jpg', 'jpeg', 'png', 'gif'];

                item.bondre.states.uploading = true;

                if (files) {
                    try {

                        let imagesUploaded = [];
                        let imageFile = null;
                        if (files && files.length) {
                            imageFile = files[0];

                            let fileExtension = imageFile.name.split('.').pop();
                            fileExtension = fileExtension.toLowerCase();
                            if (
                                supportedFilesExtensions.includes(fileExtension) &&
                                supportedFilesType.includes(imageFile.type)
                            ) {
                                imagesUploaded = await $scope.gelato_uploads(files);
                            } else {
                                toastr.error('Error! format supported: jpg, jpeg, png, gif');
                            }
                        }

                        if (imagesUploaded.length) {
                            $scope.$applyAsync(function () {
                                let imageUrl = imagesUploaded.pop();
                                if (imageUrl) {
                                    designFile.extension = imageFile.name.split('.').pop();
                                    designFile.url = imageUrl;
                                }
                                item.bondre.states.uploading = false;
                            });
                        }

                    } catch (error) {
                        console.log(error);
                        toastr.error('Error upload images!');
                    }
                }
            };

            $scope.bondre_chooseDesign = function (design, designFile, item) {
                if (!design.is_design_comfirm) {
                    toastr.error('Design is not confirmed');
                    return;
                }
                if (designFile.url !== design.url) {
                    designFile.url = design.url;
                    designFile.extension = design.url.split('.').pop();
                    $scope.bondre_changeDesignUrl(designFile);
                    safeApply();
                }
            }

            $scope.bondre_changeDesignUrl = function (designFile)
            {
                designFile.extension = designFile.url.split('.').pop();
                designFile.designPositions = {};

                safeApply();
            }

        }
    };
});
