//#import Util.js
//#import $owl_mall_sku_inventory:services/modelService.jsx
//#import $owl_mall_category:services/modelService.jsx
//#import $owlService:services/product/PriceUtil.jsx
//#import pigeon.js

var ProductUtil = (function () {
    var f = {
        getProductLogo: function (jProduct) {
            if (jProduct && jProduct.images_info) {
                var preview_images = jProduct.images_info.preview_images;
                if (preview_images && preview_images.length > 0) {
                    return preview_images[0];
                }
            }
            return null;
        },
        getProductLogoUrl: function (jProduct, width, height) {
            var jImage = f.getProductLogo(jProduct);
            if (jImage) {
                return jImage.url + "?x-oss-process=image/resize,w_" + width + ",h_" + height;
            }
            return "";
        },
        getProductLogoUrlEx: function (jProduct, spex) {
            var imageSize = spex.split("X");

            return f.getProductLogoUrl(jProduct, imageSize[0], imageSize[1]);
        },
        getImageUrl: function (jImage, width, height) {
            if (jImage) {
                return jImage.url + "?x-oss-process=image/resize,w_" + width + ",h_" + height;
            }
            return "";
        },
        getImageList: function (jProduct, key, spex) {
            var resultImages = [];
            var images_info = jProduct.images_info;
            if (images_info) {
                var images = images_info[key];
                if (images) {
                    var imageSize = spex.split("X");
                    images.map(function (jImage) {
                        var img = {
                            relUrl: f.getImageUrl(jImage, imageSize[0], imageSize[1]),
                            fullUrl: jImage.url
                        };
                        resultImages.push(img);
                    });
                }
            }
            return resultImages;
        },
        getSkuAttrs: function (jSku) {
            var value = "";
            if (jSku) {
                if (jSku.attr_color) {
                    value = jSku.attr_color;
                }
                if (jSku.attr_spec) {
                    if (value == "") {
                        value = jSku.attr_spec;
                    } else {
                        value += "," + jSku.attr_spec;
                    }
                }
            }
            return value;
        },
        getSkuBySkuId: function (jProduct, skuId) {
            if (jProduct) {
                if (jProduct.skus && jProduct.skus.length > 0) {
                    for (var i = 0; i < jProduct.skus.length; i++) {
                        var sku = jProduct.skus[i];
                        if (sku.sku_id == skuId) {
                            return sku;
                        }
                    }
                    return jProduct.skus[0];
                }
            }
            return null;
        },
        /**
         * 获取商品的所有sku的总可卖数
         * @param skus
         * @returns {number}
         */
        getTotalProductAvailableInventory: function (skus) {
            var totalInventory = 0;
            if (skus) {
                if (skus && skus.length > 0) {
                    for (var i = 0; i < skus.length; i++) {
                        var sku = skus[i];
                        totalInventory += f.getSkuAvailableInventory(sku);
                    }
                }
            }
            return totalInventory;
        },
        /**
         * 获取单个sku的可卖数
         * @param sku
         * @returns {number}
         */
        getSkuAvailableInventory: function (sku) {
            var id = "owl_mall_sku_inventory_" + sku.id;
            var jInventory = owl_mall_sku_inventoryService.get(id);
            if (jInventory) {
                return Number((jInventory.real_inventory || 0) - (Number(jInventory.lock_number || 0)));
            }
            return 0;
        },
        /**
         * 起订量
         * @param sku
         * @returns {number}
         */
        getSkuOnceMinBuy: function (sku) {
            if (sku && sku.once_min_buy) {
                return Number(sku.once_min_buy);
            }
            return 0;
        },
        /**
         * 每单限购数量
         * @param sku
         * @returns {string|number}
         */
        getSkuOnceLimitBuy: function (sku) {
            if (sku && sku.once_limit_buy) {
                return Number(sku.once_limit_buy);
            }
            return "";
        },
        getProductMarketPrice: function (jProduct, jSku) {
            if (jSku) {
                if (jSku.price_info && jSku.price_info.market_price) {
                    return PriceUtil.toYuan(jSku.price_info.market_price);
                }
            }
            // return PriceUtil.toYuan((jProduct && jProduct.price_info && jProduct.price_info.market_price) || "");
            return "";//2025-01-03，改成当sku未设置市场价，则返回为空，不返回商品的了
        },
        getSkuMinPrice: function (jProduct, jSku) {
            if (jSku) {
                if (jSku.price_info && jSku.price_info.min_price) {
                    return PriceUtil.toYuan(jSku.price_info.min_price);
                }
            }
            return PriceUtil.toYuan((jProduct && jProduct.price_info && jProduct.price_info.min_price) || "");
        },
        getSkuMaxPrice: function (jProduct, jSku) {
            if (jSku) {
                if (jSku.price_info && jSku.price_info.max_price) {
                    return PriceUtil.toYuan(jSku.price_info.max_price);
                }
            }
            return PriceUtil.toYuan((jProduct && jProduct.price_info && jProduct.price_info.max_price) || "");
        },
        getSupplyPrice: function (jProduct, jSku) {
            if (jSku) {
                if (jSku.price_info && jSku.price_info.supply_price) {
                    return PriceUtil.toYuan(jSku.price_info.supply_price);
                }
            }
            return PriceUtil.toYuan((jProduct && jProduct.price_info && jProduct.price_info.supply_price) || "");
        },
        getSecurityPrice: function (jProduct, jSku) {
            return f.getSkuMinPrice(jProduct, jSku);
        },
        getProductDealPrice: function (jProduct, jSku) {
            if (jSku) {
                if (jSku.price_info && jSku.price_info.sell_price) {
                    return PriceUtil.toYuan(jSku.price_info.sell_price);
                }
            }
            return "";
        },
        getInventoryAttrs: function (jProduct, skus) {
            var inventoryAttrs = [];
            var sku_attrs = jProduct.sku_attrs;
            if (sku_attrs) {
                for (var i = 0; i < sku_attrs.length; i++) {
                    var jAttr = sku_attrs[i];
                    var attr_id = jAttr.attr_id;
                    var attr_name = jAttr.attr_name;
                    var attr_choice = jAttr.attr_choice;
                    if (skus) {
                        attr_choice = f.filterAttrChoice(attr_id, attr_choice, skus);
                    }

                    var standardValues = [];
                    if (attr_choice) {
                        var values = attr_choice.split(",");
                        for (var k = 0; k < values.length; k++) {
                            standardValues.push({id: values[k], name: values[k]});
                        }
                    }

                    var jRecord = {};
                    jRecord.id = attr_id;
                    jRecord.name = attr_name;
                    jRecord.attr_choice = attr_choice;
                    jRecord.standardValues = standardValues;
                    inventoryAttrs.push(jRecord);
                }
            }
            return inventoryAttrs;
        },
        filterAttrChoice: function (attrId, attr_choice, skus) {
            var result = "";
            if (attr_choice) {
                var values = attr_choice.split(",");
                for (var k = 0; k < values.length; k++) {
                    var v = values[k];
                    if (!f.checkAttrValueIsExistSku(skus, attrId, v)) {
                        continue;
                    }
                    if (f.isExistStandValue(result, v)) {
                        continue;
                    }
                    if (result != "") {
                        result += ",";
                    }
                    result += v;
                }
            }
            return result;
        },
        isExistStandValue: function (attr_choice, value) {
            if (attr_choice) {
                var values = attr_choice.split(",");
                for (var k = 0; k < values.length; k++) {
                    var v = values[k];
                    if (v == value) {
                        return true;
                    }
                }
            }
            return false;
        },
        checkAttrValueIsExistSku: function (skus, attrId, value) {
            if (skus) {
                for (var i = 0; i < skus.length; i++) {
                    var jSku = skus[i];
                    var attrs = jSku.attrs;
                    if (attrs) {
                        if (attrs[attrId] == value) {
                            return true;
                        }
                    }
                }
            }
            return false;
        },
        getPlatformCategoryId: function (jProduct) {
            var platform_category = jProduct.platform_category;
            if (platform_category) {
                for (var i = 0; i < platform_category.length; i++) {
                    return platform_category[0].id;
                }
            }
            return "";
        },
        getPlatformCategoryName: function (jProduct) {
            var platform_category = jProduct.platform_category;
            if (platform_category) {
                for (var i = 0; i < platform_category.length; i++) {
                    return platform_category[0].name;
                }
            }
            return "";
        },
        addProcessLog: function (jProduct, userId, userName, memo) {
            var process_memos = jProduct.process_memos;
            if (!process_memos) {
                process_memos = [];
                jProduct.process_memos = process_memos;
            }
            process_memos.push({
                time: new Date().getTime(),
                userId: userId,
                userName: userName,
                memo: memo
            });
        },
        /**
         * 获取商品的税费
         * 根据跨境电子商务零售进口税收政策（财关税〔2016〕18号、财关税〔2018〕49号等），个人单次交易限值为人民币5000元，个人年度交易限值为人民币26000元。
         * 在限值以内进口的跨境电子商务零售进口商品，关税税率暂设为0%，进口环节增值税、消费税取消免征税额，暂按法定应纳税额的70%征收，计算规则如下：
         * 应纳税额 = 进口货物完税价格 x [（增值税税率+消费税税率 ）/ (1-消费税税率) ] x 70%
         * 进口货物完税价格超过5000元单次交易限值但低于26000元年度交易限值，且订单下仅一件商品时，可以自跨境电商零售渠道进口，按照货物税率全额征收关税和进口环节增值税、消费税，交易额计入年度交易总额。计算规则如下：
         * 个人年度超过后，按一般贸易来，26000不是江豚网一家，而是这个人全年在海关的记录
         * 一般贸易应纳税额=完税价格 × 关税税率  +（完税价格 + 关税税额）× 增值税税率+〔（完税价格 + 关税税额）÷（1 - 消费税税率）〕× 消费税税率
         * *注：进口货物完税价格 = 商品零售价格 + 运费 + 保险费
         */
        getTaxPrice: function (jProduct, jUser, dutiablePrice, rateInfo) {
            if (jProduct.cb_rate_type == "2") {
                //价格已含税
                return 0;
            }
            dutiablePrice = Number(dutiablePrice || 0);
            if (dutiablePrice <= 0) {
                return 0;
            }
            if(!rateInfo) {
                rateInfo = f.getProductCrossBorderRateInfo(jProduct);
            }
            $.log("ProductUtil.jsx...productId=" + jProduct.id + "...rateInfo=" + JSON.stringify(rateInfo) + "...dutiablePrice=" + dutiablePrice);
            if (!rateInfo) {
                return 0;
            }
            if (!rateInfo.cb_vat_rate || !rateInfo.cb_tax_rate || !rateInfo.cb_tariff_rate || !rateInfo.cb_total_rate) {
                return 0;
            }
            var cb_vat_rate = Number(rateInfo.cb_vat_rate)/100;
            var cb_tax_rate = Number(rateInfo.cb_tax_rate)/100;
            var cb_tariff_rate = Number(rateInfo.cb_tariff_rate)/100;
            var cb_total_rate = Number(rateInfo.cb_total_rate)/100;

            if (dutiablePrice <= 5000) {
                return Number(Number(dutiablePrice * ((cb_vat_rate + cb_tax_rate) / (1 - cb_tax_rate)) * 0.7).toFixed(2));
            }

            //todo:大于5000的后面要加上规则
            return Number(Number(dutiablePrice * ((cb_vat_rate + cb_tax_rate) / (1 - cb_tax_rate)) * 0.7).toFixed(2));
        },
        /**
         * 获取商品的的跨境税率
         */
        getProductCrossBorderRateInfo: function (jProduct) {
            $.log("ProductUtil.jsx...productId=" + jProduct.id + "...jProduct.cb_rate_type=" + jProduct.cb_rate_type);
            if (jProduct.cb_rate_type == "2") {
                //价格已含税
                return {
                    "cb_vat_rate": 0,
                    "cb_tax_rate": 0,
                    "cb_tariff_rate": 0,
                    "cb_total_rate": 0
                };
            }
            if (jProduct.cb_rate_type == "1") {
                //以商品设置为准
                return {
                    "cb_vat_rate": jProduct.cb_vat_rate,
                    "cb_tax_rate": jProduct.cb_tax_rate,
                    "cb_tariff_rate": jProduct.cb_tariff_rate,
                    "cb_total_rate": jProduct.cb_total_rate
                };
            }
            var platformCatId = f.getPlatformCategoryId(jProduct);
            if (!platformCatId) {
                $.log("ProductUtil.jsx...productId=" + jProduct.id + "...platformCatId is null");
                return null;
            }
            var jCategory = owl_mall_categoryService.get(platformCatId);
            if (!jCategory) {
                $.log("ProductUtil.jsx...productId=" + jProduct.id + "...jCategory is null");
                return null;
            }
            if(jCategory.cb_vat_rate || jCategory.cb_tax_rate || jCategory.cb_total_rate) {
                return {
                    "cb_vat_rate": jCategory.cb_vat_rate,
                    "cb_tax_rate": jCategory.cb_tax_rate,
                    "cb_tariff_rate": jCategory.cb_tariff_rate,
                    "cb_total_rate": jCategory.cb_total_rate
                };
            }
            //todo:该方法后面看看怎么做缓存加速
            var parentPathIds = jCategory.parentPathIds;
            if (parentPathIds && parentPathIds.length > 0) {
                for (var i = parentPathIds.length - 1; i >= 0; i--) {
                    var tempCatId = parentPathIds[i];
                    jCategory = owl_mall_categoryService.get(tempCatId);
                    if (!jCategory) {
                        continue;
                    }

                    return {
                        "cb_vat_rate": jCategory.cb_vat_rate,
                        "cb_tax_rate": jCategory.cb_tax_rate,
                        "cb_tariff_rate": jCategory.cb_tariff_rate,
                        "cb_total_rate": jCategory.cb_total_rate
                    };
                }
            }
            return null;
        }
    };
    return f;
})();