//#import Util.js
//#import pigeon.js
//#import $owlService:services/common/CommonUtil.jsx
//#import $owlService:services/product/PriceUtil.jsx
//#import $owlService:services/product/ProductUtil.jsx
//#import $owlService:services/cart/CartService.jsx
//#import $owl_mall_shop:services/modelService.jsx
//#import $owl_mall_cart:services/modelService.jsx
//#import $owl_mall_p:services/modelService.jsx
//#import $owl_mall_u:services/modelService.jsx
//#import $owl_mall_setting:services/modelService.jsx
//#import $owl_mall_off:services/modelService.jsx
//#import $owl_bclient:services/modelService.jsx
//#import $owl_orgs:services/modelService.jsx


var CartUtil = (function () {
    var f = {
        addItem: function (userId, isid, jItem,bclientId, orgId) {
            $.log("CartUtil.addItem: orgId=" + orgId);
            var cartId = CartService.getCartId((userId || isid) + "_" + orgId , 'common');
            if(bclientId){
                if(userId){
                    cartId = CartService.getCartId(userId + "_" + bclientId+ "_" + orgId , 'common');
                }
            }
            var org = owl_orgsService.get(orgId);

            var jCart = owl_mall_cartService.get(cartId);
            var isAdd = false; //cart是否已经存在？是调用cart的add 还是update
            if (!jCart) {
                var userName = null;
                if(userId){
                    var user = owl_mall_uService.get(userId);
                    userName = user.name;
                }

                var bclientName = ""
                if(bclientId){
                    var bclient = owl_bclientService.get(bclientId);
                    if(bclient){
                        bclientName = bclient.name;
                    }
                }

                var cartKey = (userId || isid) + "_" + orgId;
                if(userId && bclientId){
                    cartKey = userId + "_" + bclientId+ "_" + orgId;
                }
                // $.log("2...cartKey=" + cartKey);
                var cartIdWithoutPrefix = CartService.getCartIdWithoutPrefix(cartKey,'common')
                var _orgIds = "";

                jCart = {
                    userId:userId,
                    cartId:cartIdWithoutPrefix,
                    bclientId:bclientId,
                    bclientName : bclientName,
                    sessionId:isid,
                    userName:userName,
                    cartType:'common',
                    _orgId:orgId,
                    _orgIds:_orgIds
                };
                isAdd = true;
            }
            // $.log("3...cart is exists, cartId=" + cartId + ", jcart.cartId=" + jCart.cartId);
            jCart._orgId = orgId;
            if(org){
                // _orgIds = org.parentPathIds;
                jCart._orgIds = [].concat(org.parentPathIds,orgId);
            }
            else{
                jCart._orgIds = [orgId];
            }


            var items = jCart.items;
            if (!items) {
                items = [];
                jCart.items = items;
            }

            var item = f.getItem(items, jItem.shopId, jItem.productId, jItem.skuId, jItem.cartType);
            if (item) {
                item.amount = Number(item.amount) + Number(jItem.amount);
            } else {
                items.push(jItem);
            }
            if (isAdd) {
                owl_mall_cartService.add(jCart);
            } else {
                owl_mall_cartService.update(jCart);
            }
        },
        updateItem: function (cartId, itemId, amount) {
            var jCart = owl_mall_cartService.get(cartId);
            if (!jCart) {
                return {state:'err', msg:'cart not found, cartId=' + cartId};
            }

            var items = jCart.items;
            var item = f.getItemByItemId(items, itemId);
            if (!item) {
                return {state:'err', msg:'item not found,itemId=' + itemId};
            }
            if(item.amount + Number(amount)>0){
                item.amount = item.amount + Number(amount);
            }
            owl_mall_cartService.update(jCart);
            return {state:'ok'}
        },

        removeItem: function (cartId, itemKey) {
            var itemKeyList = [];
            itemKeyList.push(itemKey);
            f.removeItems(cartId, itemKeyList);
        },

        removeItems: function (cartId, itemKeyList) {
            var jCart = owl_mall_cartService.get(cartId);
            if (!jCart) {
                return;
            }
            // $.log('2.removeItems, cartId=' + cartId);
            var isUpdated = false;
            var items = jCart.items;
            var newItems = [];
            $.log("removeItems:" + JSON.stringify(itemKeyList)+ ",cart=" + JSON.stringify(jCart));
            for (var i = 0; i < items.length; i++) {
                var jItem = items[i];
                var key = jItem.itemId;
                if (CommonUtil.isExist(itemKeyList, key)) {
                    isUpdated = true;
                    continue;
                }
                newItems.push(jItem);
            }
            $.log("removeItems, newItems:" + JSON.stringify(newItems));
            jCart.items = newItems;
            if (isUpdated) {
                owl_mall_cartService.update(jCart);
            }
        },
        removeCheckedItems: function (userId, shopId, cartType) {
            var cartId = CartService.getCartId(userId);
            var jCart = owl_mall_cartService.get(cartId);
            if (!jCart) {
                return false;
            }

            var items = jCart.items;
            var newItems = [];
            for (var i = 0; i < items.length; i++) {
                var jItem = items[i];
                if (jItem.shop_id = shopId && jItem.cart_type == cartType && jItem.checked == "y") {
                    continue;
                }
                newItems.push(jItem);
            }
            jCart.items = newItems;

            owl_mall_cartService.update(jCart);
        },
        setItemChecked: function (cartId, itemId, checked) {
            var jCart = owl_mall_cartService.get(cartId);
            if (!jCart) {
                return false;
            }

            var items = jCart.items;
            var item = f.getItemByItemId(items, itemId);
            if (!item) {
                return false;

            }
            item.checked = checked ? "y" : "n";

            owl_mall_cartService.update(jCart);
            return true;
        },
        setCheckAll: function (cartId, checked,forOrgId) {
            $.log('setCheckAll,cartId='+cartId)
            var jCart = owl_mall_cartService.get(cartId);
            if (!jCart) {
                return;
            }
            $.log('setCheckAll,cartId='+cartId + ",cart=" + JSON.stringify(jCart));

            var items = jCart.items;
            for (var i = 0; i < items.length; i++) {
                var jItem = items[i];
                if(forOrgId && forOrgId!='0'){
                    if(forOrgId==jItem.orgId){

                        jItem.checked = checked ? "y" : "n";
                    }
                }
                else{
                    jItem.checked = checked ? "y" : "n";
                }
            }

            // $.log("cart.update, cartId=" + jCart.id);
            owl_mall_cartService.update(jCart);
        },
        getItemByItemId: function (items, itemId) {
            for (var i = 0; i < items.length; i++) {
                var jItem = items[i];
                if (jItem.itemId == itemId) {
                    return jItem;
                }
            }
            return null;
        },
        getItem: function (items, shopId, productId, skuId, cartType) {
            // $.log("getItem shopId=" + shopId + ", productId=" + productId + ", skuId=" + skuId + ",cartType=" + cartType);
            for (var i = 0; i < items.length; i++) {
                var jItem = items[i];
                if(skuId){
                    if (jItem.shopId === shopId && jItem.productId === productId && jItem.skuId === skuId && jItem.cartType === cartType) {
                        return jItem;
                    }
                }
                else{
                    if(jItem.shopId === shopId && jItem.productId === productId && jItem.cartType === cartType){
                        return jItem
                    }
                }

            }
            return null;
        },
        getItemKey: function (jItem) {
            return jItem.cart_type + "_" + jItem.shop_id + "_" + jItem.product_id + "_" + jItem.sku_id;
        },
        convertCart: function (jCart, shopId, cartType, checkedOnly, spec) {
            var smallItems = [];
            if (!spec) {
                spec = "200X200";
            }
            spec = spec.split("X");

            if (jCart.items) {
                var productIds = [];
                var skuIds = [];
                jCart.items.map(function (item) {
                    if (item.cart_type == cartType) {
                        if ((shopId && item.shop_id == shopId) || !shopId) {
                            if (!CommonUtil.isExist(productIds, item.product_id)) {
                                productIds.push(item.product_id);
                            }
                            skuIds.push(item.sku_id);
                        }
                    }
                });
                var products = owl_mall_pService.getObjects(productIds);
                var offIds = productIds.map(function (item, index) {
                    return "owl_mall_off_" + item;
                });
                var offs = owl_mall_offService.getObjects(offIds);
                var offMap = CommonUtil.convertMap("product_id", offs);

                for (var i = 0; i < jCart.items.length; i++) {
                    var jItem = jCart.items[i];
                    if (jItem.cart_type != cartType) {
                        continue;
                    }
                    if (shopId && jItem.shop_id != shopId) {
                        continue;
                    }
                    var jProduct = CommonUtil.getObjectById(products, jItem.product_id);
                    if (!jProduct) {
                        continue;
                    }
                    var jSku = null;
                    if (jItem.sku_id != jItem.product_id) {
                        jSku = ProductUtil.getSkuBySkuId(jProduct, jItem.sku_id);
                        if (!jSku) {
                            continue;
                        }
                    }

                    if (checkedOnly && jItem.checked != "y") {
                        continue;
                    }

                    var smallItem = {};
                    smallItem.itemKey = f.getItemKey(jItem);
                    smallItem.shopId = jItem.shop_id;
                    smallItem.productId = jItem.product_id;
                    smallItem.name = jItem.name;
                    smallItem.skuId = jItem.sku_id;
                    smallItem.skuCode = jItem.sku_code;
                    smallItem.barcode = jItem.barcode || "";
                    smallItem.icon = ProductUtil.getImageUrl(jItem.icon, spec[0], spec[1]);
                    smallItem.amount = jItem.amount;
                    smallItem.checked = jItem.checked == "y" ? true : false;
                    smallItem.attrs = ProductUtil.getSkuAttrs(jSku);
                    smallItem.addPrice = PriceUtil.toYuan(jItem.add_price);
                    smallItem.cartType = jItem.cart_type;
                    smallItem.unitName = jProduct.unit_name || "";
                    smallItem.deliveryPrice = PriceUtil.toYuan(jProduct.price_info.delivery_price || 0);
                    smallItem.unitPrice = cartType == "common" ? PriceUtil.toYuan(ProductUtil.getProductDealPrice(jProduct, jSku)) : PriceUtil.toYuan(jItem.add_price);
                    // 查询特价信息
                    smallItem.off = false;
                    if (offMap.has(jItem.product_id) && cartType == "common") {
                        var off = offMap.get(jItem.product_id);
                        if (off && off.publish_state == 1 && off.del != "T") {
                            var curr = new Date().getTime();

                            var beginTime = CommonUtil.convertDateTime(off.begin_time);
                            beginTime = beginTime.substring(0,19);
                            beginTime = beginTime.replace(/-/g,'/');
                            beginTime = new Date(beginTime).getTime();

                            var endTime = CommonUtil.convertDateTime(off.end_time);
                            endTime = endTime.substring(0,19);
                            endTime = endTime.replace(/-/g,'/');
                            endTime = new Date(endTime).getTime();

                            if (beginTime < curr && endTime > curr) {
                                smallItem.unitPrice = PriceUtil.toYuan(off.off_price);
                                smallItem.off = true;
                            }
                        }
                    }
                    smallItem.totalPrice = PriceUtil.toYuan(Number(smallItem.unitPrice) * Number(smallItem.amount));

                    smallItems.push(smallItem);
                }
            }

            var carts = [];
            var tempCarts = f.convertToCarts(jCart.user_id, cartType, smallItems);
            for (var i = 0; i < tempCarts.length; i++) {
                var smallCart = f.calcCartPrice(tempCarts[i]);
                var jShop = owl_mall_shopService.get(smallCart.shopId);
                smallCart.shopName = (jShop && jShop.name) || "";
                carts.push(smallCart);
            }
            return carts;
        },

        convertToCarts: function (userId, cartType, smallItems) {
            var bigCart = {};
            for (var i = 0; i < smallItems.length; i++) {
                var item = smallItems[i];
                var shopId = item.shopId;
                var shopCart = bigCart[shopId];
                if (!shopCart) {
                    shopCart = {};
                    shopCart.shopId = shopId;
                    shopCart.cartType = cartType;
                    shopCart.userId = userId;
                    bigCart[shopId] = shopCart;
                }
                var shopItems = shopCart.items;
                if (!shopItems) {
                    shopItems = [];
                    shopCart.items = shopItems;
                }
                shopItems.push(item);
            }
            var result = [];
            for (var key in bigCart) {
                result.push(bigCart[key]);
            }
            return result;
        },

        calcCartPrice: function (smallCart) {
            var shopId = smallCart.shopId;
            var totalProductPrice = 0;//商品总金额
            var totalDeliveryPrice = 0;//运费
            var totalDiscountPrice = 0;//折扣金额
            var totalDealPrice = 0;//成交价（totalProductPrice-totalDiscountPrice）
            var totalPayPrice = 0;//应付金额
            if (smallCart.items) {
                for (var i = 0; i < smallCart.items.length; i++) {
                    var jItem = smallCart.items[i];

                    if (!jItem.checked) {
                        continue;
                    }

                    totalProductPrice += Number(jItem.totalPrice);
                    totalDeliveryPrice += Number(jItem.deliveryPrice || 0);

                }
            }

            //满额免运费规则
            var deliveryFreeAmount = 0;
            var deliveryFreeAmountId = CartService.getDeliveryFreeAmountId(shopId);
            var jSetting = owl_mall_settingService.get(deliveryFreeAmountId);
            if (jSetting && jSetting.args_value) {
                deliveryFreeAmount = Number(jSetting.args_value);
            } else {
                $.log("\n.......................jSetting is null");
            }

            if (deliveryFreeAmount > 0 && totalProductPrice >= deliveryFreeAmount) {
                //满额免运费
                totalDeliveryPrice = 0;
            }

            totalDealPrice = totalProductPrice - totalDiscountPrice + totalDeliveryPrice;
            totalPayPrice = totalDealPrice;

            smallCart.totalDeliveryPrice = PriceUtil.toYuan(totalDeliveryPrice);
            smallCart.totalProductPrice = PriceUtil.toYuan(totalProductPrice);
            smallCart.totalDiscountPrice = PriceUtil.toYuan(totalDiscountPrice);
            smallCart.totalDealPrice = PriceUtil.toYuan(totalDealPrice);
            smallCart.totalPayPrice = PriceUtil.toYuan(totalPayPrice);

            return smallCart;
        }
    };
    return f;
})();