function BaseFulfillController($scope, $http) {
    $scope.suggestsPrinting = [];
    
    $scope.getSuggestsPrinting = function (orderCode) {
        $http.get(base_api_url + '/api/get-profit-info', { params: { code: orderCode, get_warehouse: 1 }}).then(function (response) {
            let suggestsPrinting = {};
            if (response.data && response.data.products) {
                for (var product of response.data.products) {
                    if (product.warehouse && product.warehouse.printing_code && typeof suggestsPrinting[product.warehouse.printing_code] === 'undefined') {
                        suggestsPrinting[product.warehouse.printing_code] = {
                            name: product.warehouse.name,
                            printing_code: product.warehouse.printing_code,
                            cost: product.costBefore,
                        }
                    }
                    if (product.warehouse_suggests && product.warehouse_suggests.length) {
                        for (var suggest of product.warehouse_suggests) {
                            if (typeof suggestsPrinting[suggest.printing_code] === 'undefined') {
                                suggestsPrinting[suggest.printing_code] = {
                                    name: suggest.name,
                                    printing_code: suggest.printing_code,
                                    cost: suggest.cost
                                }
                            }
                        }
                    }
                }
            }
            $scope.suggestsPrinting = Object.values(suggestsPrinting);
        }, function (error) {
            $scope.suggestsPrinting = [];
        })
    }
}
system.directive('fulfillbase', function () {
    return {
        controller: function ($scope, $http, $rootScope, $timeout, $window, Upload) {

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

            $scope.getCustomConfigs = function (item) {

                if (typeof item.configurations != 'undefined' && item.configurations) {
                    try {
                        let configurations = JSON.parse(item.configurations);
                        let display_configure = {};
                        let design_url = [];

                        for (let key in configurations) {
                            let temp = configurations[key];
                            if (typeof temp == 'string' || typeof temp == 'number') {
                                display_configure[key] = temp;
                            } else if (typeof temp == 'object' && temp.type === 'image') {
                                design_url.push(temp.value);
                            }
                        }

                        item.configurations = configurations;
                        item.display_configure = display_configure;
                        item.design_url = design_url;

                        safeApply();

                    } catch (error) {
                        console.log(error)
                    }
                }
            }

            $scope.hasMultipleDesign = function (item) {
                return item.design_url && item.design_url.length;
            }

            $scope.download = function (item) {
                if (item.design_url && item.design_url.length) {
                    for (let url of item.design_url) {
                        if (url && url.substring(0, 1) !== '/' && url.substring(0, 4) !== 'http') {
                            url = 'https://' + url;
                        }
                        if (url && url.substring(0, 16) === 'https://https://') {
                            url = url.replace('https://https://', 'https://');
                        }
                        url = new URL(url);
                        const link = document.createElement('a');
                        link.href = url;
                        let file = url.pathname.split("/").pop();
                        link.setAttribute('download', file);
                        link.setAttribute('target', '_blank');
                        link.style.display = 'none';
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                    }
                }
            }

            $scope.capitalizeFirstLetter = function (string) {
                let _res = '';
                if (string && typeof string == 'string')
                    _res = string.charAt(0).toUpperCase() + string.slice(1);
                return _res;
            }

            $scope.writeToCache = function (key, data) {
                data.created = new Date().getTime();
                localStorage.setItem(key, JSON.stringify(data));
            }

            $scope.readFromCache = function (key) {
                return JSON.parse(localStorage.getItem(key)) || null;
            }

            $scope.buildLocaleData = function (url, params, locale) {
                if (locale && locale != '') {
                    if (locale != 'us') url = '/' + locale + url;
                    if (params && params != '') {
                        params.ignore_localization = 1;
                    }
                }
                return { url: url, params: params };
            }

            $scope.invertColor = function (hex, bw) {
                if (hex.indexOf('#') === 0) {
                    hex = hex.slice(1);
                }
                // convert 3-digit hex to 6-digits.
                if (hex.length === 3) {
                    hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
                }
                if (hex.length !== 6) {
                    console.warn('Invalid HEX color.');
                    return '#ffffff';
                }
                let r = parseInt(hex.slice(0, 2), 16),
                    g = parseInt(hex.slice(2, 4), 16),
                    b = parseInt(hex.slice(4, 6), 16);
                if (bw) {
                    return (r * 0.299 + g * 0.587 + b * 0.114) > 186
                        ? '#000000'
                        : '#FFFFFF';
                }
                // invert color components
                r = (255 - r).toString(16);
                g = (255 - g).toString(16);
                b = (255 - b).toString(16);
                // pad each with zeros and return
                return "#" + padZero(r) + padZero(g) + padZero(b);
            }

            function padZero(str, len) {
                len = len || 2;
                const zeros = new Array(len).join('0');
                return (zeros + str).slice(-len);
            }

            $scope.findDesign = function (orderItem, isTemplate, scopeDesigns)
            {
                let designs = scopeDesigns.filter(function(design) {
                    // let gCondition = parseInt(design.product_id) === parseInt(orderItem.product_id);
                    return parseInt(design.product_id) === parseInt(orderItem.product_id);

                    /* if (isTemplate) {
                        return gCondition
                            && design.type === 'design_template';
                    } else {
                        return gCondition
                            && parseInt(design.sku_id) === parseInt(orderItem.product_sku_id)
                            && design.type === 'design_sku';
                    } */
                });

                designs.sort(function(a, b) {
                    if (a.is_primary > b.is_primary){
                        return -1;
                    }
                    if (a.is_primary < b.is_primary){
                        return 1;
                    }
                    return 0;
                });

                return designs;
            }

            $scope.isTemplateProduct = function(productId, productTemplateIds) {
                return productTemplateIds.includes(productId);
            }

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

            $scope.name2Attrs = function(name) 
            {
                const obj = {};

                if (name && name.length) {
                    const regex = /(Color|Type|Style|Size|Couleur|Taille|Tipo|Estilo|Talla|Line Color):[^,]*/g;
                    const matches = name.match(regex, "i");

                    if (matches) {
                        for (let i = 0; i < matches.length; i++) {
                            const attr = matches[i].split(':');
                            obj[attr[0]] = attr[1].trim();
                        }
                    }
                }

                return obj;
            }

            $scope.copyToClipboard = str => {
                const el = document.createElement('textarea');
                el.value = str;
                el.setAttribute('readonly', '');
                el.style.position = 'absolute';
                el.style.left = '-9999px';
                document.body.appendChild(el);
                el.select();
                document.execCommand('copy');
                document.body.removeChild(el);
            };

            $scope.getDesignJobOrder = (currentOrder) => {

                let localCode = localePrefix;
                if (typeof localCode === 'undefined' || localCode === '') {
                    localCode = defaultLocale;
                }

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

                if (localCode == 'central') {
                    localCode = $scope.fulFillLocale;
                }

                let dataJob;
                dataJob = {
                    order_id: currentOrder.id,
                    locale: localCode
                };
                const requestObj = $scope.buildLocaleData('/service/pod/design-job/order', dataJob, $scope.fulFillLocale);
                return $http.get(requestObj.url, { params: requestObj.params }).then((res) => {
                    if ( res.data.status === 'successful') {
                        currentOrder.items.forEach((element, index) => {
                            // console.log(element);
                            // console.log(res.data.result[element.id]);
                            const item = res.data.result[element.id];
                            if (item) {
                                currentOrder.items[index].designJob = item;
                            }
                        });
                    }
                })
            }

            $scope.loadOrderInfo = (orderId, market = 'us') => {

                // console.log($scope.debug)
                // console.log(market)

                // build locate central
                let baseUrl = new URL(base_api_url);

                let _host = baseUrl.host.split('.');

                if (_host[0] !== 'api') {
                    _host[0] = market;
                    $scope.fulFillLocale = market;
                }

                _host = _host.join('.');
                baseUrl.host = _host;

                // orderId = 1373;

                return new Promise((resolve, reject) => {
                    $http.get(baseUrl.toString() + 'order?filters=id=' + orderId + '&embeds=shipment,warehouse,shippingInfoCompleted&metric=first&service_token=megaads@123').then(function (response) {
                        if (response.data.status === 'successful') {
                            resolve(response.data.result);
                        }
                    }); 
                });
            }

            $scope.getFailFulfillMessage = (supplier) =>
            {
                let defaultMessage = 'Vui lòng kiểm tra lại độ dài Zipcode, thông tin địa chỉ liên quan và thử lại';
                switch (supplier) {
                    case 'printify':
                        break;
                    default:
                        break;
                }

                return defaultMessage;
            }

            $scope.checkEstimateCosts = function(order, toastr = window.toastr) {

                const amount = order.amount;
                const estimateCosts = order.attributes.estimate_costs;

                if (estimateCosts && parseFloat(amount) < parseFloat(estimateCosts)) {
                    toastr.warning('Giá vốn của đơn hàng ' + order.code + ' cao hơn giá vốn ước tính. Bạn cần xác nhận lại giá vốn trước khi xác nhận đơn hàng.');
                }
            }


            $scope.callFunction =  function (fn, order) {
                $scope.$eval(fn, {order: order});
            }

            $scope.getPrinterClickPriority = function (list) {
                var retVal = list[0].click;
                for (var i in list) {
                    if (list[i].show_type != '') {
                        retVal = list[i].click;
                        break;
                    }
                }
                return retVal;
            }
        }
    };
});
