Browse Source

代码优化

喻文俊 3 years ago
parent
commit
d69de72f98

+ 4 - 4
common/util.js

@@ -1,5 +1,5 @@
 /* 常用工具函数 */
-const msg = (title, duration = 1500, mask = true, icon = 'none') => {
+export const msg = (title, duration = 1500, mask = true, icon = 'none') => {
     //统一提示方便全局修改
     if (Boolean(title) === false) {
         return
@@ -11,7 +11,7 @@ const msg = (title, duration = 1500, mask = true, icon = 'none') => {
         icon
     })
 }
-const modal = (title, content, confirmText, cancelText, showCancel = false, callBack) => {
+export const modal = (title, content, confirmText, cancelText, showCancel = false, callBack) => {
     uni.showModal({
         title,
         content,
@@ -26,7 +26,7 @@ const modal = (title, content, confirmText, cancelText, showCancel = false, call
         }
     })
 }
-const json = type => {
+export const json = type => {
     //模拟异步请求数据
     return new Promise(resolve => {
         setTimeout(() => {
@@ -36,7 +36,7 @@ const json = type => {
     })
 }
 
-const prePage = () => {
+export const prePage = () => {
     let pages = getCurrentPages()
     let prePage = pages[pages.length - 2]
     // #ifdef H5

+ 201 - 445
pages/goods/cart.vue

@@ -43,7 +43,7 @@
                                 <view class="goods-pros" v-for="(pros, idx) in item.productList" :key="idx">
                                     <view class="goods-pros-t">
                                         <!--选择商品-->
-                                        <view class="checkbox-box" @click.stop="ischeck(item, pros)">
+                                        <view class="checkbox-box" @click.stop="checkProduct(item, pros)">
                                             <view
                                                 class="checkbox iconfont"
                                                 :class="[pros.productsChecked ? 'icon-xuanze' : 'icon-weixuanze']"
@@ -78,7 +78,7 @@
                                                             type="number"
                                                             maxlength="4"
                                                             v-model="pros.productCount"
-                                                            @blur="changeNnmber($event, item, pros)"
+                                                            @blur="changeNumber($event, item, pros)"
                                                             @focus="changeInput(pros)"
                                                         />
                                                         <view
@@ -188,7 +188,7 @@
         <tui-modal
             :show="modal"
             @click="handleClick"
-            @cancel="hideMobel"
+            @cancel="hideModal"
             :content="contentModalText"
             color="#333"
             :size="32"
@@ -206,7 +206,7 @@ import authorize from '@/common/authorize.js'
 import HeaderCart from '@/components/cm-module/headerNavbar/header-cart.vue' //顶部自定义胶囊'
 import activiPopup from '@/components/cm-module/productDetails/cm-activipopu'
 import modalLayer from '@/components/cm-module/modal-layer/modal-layer'
-import { mapGetters } from 'vuex'
+import { mapGetters, mapActions, mapMutations } from 'vuex'
 import { cartList } from '@/common/json/data.json.js' //本地数据
 
 export default {
@@ -227,33 +227,15 @@ export default {
             headerBtnPosi: this.setHeaderBtnPosi(), //获取设备顶部胶囊高度
             systeminfo: this.setSysteminfo(), //获取设备信息
             CustomBar: this.CustomBar, // 顶部导航栏高度
-            userId: '',
             popupShow: false,
             handlerPros: {}, //监听单挑促销商品
-            failureList: [], //失效商品列表
-            goodsList: [], //购物车的商品
-            delGoodsList: '', //要删除的商品
-            setGoodData: '', //确认订单的商品
             isCheckAll: false, //是否全选
-            kindCount: 0, //购物车宝贝数量
             allPrice: 0, //所有价格
             totalOriginalPrice: 0, //所有原价价
             reducedPrice: 0, //满减
-            allCount: 0, //被选中的产品数量
-            isModallayer: false,
             skeletonShow: true,
             isshowDelbtn: false,
-            isDisabled: false, // 供应商/店铺全选是否禁用状态
-            isEmpty: false, //显示空购物车
             scrollHeight: 'auto',
-            nomoreText: '上拉显示更多',
-            hasNextPage: false,
-            loadding: false,
-            pullUpOn: true,
-            pullFlag: true,
-            pageSize: 10,
-            pageNum: 1,
-            submitIds: [],
             modal: false,
             contentModalText: '',
             deleteType: 0
@@ -263,7 +245,20 @@ export default {
         this.setScrollHeight()
     },
     computed: {
-        ...mapGetters(['hasLogin', 'isIphoneX'])
+        ...mapGetters([
+            'hasLogin',
+            'isIphoneX',
+            'isEmpty',
+            'goodsList',
+            'failureList',
+            'kindCount',
+            'userId',
+            'cartIds'
+        ]),
+        //被选中的产品数量
+        allCount() {
+            return this.cartIds.length
+        }
     },
     filters: {
         NumFormat(value) {
@@ -275,463 +270,257 @@ export default {
             return (val * count).toFixed(2)
         }
     },
+    watch: {
+        //深度监听所有数据,每次改变重新计算总价和总数
+        goodsList: {
+            deep: true,
+            handler(val, oldval) {
+                this.totalPeice()
+            }
+        }
+    },
+    //下拉刷新
+    onPullDownRefresh() {
+        this.initCart().finally(() => {
+            setTimeout(() => {
+                uni.stopPullDownRefresh()
+            }, 2000)
+        })
+    },
+    onShow() {
+        if (this.hasLogin) {
+            this.initData()
+        } else {
+            this.$api.redirectTo('/pages/login/login')
+        }
+    },
+    onHide() {
+        this.saveCartIds([])
+    },
     methods: {
+        ...mapActions('cart', ['initCart', 'updateShoppogCount', 'removeFromCart', 'removeFailureFromCart']),
+        ...mapMutations('cart', [
+            'selectProduct',
+            'selectAllShopProduct',
+            'selectAllProduct',
+            'saveCartIds',
+            'selectFailure',
+            'selectAllFailure'
+        ]),
         initData() {
-            this.isModallayer = false //遮罩层 防止多次点击
-            this.isCheckAll = false //是否全选
-            this.submitIds = []
-            this.$api.getStorage().then(resolve => {
-                this.userId = resolve.userId ? resolve.userId : 0
-                this.InitGetCartGoodsList()
+            this.initCart().finally(() => {
+                this.skeletonShow = false
             })
         },
+        // 活动价弹窗
         clickPopupShow(pros, type) {
             if (pros.ladderList.length > 0) {
                 this.popupShow = true
                 this.handlerPros = pros
             }
         },
-        setScrollHeight() {
-            // 窗口高度-footer高度
-            const { windowHeight, pixelRatio } = uni.getSystemInfoSync()
-            setTimeout(() => {
-                const query = uni.createSelectorQuery().in(this)
-                query.selectAll('.footer').boundingClientRect()
-                query.exec(res => {
-                    this.windowHeight = windowHeight
-                    if (res[0][0]) {
-                        this.scrollHeight = windowHeight - res[0][0].height
-                    }
-                })
-            }, 500)
-        },
-        InitGetCartGoodsList() {
-            //初始化购物车 index:1
-            this.ProductService.QueryShoppingCartList({ userId: this.userId })
-                .then(response => {
-                    this.skeletonShow = false
-                    let data = response.data
-                    this.kindCount = data.cartQuantity
-                    if (data.shopList.length > 0 || data.products.length > 0) {
-                        this.isEmpty = false
-                    } else {
-                        this.isEmpty = true
-                    }
-                    if (data.shopList && data.shopList.length > 0) {
-                        this.goodsList = data.shopList
-                        console.log(this.goodsList)
-                        this.totalShopPeice()
-                    } else {
-                        this.goodsList = []
-                    }
-                    if (data.products && data.products.length > 0) {
-                        this.failureList = data.products
-                    } else {
-                        this.failureList = []
-                    }
-                })
-                .catch(error => {
-                    this.$util.msg(error.msg, 2000)
-                })
-        },
+        // 勾选单个失效商品
         ischeckFailure(failure) {
-            failure.productsChecked = !failure.productsChecked
-            this.updateCheckAllBtn()
-        },
-        ischeck(item, pro) {
-            //为未选中的时候改变为true,反之为true
-            pro.productsChecked = !pro.productsChecked
-            if (pro.productsChecked) {
-                if (!this.submitIds.includes(pro.productID * 1)) {
-                    this.submitIds.push(pro.productID)
-                }
-            } else {
-                var lent = this.submitIds.indexOf(pro.productID * 1)
-                if (lent >= 0) {
-                    this.submitIds.splice(lent, 1)
-                }
-            }
-            this.updateProductCheckedAllBtn(item)
-            this.updateCheckAllBtn()
-        },
-        updateProductCheckedAllBtn(item) {
-            // 单独每个供应商的勾选判断
-            let productList = item.productList,
-                productsCheckedLength = 0,
-                disabledLength = 0
-            if (this.isshowDelbtn) {
-                productList.forEach(pros => {
-                    if (pros.productsChecked) {
-                        productsCheckedLength++
-                    }
-                })
-            } else {
-                productList.forEach(pros => {
-                    if (pros.productsChecked) {
-                        productsCheckedLength++
-                    }
-                })
-            }
-            item.checked = productsCheckedLength === productList.length
-        },
-        updateCheckAllBtn() {
-            // 全选勾选判断
-            let goodsCheckedLength = 0,
-                goodsList = this.goodsList,
-                failureList = this.failureList
-            goodsList.forEach(item => {
-                if (item.checked) {
-                    goodsCheckedLength++
-                }
-            })
-            failureList.forEach(failureItem => {
-                if (failureItem.productsChecked) {
-                    goodsCheckedLength++
-                }
+            this.selectFailure({
+                productId: failure.productId,
+                checked: !failure.productsChecked
             })
-            if (this.isshowDelbtn) {
-                this.isCheckAll = goodsCheckedLength === goodsList.length + failureList.length
-            } else {
-                this.isCheckAll = goodsCheckedLength === goodsList.length
-            }
+            this.getCheckedProductId()
         },
-        checkShop(item) {
-            //与单选商品类似
-            item.checked = !item.checked
-            this.setProductChecked(item)
-            this.updateCheckAllBtn()
+        // 勾选单个商品
+        checkProduct(shop, product) {
+            this.selectProduct({
+                shopId: shop.shopId,
+                productId: product.productId,
+                checked: !product.productsChecked
+            })
+            this.isSelectAll()
         },
-        setProductChecked(item) {
-            item.productList.forEach(pros => {
-                if (item.checked) {
-                    pros.productsChecked = true
-                    if (!this.submitIds.includes(pros.productId * 1)) {
-                        this.submitIds.push(pros.productId)
-                    }
-                } else {
-                    pros.productsChecked = false
-                    var lent = this.submitIds.indexOf(pros.productId * 1)
-                    if (lent >= 0) {
-                        this.submitIds.splice(lent, 1)
-                    }
-                }
+        // 勾选商店所有商品
+        checkShop(shop) {
+            this.selectAllShopProduct({
+                shopId: shop.shopId,
+                checked: !shop.checked
             })
+            this.isSelectAll()
         },
-        updateBothCheckBtn() {
+        // 勾选全部商品
+        checkAll() {
+            this.isCheckAll = !this.isCheckAll
+            this.selectAllProduct(this.isCheckAll)
+            // 删除商品的全选也要选中失效商品
             if (this.isshowDelbtn) {
-                // 当管理删除按钮出现时,失效的商品可被选择
-                this.goodsList.forEach(item => {
-                    item.checked = this.isCheckAll
-                    this.setProductChecked(item)
-                })
-                //删除按钮 全选包括失效商品勾选
-                this.failureList.forEach(failureItem => {
-                    failureItem.productsChecked = this.isCheckAll
-                })
-            } else {
-                this.goodsList.forEach(item => {
-                    item.checked = this.isCheckAll && !item.isDisabled
-                    this.setProductChecked(item)
-                })
+                this.selectAllFailure(this.isCheckAll)
             }
+            this.isSelectAll()
         },
-        checkAll() {
-            //全选方法内调用方法
-            this.isCheckAll = !this.isCheckAll
-            this.updateBothCheckBtn()
+        // 判断是否全选商品
+        isSelectAll() {
+            this.isCheckAll = this.goodsList.every(shop => shop.checked)
+            this.getCheckedProductId()
         },
-        totalShopPeice() {
-            //每次所属会所下的商品增减重新计算合计价格&减去含有下架的商品
-            let touchPrice = 0
-            let reducedPrice = 0 //商铺合计满减价
-            this.goodsList.map((item, index) => {
-                let _totalPrice = 0
-                let _reducedPrice = 0
-                let _totalOriginalPrice = 0
-                item.productList.forEach(pros => {
-                    let _price = pros.price * pros.productCount
-                    _totalOriginalPrice += pros.price * pros.productCount
-                    if (pros.promotion && pros.promotion.type != 2 && pros.promotion.mode == 2) {
-                        if (_price >= pros.promotion.touchPrice) {
-                            _price = _price - pros.promotion.reducedPrice
-                            _reducedPrice += pros.promotion.reducedPrice
-                        }
-                        _totalPrice += _price
-                    } else {
-                        _reducedPrice = 0
-                        _totalPrice += pros.price * pros.productCount
-                    }
-                })
-                item.reducedPrice = _reducedPrice
-                item.totalOriginalPrice = _totalOriginalPrice
-                item.totalPrice = _totalPrice
+        // 获取勾选商品的id
+        getCheckedProductId() {
+            const cartIds = []
+            this.goodsList.forEach(shop => {
+                const ids = shop.productList.reduce((cartIds, prod) => {
+                    if (prod.productsChecked) cartIds.push(prod.cartId)
+                    return cartIds
+                }, [])
+                cartIds.push(...ids)
             })
+            if (this.isshowDelbtn) {
+                const ids = this.failureList.reduce((cartIds, prod) => {
+                    if (prod.productsChecked) cartIds.push(prod.cartId)
+                    return cartIds
+                }, [])
+                cartIds.push(...ids)
+            }
+            console.log(cartIds)
+            this.saveCartIds(cartIds)
         },
+        //计算总价格,每次调用此方法,将初始值为0,遍历价格并累加
         totalPeice() {
-            //计算总价格,每次调用此方法,将初始值为0,遍历价格并累加
-            let totalPrice = 0
-            let reducedPrice = 0
-            let originalPrice = 0
-            this.goodsList.forEach((item, index) => {
-                let supplierPrice = 0
-                let supplierReducedPrice = 0
-                item.totalprice = 0
-                item.reducedprice = 0
-                item.originalprice = 0
-                item.productList.forEach(pros => {
-                    if (pros.productsChecked) {
-                        supplierPrice += pros.price * pros.productCount
-                        // 单品满减
-                        if (pros.promotion && pros.promotion.type * 1 === 1 && pros.promotion.mode * 1 === 2) {
-                            // 单品满减-重新计算供应商总价/满减金额
-                            if (pros.price * pros.productCount >= pros.promotion.touchPrice) {
-                                supplierPrice -= pros.promotion.reducedPrice
-                                supplierReducedPrice += pros.promotion.reducedPrice
+            const priceObj = this.goodsList.reduce(
+                (priceObj, shop) => {
+                    shop.productList.forEach(prod => {
+                        if (prod.productsChecked) {
+                            priceObj.totalOriginalPrice += prod.price * prod.productCount
+                            // 单品满减
+                            if (prod.promotion && prod.promotion.type * 1 === 1 && prod.promotion.mode * 1 === 2) {
+                                // 单品满减-重新计算供应商总价/满减金额
+                                if (prod.price * prod.productCount >= prod.promotion.touchPrice) {
+                                    priceObj.reducedPrice += prod.promotion.reducedPrice
+                                }
                             }
                         }
-                    }
-                })
-                item.totalprice = supplierPrice
-                item.reducedprice = supplierReducedPrice
-                item.originalprice = supplierPrice + supplierReducedPrice
-                totalPrice += item.totalprice
-                reducedPrice += item.reducedprice
-                originalPrice += item.originalprice
-            })
-            //最后统计商品原价
-            this.totalOriginalPrice = originalPrice
-            //最后满减金额 = 店铺减去金额 + 单品减去金额 + 凑单减去金额
-            this.reducedPrice = reducedPrice
-            //最终合计价格 = 	店铺满减合计 + 单品满减  + 正常合计 + 凑单满减
-            this.allPrice = totalPrice
-        },
-        totalCount() {
-            //计算总数量
-            this.allCount = 0
-            let prosAllCount = 0
-            let validCount = 0
-            let validList = []
-            let productList = []
-            this.goodsList.forEach(item => {
-                productList = item.productList
-                productList.forEach(pros => {
-                    if (pros.productsChecked) {
-                        prosAllCount += parseInt(pros.productCount)
-                        this.allCount = prosAllCount
-                    }
-                })
-            })
+                    })
+                    priceObj.allPrice = priceObj.totalOriginalPrice - priceObj.reducedPrice
+                    return priceObj
+                },
+                {
+                    totalOriginalPrice: 0,
+                    reducedPrice: 0,
+                    allPrice: 0
+                }
+            )
+            this.allPrice = priceObj.allPrice
         },
+        //商品数量加加
         changeCountAdd(item, pros) {
-            //商品数量加加
-            pros.productCount++
-            this.processActivityPrice(pros)
-            this.updateShoppogNum(pros)
-            this.totalShopPeice()
+            const productCount = pros.productCount + 1
+            this.updateShoppogCount({
+                cartId: pros.cartId,
+                productCount
+            })
         },
+        //商品数量减减
         changeCountSub(item, pros) {
-            //商品数量减减
-            if (pros.productCount <= 1) {
-                pros.productCount = 1
+            let productCount = pros.productCount
+            if (productCount <= 1) {
+                productCount = 1
                 this.$util.msg('购买数量不能少于1', 2000)
                 return
             } else {
-                pros.productCount--
+                productCount--
             }
-            this.processActivityPrice(pros)
-            this.updateShoppogNum(pros)
-            this.totalShopPeice()
-        },
-        changeInput(pros) {
-            //输入商品数量更新
+            this.updateShoppogCount({
+                cartId: pros.cartId,
+                productCount
+            })
         },
-        changeNnmber(e, item, pros) {
-            //输入商品数量更新
-            let _value = Number(e.detail.value)
-            if (!this.$api.isNumber(_value)) {
-                pros.productCount = 1
-            } else if (_value <= 1) {
+        //输入商品数量更新
+        changeInput(pros) {},
+        //输入商品数量更新
+        changeNumber(e, item, pros) {
+            let _value = Math.abs(Number(e.detail.value))
+            let productCount = pros.productCount
+            if (_value <= 1) {
                 this.$util.msg('购买数量不能少于1', 2000)
-                pros.productCount = 1
-            } else {
-                pros.productCount = e.detail.value
-            }
-            this.processActivityPrice(pros)
-            this.updateShoppogNum(pros)
-            this.totalShopPeice()
-        },
-        processActivityPrice(pros) {
-            //单独处理活动价格和阶梯价格
-            if (pros.activeStatus == 1) {
-                pros.ladderList.forEach((item, index) => {
-                    if (pros.productCount >= item.buyNum) {
-                        pros.price = item.buyPrice
-                    }
-                })
+                productCount = 1
             } else {
-                pros.price = pros.price
+                productCount = _value
             }
-        },
-        updateShoppogNum(pros) {
-            //加减购物车商品更新到后台
-            this.ProductService.ShoppingCartUpdate({
+            this.updateShoppogCount({
                 cartId: pros.cartId,
-                productCount: pros.productCount
-            })
-                .then(response => {
-                    this.isshowDelbtn = false
-                    this.InitGetCartGoodsList()
-                })
-                .catch(error => {
-                    this.$util.msg(error.msg, 2000)
-                })
-        },
-        toConfirmation() {
-            //跳转确认订单页面
-            let setGoodsList = []
-            this.goodsList.forEach(res => {
-                let products = res.productList
-                products.forEach(pros => {
-                    if (pros.productsChecked) {
-                        setGoodsList.push(pros.productId)
-                    }
-                })
+                productCount
             })
-            if (setGoodsList == '') {
-                this.$util.msg('请先选择结算商品~', 2000)
-                return
-            }
-            let cartIds = ''
-            this.goodsList.forEach(el => {
-                //获取勾选的商品ID拼接字符串逗号隔开,最后一个逗号去掉
-                el.productList.forEach(pros => {
-                    if (pros.productsChecked) {
-                        cartIds += pros.cartId + ','
-                    }
-                })
-            })
-            let cartPramsData = {
-                allPrice: this.allPrice,
-                allCount: this.allCount,
-                cartIds: cartIds.substring(0, cartIds.lastIndexOf(',')),
-                productCount: ''
-            }
-            this.$api.navigateTo(`/pages/user/order/create-order?data=${JSON.stringify({ data: cartPramsData })}`)
         },
+        //显示删除商品管理
         showDelManager() {
-            //显示删除商品管理
             this.isshowDelbtn = true
-            if (this.isCheckAll) {
-                this.updateBothCheckBtn()
-            } else {
-                this.goodsList.forEach(item => {
-                    if (item.checked) {
-                        item.productList.forEach(pros => {
-                            pros.productsChecked = true
-                        })
-                    }
-                })
-                this.updateCheckAllBtn()
-            }
-            // 失效也被勾选
-            this.failureList.forEach(failureItem => {
-                if (failureItem.isFailureLayer) {
-                    failureItem.isFailureLayer = false
-                }
-            })
         },
+        //隐藏删除商品管理
         hideDelManage() {
-            //隐藏删除商品管理
+            this.selectAllFailure(false)
+            this.getCheckedProductId()
             this.isshowDelbtn = false
-            let isFailureLayer,
-                newFailureList = []
-            if (this.isCheckAll) {
-                this.updateBothCheckBtn()
-            } else {
-                // 失效商品取消勾选
-                this.goodsList.forEach(item => {
-                    if (item.isDisabled) {
-                        item.checked = false
-                    }
-                    item.productList.forEach(pros => {
-                        if (pros.validFlag == 3) {
-                            pros.productsChecked = false
-                        }
-                    })
-                })
-                this.updateCheckAllBtn()
-            }
-            this.failureList.forEach((failure, index) => {
-                if (failure.failureState == 1 || failure.failureState == 2) {
-                    isFailureLayer = true
-                } else {
-                    isFailureLayer = false
-                }
-                newFailureList.push(Object.assign({}, failure, { isFailureLayer: isFailureLayer }))
-            })
-            this.failureList = newFailureList
         },
+        //删除购物车商品
         deleteList() {
-            //删除购物车商品
-            this.delGoodsList = []
-            this.goodsList.forEach(delitem => {
-                let products = delitem.productList
-                products.forEach(pros => {
-                    if (pros.productsChecked) {
-                        this.delGoodsList += pros.cartId + ','
-                    }
-                })
-            })
-            this.failureList.forEach(failure => {
-                if (failure.productsChecked) {
-                    this.delGoodsList += failure.cartId + ','
-                }
-            })
-            if (this.delGoodsList.length == 0) {
-                this.$util.msg('请选择要删除的商品~', 2000)
-                return
+            if (this.cartIds.length <= 0) {
+                return this.$util.msg('请选择要删除的商品~', 2000)
             } else {
                 this.modal = true
                 this.contentModalText = '确定删除选中的商品吗?'
                 this.deleteType = 1
             }
         },
+        // 清空失效商品
         deletefailureList() {
-            this.delGoodsList = ''
-            this.failureList.forEach(failure => {
-                this.delGoodsList += failure.cartId + ','
-            })
             this.modal = true
             this.contentModalText = '确定清除所有失效商品吗?'
             this.deleteType = 2
         },
+        //从购物车移除商品
         handleClick(e) {
-            //用户操作订单
-            let index = e.index
-            if (index == 1) {
-                this.ProductService.ShoppingCartDelete({
-                    cartIds: this.delGoodsList
+            if (e.index !== 1) return (this.modal = false)
+            if (this.deleteType === 1) {
+                // 删除所有勾选的商品
+                this.removeFromCart().finally(() => {
+                    this.isshowDelbtn = false
+                })
+            } else {
+                //一键删除失效商品
+                this.removeFailureFromCart().finally(() => {
+                    this.isshowDelbtn = false
                 })
-                    .then(response => {
-                        this.$util.msg('删除成功', 2000)
-                        setTimeout(() => {
-                            this.isshowDelbtn = false
-                            this.InitGetCartGoodsList()
-                        }, 1000)
-                    })
-                    .catch(error => {
-                        this.$util.msg(error.msg, 2000)
-                    })
             }
             this.modal = false
         },
-        hideMobel() {
+        //跳转确认订单页面
+        toConfirmation() {
+            if (this.cartIds.length <= 0) {
+                return this.$util.msg('请先选择结算商品~', 2000)
+            }
+            let cartPramsData = {
+                allPrice: this.allPrice,
+                allCount: this.allCount,
+                cartIds: this.cartIds.join(','),
+                productCount: ''
+            }
+            this.$api.navigateTo(`/pages/user/order/create-order?data=${JSON.stringify({ data: cartPramsData })}`)
+        },
+        hideModal() {
             this.modal = false
         },
         navToListPage(item) {
-            this.isModallayer = true
             this.$api.navigateTo(`/pages/goods/product?productId=${item.productId}`)
         },
+        // 窗口高度-footer高度
+        setScrollHeight() {
+            const { windowHeight, pixelRatio } = uni.getSystemInfoSync()
+            setTimeout(() => {
+                const query = uni.createSelectorQuery().in(this)
+                query.selectAll('.footer').boundingClientRect()
+                query.exec(res => {
+                    this.windowHeight = windowHeight
+                    if (res[0][0]) {
+                        this.scrollHeight = windowHeight - res[0][0].height
+                    }
+                })
+            }, 500)
+        },
         setHeaderBtnPosi() {
             // 获得胶囊按钮位置信息
             let headerBtnPosi = uni.getMenuButtonBoundingClientRect()
@@ -746,39 +535,6 @@ export default {
                 }
             })
             return systeminfo
-        },
-        PromotionsFormat(promo) {
-            //促销活动类型数据处理
-            if (promo != null) {
-                if (promo.type == 1 && promo.mode == 1) {
-                    return true
-                } else {
-                    return false
-                }
-            }
-            return false
-        }
-    },
-    watch: {
-        //深度监听所有数据,每次改变重新计算总价和总数
-        goodsList: {
-            deep: true,
-            handler(val, oldval) {
-                this.totalPeice()
-                this.totalCount()
-            }
-        }
-    },
-    onPullDownRefresh() {
-        //下拉刷新
-        this.InitGetCartGoodsList()
-        uni.stopPullDownRefresh()
-    },
-    onShow() {
-        if (this.hasLogin) {
-            this.initData()
-        } else {
-            this.$api.redirectTo('/pages/login/login')
         }
     }
 }

+ 1 - 32
pages/goods/good-floorMore.vue

@@ -122,39 +122,8 @@ export default {
         },
         // 添加到购物车
         handAddCarts(pro) {
-            if (!this.hasLogin) {
-                this.$api.navigateTo(`/pages/login/login`)
-            } else {
-                this.ProductService.shoppingAddCart({
-                    productId: pro.productId,
-                    userId: this.userId,
-                    productCount: 1,
-                    heUserId: 0
-                })
-                    .then(response => {
-                        this.$util.msg('加入购物车成功', 1500, true, 'success')
-                        this.GetCartNumber()
-                    })
-                    .catch(error => {
-                        this.$util.msg(error.msg, 2000)
-                    })
-            }
+            this.addToCart({ productId: pro.productId })
         },
-        //查询购物车数量
-        GetCartNumber() {
-            this.ProductService.QueryShoppingQuantity({
-                userId: this.userId
-            })
-                .then(response => {
-                    this.$store.commit('app/updateAllNum', response.data)
-                })
-                .catch(error => {
-                    console.log('查询购物车数量错误信息', error)
-                })
-        }
-    },
-    onShow() {
-        this.GetCartNumber()
     },
     // 监听页面滚动事件
     onPageScroll(e) {

+ 18 - 93
pages/goods/product.vue

@@ -204,11 +204,11 @@
                             <view class="item-bt" @click="buyProductCart()">
                                 <text class="iconfont icon-gouwuche"></text> <text>购物车</text>
                                 <text
-                                    v-if="hasLogin && goodsData.cartCount > 0"
+                                    v-if="hasLogin && kindCount > 0"
                                     class="uni-badge uni-badge-error uni-small uni-badge--small icon-num"
-                                    :class="[goodsData.cartCount < 10 ? 'goleft' : '']"
+                                    :class="[kindCount < 10 ? 'goleft' : '']"
                                 >
-                                    {{ goodsData.cartCount >= 100 ? '99+' : goodsData.cartCount }}
+                                    {{ kindCount >= 100 ? '99+' : kindCount }}
                                 </text>
                                 <view class="animation-num" :class="isAnimation ? 'animation' : 'restion'">+1</view>
                             </view>
@@ -285,7 +285,7 @@
 </template>
 
 <script>
-import { mapGetters } from 'vuex'
+import { mapGetters, mapActions } from 'vuex'
 import HeaderProduct from '@/components/cm-module/headerNavbar/header-poduct' //自定义导航
 import cmPrice from '@/components/cm-module/productDetails/cm-price.vue' //价格显示
 import cmAttributes from '@/components/cm-module/productDetails/cm-attributes.vue' //规格信息
@@ -333,9 +333,7 @@ export default {
             isQuantity: false,
             disabled: false,
             tabCurrentIndex: 0,
-            userId: '',
             productId: 0,
-            userIdentity: 0, //用户类型
             goodsData: {}, //自定义数据
             product: {}, //采美
             productImage: [],
@@ -375,7 +373,7 @@ export default {
         this.getWinHeight()
     },
     computed: {
-        ...mapGetters(['hasLogin', 'isIphoneX'])
+        ...mapGetters(['hasLogin', 'isIphoneX', 'kindCount', 'userIdentity', 'userId'])
     },
     filters: {
         NumFormat(value) {
@@ -385,13 +383,13 @@ export default {
         }
     },
     methods: {
+        ...mapActions('cart', ['addToCart', 'getCartNumber']),
         initData() {
             // 初始化商品详情查询
             this.ProductService.QueryProductDetils({
                 productId: this.productId
             })
                 .then(response => {
-                    //购物车数量
                     this.skeletonShow = false
                     this.productImage = []
                     this.product = response.data
@@ -420,7 +418,7 @@ export default {
                     }, 2000)
                     console.log(this.userId)
                     if (this.userId > 0) {
-                        this.GetCartNumber()
+                        this.getCartNumber()
                     }
                     this.isRequest = true
                 })
@@ -428,19 +426,6 @@ export default {
                     this.$util.msg(error.msg, 2000)
                 })
         },
-        GetCartNumber() {
-            //查询购物车数量
-            this.ProductService.QueryShoppingQuantity({
-                userId: this.userId
-            })
-                .then(response => {
-                    this.goodsData.cartCount = response.data
-                    this.$store.commit('app/updateAllNum', response.data)
-                })
-                .catch(error => {
-                    console.log('查询购物车数量错误信息', error)
-                })
-        },
         swiperChange(e) {
             //顶部商品图片切换
             const index = e.detail.current
@@ -556,7 +541,11 @@ export default {
         btnConfirm() {
             //加入购物车&&立即购买跳转订单页并关闭弹窗
             if (this.isBtnType == 'add') {
-                this.getAddProductCart()
+                this.addToCart({
+                    productId: this.productId,
+                    productCount: this.number
+                })
+                this.specClass = 'hide'
             } else {
                 this.toConfirmation()
             }
@@ -577,43 +566,6 @@ export default {
                 this.specClass = 'none'
             }, 200)
         },
-        getAddProductCart() {
-            //增加购物车成功和toast弹窗提示成功
-            this.ProductService.shoppingAddCart({
-                productId: this.productId,
-                userId: this.userId,
-                productCount: this.number,
-                heUserId: 0
-            })
-                .then(response => {
-                    this.specClass = 'hide'
-                    this.$util.msg('加入购物车成功', 1500, true, 'success')
-                    this.isAnimation = true
-                    setTimeout(() => {
-                        this.specClass = 'none'
-                    }, 200)
-                    setTimeout(() => {
-                        this.isAnimation = false
-                    }, 2000)
-                    this.GetCartNumber()
-                })
-                .catch(error => {
-                    this.$util.msg(error.msg, 2000)
-                })
-        },
-
-        navToLogin() {
-            authorize
-                .checkLogin()
-                .then(res => {
-                    this.$store.commit('app/setLoginType', 8)
-                    this.$store.commit('app/setLoginproductId', this.productId)
-                    this.$api.navigateTo(`/pages/login/login?id=${this.productId}`)
-                })
-                .catch(err => {
-                    this.$api.navigateTo('/pages/authorization/authorization?type=1')
-                })
-        },
         setHeaderBtnPosi() {
             // 获得胶囊按钮位置信息
             let headerBtnPosi = uni.getMenuButtonBoundingClientRect()
@@ -669,7 +621,6 @@ export default {
                                 })
                             })
                             this.sectionPropsArr = sectionPropsArr
-                            console.log(this.sectionPropsArr)
                             this.sectionTopRangeArr = this.getSectionRange(sectionPropsArr)
                         })
                         .exec()
@@ -682,22 +633,6 @@ export default {
             for (let i = 0; i < arr.length; i++) {
                 sectionScrollTopList.push(`${arr[i].scrollTop}-${arr[i].scrollTop + arr[i].height}`)
             }
-            // for(let i = 0; i < arr.length; i++) {
-            // 	let thisScrollTop = arr[i].scrollTop;
-            // 	let thisHeight = arr[i].height;
-            // 	if(i < arr.length - 1) {
-            // 		let nextScrollTop = arr[i+1].scrollTop;
-            // 		if(i == 0) {
-            // 			sectionScrollTopList.push(`0-${thisScrollTop + thisHeight}`);
-            // 		} else if(i == arr.length - 1){
-            // 			sectionScrollTopList.push(`${thisScrollTop + thisHeight}-${nextScrollTop - this.winHeight}`);
-            // 		} else {
-            // 			sectionScrollTopList.push(`${thisScrollTop + thisHeight}-${nextScrollTop}`);
-            // 		}
-            // 	} else {
-            // 		sectionScrollTopList.push(`${thisScrollTop}-${thisScrollTop+500}`);
-            // 	}
-            // }
             return sectionScrollTopList
         },
         activeTab: debounce(
@@ -710,7 +645,6 @@ export default {
                             openInterval = Number(splitItem[0]),
                             closedInterval = Number(splitItem[1])
                         if (top >= openInterval && top < closedInterval) {
-                            console.log(top)
                             _this.tabCurrentIndex = index
                         }
                     })
@@ -764,21 +698,12 @@ export default {
         }
     },
     onShow() {
-        this.$api
-            .getStorage()
-            .then(resolve => {
-                this.userId = resolve.userId ? resolve.userId : ''
-                this.userIdentity = resolve.userIdentity ? resolve.userIdentity : 0
-                if (isPreviewImg) {
-                    isPreviewImg = false
-                    return
-                } else {
-                    this.initData()
-                }
-            })
-            .catch(error => {
-                this.initData()
-            })
+        if (isPreviewImg) {
+            isPreviewImg = false
+            return
+        } else {
+            this.initData()
+        }
     }
 }
 </script>

+ 1 - 17
pages/goods/search.vue

@@ -242,23 +242,7 @@ export default {
                 })
         },
         handAddCarts(pro) {
-            if (!this.hasLogin) {
-                this.$api.navigateTo('/pages/login/login')
-            } else {
-                this.ProductService.shoppingAddCart({
-                    productId: pro.productId,
-                    userId: this.listQuery.userId,
-                    productCount: 1,
-                    heUserId: 0
-                })
-                    .then(response => {
-                        this.$util.msg('加入购物车成功', 1500, true, 'success')
-                        this.GetCartNumber()
-                    })
-                    .catch(error => {
-                        this.$util.msg(error.msg, 2000)
-                    })
-            }
+            this.addToCart({ productId: pro.productId })
         },
         onShowClose() {
             //输入框输入时触发

+ 26 - 25
pages/login/login.vue

@@ -50,7 +50,7 @@
 <script>
 import authorize from '@/common/authorize.js'
 import wxLogin from '@/services/wxLogin.js'
-import { mapGetters, mapMutations } from 'vuex'
+import { mapGetters, mapActions  } from 'vuex'
 export default {
     data() {
         return {
@@ -72,12 +72,14 @@ export default {
             isLoginStatus: false
         }
     },
-    onLoad(option) {},
-    computed: {
-        ...mapGetters(['isWxAuthorize'])
+    onLoad() {
+        if(this.hasLogin) return this.$api.switchTabTo('/pages/tabBar/index/index')
+    },
+    computed:{
+        ...mapGetters(['hasLogin'])
     },
     methods: {
-        ...mapMutations('app', ['login', 'wxLogin', 'updateStatus']),
+        ...mapActions('user', ['customLogin']),
         // 登录
         SubMitLogins() {
             // const WechatInfo = uni.getStorageSync('wechatUserInfo')
@@ -118,23 +120,25 @@ export default {
             })
         },
         LoginGetUser() {
-            this.UserService.UserMobileLogin(this.params)
-                .then(response => {
-                    // 保存用户信息
-                    const _data = JSON.parse(response.data)
-                    this.login(_data)
-                    this.updateStatus(_data)
-                    // 登录成功提示
-                    this.$util.msg('登录成功', 1500, false, 'success')
-                    this.isLoginStatus = false
-                    setTimeout(() => {
-                        this.$api.switchTabTo('/pages/tabBar/index/index')
-                    }, 1500)
-                })
-                .catch(error => {
-                    this.$util.msg(error.msg, 2000)
-                    this.isLoginStatus = false
-                })
+            this.customLogin(this.params)
+            this.isLoginStatus = false
+            // this.UserService.UserMobileLogin(this.params)
+            //     .then(response => {
+            //         // 保存用户信息
+            //         const _data = JSON.parse(response.data)
+            //         this.login(_data)
+            //         this.updateStatus(_data)
+            //         // 登录成功提示
+            //         this.$util.msg('登录成功', 1500, false, 'success')
+            //         this.isLoginStatus = false
+            //         setTimeout(() => {
+            //             this.$api.switchTabTo('/pages/tabBar/index/index')
+            //         }, 1500)
+            //     })
+            //     .catch(error => {
+            //         this.$util.msg(error.msg, 2000)
+            //         this.isLoginStatus = false
+            //     })
         },
         GetMobileCodeFn() {
             //获取手机验证码
@@ -182,9 +186,6 @@ export default {
                 this.isMobileDisabled = true
             }
         }
-    },
-    onShow() {
-        wxLogin.wxLoginAuthorize()
     }
 }
 </script>

+ 200 - 474
pages/tabBar/cart/index.vue

@@ -33,7 +33,7 @@
                                 <view class="goods-pros" v-for="(pros, idx) in item.productList" :key="idx">
                                     <view class="goods-pros-t">
                                         <!--选择商品-->
-                                        <view class="checkbox-box" @click.stop="ischeck(item, pros)">
+                                        <view class="checkbox-box" @click.stop="checkProduct(item, pros)">
                                             <view
                                                 class="checkbox iconfont"
                                                 :class="[pros.productsChecked ? 'icon-xuanze' : 'icon-weixuanze']"
@@ -68,7 +68,7 @@
                                                             type="number"
                                                             maxlength="4"
                                                             v-model="pros.productCount"
-                                                            @blur="changeNnmber($event, item, pros)"
+                                                            @blur="changeNumber($event, item, pros)"
                                                             @focus="changeInput(pros)"
                                                         />
                                                         <view
@@ -177,7 +177,7 @@
         <tui-modal
             :show="modal"
             @click="handleClick"
-            @cancel="hideMobel"
+            @cancel="hideModal"
             :content="contentModalText"
             color="#333"
             :size="32"
@@ -194,7 +194,7 @@
 import authorize from '@/common/authorize.js'
 import activiPopup from '@/components/cm-module/productDetails/cm-activipopu'
 import modalLayer from '@/components/cm-module/modal-layer/modal-layer'
-import { mapGetters } from 'vuex'
+import { mapGetters, mapActions, mapMutations } from 'vuex'
 
 export default {
     components: {
@@ -205,33 +205,16 @@ export default {
         return {
             StaticUrl: this.$Static,
             CustomBar: this.CustomBar, // 顶部导航栏高度
-            userId: '',
             popupShow: false,
             handlerPros: {}, //监听单挑促销商品
-            failureList: [], //失效商品列表
-            goodsList: [], //购物车的商品
-            delGoodsList: '', //要删除的商品
-            setGoodData: '', //确认订单的商品
             isCheckAll: false, //是否全选
-            kindCount: 0, //购物车宝贝数量
             allPrice: 0, //所有价格
             totalOriginalPrice: 0, //所有原价价
             reducedPrice: 0, //满减
-            allCount: 0, //被选中的产品数量
-            isModallayer: false,
             skeletonShow: true,
             isshowDelbtn: false,
-            isDisabled: false, // 供应商/店铺全选是否禁用状态
-            isEmpty: false, //显示空购物车
             scrollHeight: 'auto',
-            nomoreText: '上拉显示更多',
             hasNextPage: false,
-            loadding: false,
-            pullUpOn: true,
-            pullFlag: true,
-            pageSize: 10,
-            pageNum: 1,
-            submitIds: [],
             modal: false,
             contentModalText: '',
             deleteType: 0
@@ -241,7 +224,20 @@ export default {
         this.setScrollHeight()
     },
     computed: {
-        ...mapGetters(['hasLogin', 'isIphoneX'])
+        ...mapGetters([
+            'hasLogin',
+            'isIphoneX',
+            'isEmpty',
+            'goodsList',
+            'failureList',
+            'kindCount',
+            'userId',
+            'cartIds'
+        ]),
+        //被选中的产品数量
+        allCount() {
+            return this.cartIds.length
+        }
     },
     filters: {
         NumFormat(value) {
@@ -253,526 +249,256 @@ export default {
             return (val * count).toFixed(2)
         }
     },
+    watch: {
+        //深度监听所有数据,每次改变重新计算总价和总数
+        goodsList: {
+            deep: true,
+            handler(val, oldval) {
+                this.totalPeice()
+            }
+        }
+    },
+    //下拉刷新
+    onPullDownRefresh() {
+        this.initCart().finally(() => {
+            setTimeout(() => {
+                uni.stopPullDownRefresh()
+            }, 2000)
+        })
+    },
+    onShow() {
+        if (this.hasLogin) {
+            this.initData()
+        } else {
+            this.$api.redirectTo('/pages/login/login')
+        }
+    },
+    onHide() {
+        this.saveCartIds([])
+    },
     methods: {
+        ...mapActions('cart', ['initCart', 'updateShoppogCount', 'removeFromCart', 'removeFailureFromCart']),
+        ...mapMutations('cart', [
+            'selectProduct',
+            'selectAllShopProduct',
+            'selectAllProduct',
+            'saveCartIds',
+            'selectFailure',
+            'selectAllFailure'
+        ]),
         initData() {
-            this.isModallayer = false //遮罩层 防止多次点击
-            this.isCheckAll = false //是否全选
-            this.submitIds = []
-            this.$api.getStorage().then(resolve => {
-                this.userId = resolve.userId ? resolve.userId : 0
-                this.InitGetCartGoodsList()
-                this.GetCartNumber()
+            this.initCart().finally(() => {
+                this.skeletonShow = false
             })
         },
+        // 活动价弹窗
         clickPopupShow(pros, type) {
             if (pros.ladderList.length > 0) {
                 this.popupShow = true
                 this.handlerPros = pros
             }
         },
-        setScrollHeight() {
-            // 窗口高度-footer高度
-            const { windowHeight, pixelRatio } = uni.getSystemInfoSync()
-            setTimeout(() => {
-                const query = uni.createSelectorQuery().in(this)
-                query.selectAll('.footer').boundingClientRect()
-                query.exec(res => {
-                    this.windowHeight = windowHeight
-                    if (res[0][0]) {
-                        this.scrollHeight = windowHeight - res[0][0].height
-                    }
-                })
-            }, 500)
-        },
-        InitGetCartGoodsList() {
-            //初始化购物车 index:1
-            this.ProductService.QueryShoppingCartList({ userId: this.userId })
-                .then(response => {
-                    this.skeletonShow = false
-                    let data = response.data
-                    this.kindCount = data.cartQuantity
-                    if (data.shopList.length > 0 || data.products.length > 0) {
-                        this.isEmpty = false
-                    } else {
-                        this.isEmpty = true
-                    }
-                    if (data.shopList && data.shopList.length > 0) {
-                        this.goodsList = data.shopList
-                        console.log(this.goodsList)
-                        this.totalShopPeice()
-                    } else {
-                        this.goodsList = []
-                    }
-                    if (data.products && data.products.length > 0) {
-                        this.failureList = data.products
-                    } else {
-                        this.failureList = []
-                    }
-                })
-                .catch(error => {
-                    this.$util.msg(error.msg, 2000)
-                })
-        },
+        // 勾选单个失效商品
         ischeckFailure(failure) {
-            failure.productsChecked = !failure.productsChecked
-            this.updateCheckAllBtn()
-        },
-        ischeck(item, pro) {
-            //为未选中的时候改变为true,反之为true
-            pro.productsChecked = !pro.productsChecked
-            if (pro.productsChecked) {
-                if (!this.submitIds.includes(pro.productID * 1)) {
-                    this.submitIds.push(pro.productID)
-                }
-            } else {
-                var lent = this.submitIds.indexOf(pro.productID * 1)
-                if (lent >= 0) {
-                    this.submitIds.splice(lent, 1)
-                }
-            }
-            this.updateProductCheckedAllBtn(item)
-            this.updateCheckAllBtn()
-        },
-        updateProductCheckedAllBtn(item) {
-            // 单独每个供应商的勾选判断
-            let productList = item.productList,
-                productsCheckedLength = 0,
-                disabledLength = 0
-            if (this.isshowDelbtn) {
-                productList.forEach(pros => {
-                    if (pros.productsChecked) {
-                        productsCheckedLength++
-                    }
-                })
-            } else {
-                productList.forEach(pros => {
-                    if (pros.productsChecked) {
-                        productsCheckedLength++
-                    }
-                })
-            }
-            item.checked = productsCheckedLength === productList.length
-        },
-        updateCheckAllBtn() {
-            // 全选勾选判断
-            let goodsCheckedLength = 0,
-                goodsList = this.goodsList,
-                failureList = this.failureList
-            goodsList.forEach(item => {
-                if (item.checked) {
-                    goodsCheckedLength++
-                }
+            this.selectFailure({
+                productId: failure.productId,
+                checked: !failure.productsChecked
             })
-            failureList.forEach(failureItem => {
-                if (failureItem.productsChecked) {
-                    goodsCheckedLength++
-                }
-            })
-            if (this.isshowDelbtn) {
-                this.isCheckAll = goodsCheckedLength === goodsList.length + failureList.length
-            } else {
-                this.isCheckAll = goodsCheckedLength === goodsList.length
-            }
+            this.getCheckedProductId()
         },
-        checkShop(item) {
-            //与单选商品类似
-            item.checked = !item.checked
-            this.setProductChecked(item)
-            this.updateCheckAllBtn()
+        // 勾选单个商品
+        checkProduct(shop, product) {
+            this.selectProduct({
+                shopId: shop.shopId,
+                productId: product.productId,
+                checked: !product.productsChecked
+            })
+            this.isSelectAll()
         },
-        setProductChecked(item) {
-            item.productList.forEach(pros => {
-                if (item.checked) {
-                    pros.productsChecked = true
-                    if (!this.submitIds.includes(pros.productId * 1)) {
-                        this.submitIds.push(pros.productId)
-                    }
-                } else {
-                    pros.productsChecked = false
-                    var lent = this.submitIds.indexOf(pros.productId * 1)
-                    if (lent >= 0) {
-                        this.submitIds.splice(lent, 1)
-                    }
-                }
+        // 勾选商店所有商品
+        checkShop(shop) {
+            this.selectAllShopProduct({
+                shopId: shop.shopId,
+                checked: !shop.checked
             })
+            this.isSelectAll()
         },
-        updateBothCheckBtn() {
+        // 勾选全部商品
+        checkAll() {
+            this.isCheckAll = !this.isCheckAll
+            this.selectAllProduct(this.isCheckAll)
+            // 删除商品的全选也要选中失效商品
             if (this.isshowDelbtn) {
-                // 当管理删除按钮出现时,失效的商品可被选择
-                this.goodsList.forEach(item => {
-                    item.checked = this.isCheckAll
-                    this.setProductChecked(item)
-                })
-                //删除按钮 全选包括失效商品勾选
-                this.failureList.forEach(failureItem => {
-                    failureItem.productsChecked = this.isCheckAll
-                })
-            } else {
-                this.goodsList.forEach(item => {
-                    item.checked = this.isCheckAll && !item.isDisabled
-                    this.setProductChecked(item)
-                })
+                this.selectAllFailure(this.isCheckAll)
             }
+            this.isSelectAll()
         },
-        checkAll() {
-            //全选方法内调用方法
-            this.isCheckAll = !this.isCheckAll
-            this.updateBothCheckBtn()
+        // 判断是否全选商品
+        isSelectAll() {
+            this.isCheckAll = this.goodsList.every(shop => shop.checked)
+            this.getCheckedProductId()
         },
-        totalShopPeice() {
-            //每次所属会所下的商品增减重新计算合计价格&减去含有下架的商品
-            let touchPrice = 0
-            let reducedPrice = 0 //商铺合计满减价
-            this.goodsList.map((item, index) => {
-                let _totalPrice = 0
-                let _reducedPrice = 0
-                let _totalOriginalPrice = 0
-                item.productList.forEach(pros => {
-                    let _price = pros.price * pros.productCount
-                    _totalOriginalPrice += pros.price * pros.productCount
-                    if (pros.promotion && pros.promotion.type != 2 && pros.promotion.mode == 2) {
-                        if (_price >= pros.promotion.touchPrice) {
-                            _price = _price - pros.promotion.reducedPrice
-                            _reducedPrice += pros.promotion.reducedPrice
-                        }
-                        _totalPrice += _price
-                    } else {
-                        _reducedPrice = 0
-                        _totalPrice += pros.price * pros.productCount
-                    }
-                })
-                item.reducedPrice = _reducedPrice
-                item.totalOriginalPrice = _totalOriginalPrice
-                item.totalPrice = _totalPrice
+        // 获取勾选商品的id
+        getCheckedProductId() {
+            const cartIds = []
+            this.goodsList.forEach(shop => {
+                const ids = shop.productList.reduce((cartIds, prod) => {
+                    if (prod.productsChecked) cartIds.push(prod.cartId)
+                    return cartIds
+                }, [])
+                cartIds.push(...ids)
             })
+            if (this.isshowDelbtn) {
+                const ids = this.failureList.reduce((cartIds, prod) => {
+                    if (prod.productsChecked) cartIds.push(prod.cartId)
+                    return cartIds
+                }, [])
+                cartIds.push(...ids)
+            }
+            console.log(cartIds)
+            this.saveCartIds(cartIds)
         },
+        //计算总价格,每次调用此方法,将初始值为0,遍历价格并累加
         totalPeice() {
-            //计算总价格,每次调用此方法,将初始值为0,遍历价格并累加
-            let totalPrice = 0
-            let reducedPrice = 0
-            let originalPrice = 0
-            this.goodsList.forEach((item, index) => {
-                let supplierPrice = 0
-                let supplierReducedPrice = 0
-                item.totalprice = 0
-                item.reducedprice = 0
-                item.originalprice = 0
-                item.productList.forEach(pros => {
-                    if (pros.productsChecked) {
-                        supplierPrice += pros.price * pros.productCount
-                        // 单品满减
-                        if (pros.promotion && pros.promotion.type * 1 === 1 && pros.promotion.mode * 1 === 2) {
-                            // 单品满减-重新计算供应商总价/满减金额
-                            if (pros.price * pros.productCount >= pros.promotion.touchPrice) {
-                                supplierPrice -= pros.promotion.reducedPrice
-                                supplierReducedPrice += pros.promotion.reducedPrice
+            const priceObj = this.goodsList.reduce(
+                (priceObj, shop) => {
+                    shop.productList.forEach(prod => {
+                        if (prod.productsChecked) {
+                            priceObj.totalOriginalPrice += prod.price * prod.productCount
+                            // 单品满减
+                            if (prod.promotion && prod.promotion.type * 1 === 1 && prod.promotion.mode * 1 === 2) {
+                                // 单品满减-重新计算供应商总价/满减金额
+                                if (prod.price * prod.productCount >= prod.promotion.touchPrice) {
+                                    priceObj.reducedPrice += prod.promotion.reducedPrice
+                                }
                             }
                         }
-                    }
-                })
-                item.totalprice = supplierPrice
-                item.reducedprice = supplierReducedPrice
-                item.originalprice = supplierPrice + supplierReducedPrice
-                totalPrice += item.totalprice
-                reducedPrice += item.reducedprice
-                originalPrice += item.originalprice
-            })
-            //最后统计商品原价
-            this.totalOriginalPrice = originalPrice
-            //最后满减金额 = 店铺减去金额 + 单品减去金额 + 凑单减去金额
-            this.reducedPrice = reducedPrice
-            //最终合计价格 = 	店铺满减合计 + 单品满减  + 正常合计 + 凑单满减
-            this.allPrice = totalPrice
-        },
-        totalCount() {
-            //计算总数量
-            this.allCount = 0
-            let prosAllCount = 0
-            let validCount = 0
-            let validList = []
-            let productList = []
-            this.goodsList.forEach(item => {
-                productList = item.productList
-                productList.forEach(pros => {
-                    if (pros.productsChecked) {
-                        prosAllCount += parseInt(pros.productCount)
-                        this.allCount = prosAllCount
-                    }
-                })
-            })
+                    })
+                    priceObj.allPrice = priceObj.totalOriginalPrice - priceObj.reducedPrice
+                    return priceObj
+                },
+                {
+                    totalOriginalPrice: 0,
+                    reducedPrice: 0,
+                    allPrice: 0
+                }
+            )
+            this.allPrice = priceObj.allPrice
         },
+        //商品数量加加
         changeCountAdd(item, pros) {
-            //商品数量加加
-            pros.productCount++
-            this.processActivityPrice(pros)
-            this.updateShoppogNum(pros)
-            this.totalShopPeice()
+            const productCount = pros.productCount + 1
+            this.updateShoppogCount({
+                cartId: pros.cartId,
+                productCount
+            })
         },
+        //商品数量减减
         changeCountSub(item, pros) {
-            //商品数量减减
-            if (pros.productCount <= 1) {
-                pros.productCount = 1
+            let productCount = pros.productCount
+            if (productCount <= 1) {
+                productCount = 1
                 this.$util.msg('购买数量不能少于1', 2000)
                 return
             } else {
-                pros.productCount--
+                productCount--
             }
-            this.processActivityPrice(pros)
-            this.updateShoppogNum(pros)
-            this.totalShopPeice()
-        },
-        changeInput(pros) {
-            //输入商品数量更新
+            this.updateShoppogCount({
+                cartId: pros.cartId,
+                productCount
+            })
         },
-        changeNnmber(e, item, pros) {
-            //输入商品数量更新
-            let _value = Number(e.detail.value)
-            if (!this.$api.isNumber(_value)) {
-                pros.productCount = 1
-            } else if (_value <= 1) {
+        //输入商品数量更新
+        changeInput(pros) {},
+        //输入商品数量更新
+        changeNumber(e, item, pros) {
+            let _value = Math.abs(Number(e.detail.value))
+            let productCount = pros.productCount
+            if (_value <= 1) {
                 this.$util.msg('购买数量不能少于1', 2000)
-                pros.productCount = 1
+                productCount = 1
             } else {
-                pros.productCount = e.detail.value
+                productCount = _value
             }
-            this.processActivityPrice(pros)
-            this.updateShoppogNum(pros)
-            this.totalShopPeice()
-        },
-        processActivityPrice(pros) {
-            //单独处理活动价格和阶梯价格
-            if (pros.activeStatus == 1) {
-                pros.ladderList.forEach((item, index) => {
-                    if (pros.productCount >= item.buyNum) {
-                        pros.price = item.buyPrice
-                    }
-                })
-            } else {
-                pros.price = pros.price
-            }
-        },
-        updateShoppogNum(pros) {
-            //加减购物车商品更新到后台
-            this.ProductService.ShoppingCartUpdate({
+            this.updateShoppogCount({
                 cartId: pros.cartId,
-                productCount: pros.productCount
+                productCount
             })
-                .then(response => {
-                    this.isshowDelbtn = false
-                    this.InitGetCartGoodsList()
-                })
-                .catch(error => {
-                    this.$util.msg(error.msg, 2000)
-                })
-        },
-        toConfirmation() {
-            //跳转确认订单页面
-            let setGoodsList = []
-            this.goodsList.forEach(res => {
-                let products = res.productList
-                products.forEach(pros => {
-                    if (pros.productsChecked) {
-                        setGoodsList.push(pros.productId)
-                    }
-                })
-            })
-            if (setGoodsList == '') {
-                this.$util.msg('请先选择结算商品~', 2000)
-                return
-            }
-            let cartIds = ''
-            this.goodsList.forEach(el => {
-                //获取勾选的商品ID拼接字符串逗号隔开,最后一个逗号去掉
-                el.productList.forEach(pros => {
-                    if (pros.productsChecked) {
-                        cartIds += pros.cartId + ','
-                    }
-                })
-            })
-            let cartPramsData = {
-                allPrice: this.allPrice,
-                allCount: this.allCount,
-                cartIds: cartIds.substring(0, cartIds.lastIndexOf(',')),
-                productCount: ''
-            }
-            this.$api.navigateTo(`/pages/user/order/create-order?data=${JSON.stringify({ data: cartPramsData })}`)
         },
+        //显示删除商品管理
         showDelManager() {
-            //显示删除商品管理
             this.isshowDelbtn = true
-            if (this.isCheckAll) {
-                this.updateBothCheckBtn()
-            } else {
-                this.goodsList.forEach(item => {
-                    if (item.checked) {
-                        item.productList.forEach(pros => {
-                            pros.productsChecked = true
-                        })
-                    }
-                })
-                this.updateCheckAllBtn()
-            }
-            // 失效也被勾选
-            this.failureList.forEach(failureItem => {
-                if (failureItem.isFailureLayer) {
-                    failureItem.isFailureLayer = false
-                }
-            })
         },
+        //隐藏删除商品管理
         hideDelManage() {
-            //隐藏删除商品管理
+            this.selectAllFailure(false)
+            this.getCheckedProductId()
             this.isshowDelbtn = false
-            let isFailureLayer,
-                newFailureList = []
-            if (this.isCheckAll) {
-                this.updateBothCheckBtn()
-            } else {
-                // 失效商品取消勾选
-                this.goodsList.forEach(item => {
-                    if (item.isDisabled) {
-                        item.checked = false
-                    }
-                    item.productList.forEach(pros => {
-                        if (pros.validFlag == 3) {
-                            pros.productsChecked = false
-                        }
-                    })
-                })
-                this.updateCheckAllBtn()
-            }
-            this.failureList.forEach((failure, index) => {
-                if (failure.failureState == 1 || failure.failureState == 2) {
-                    isFailureLayer = true
-                } else {
-                    isFailureLayer = false
-                }
-                newFailureList.push(Object.assign({}, failure, { isFailureLayer: isFailureLayer }))
-            })
-            this.failureList = newFailureList
         },
+        //删除购物车商品
         deleteList() {
-            //删除购物车商品
-            this.delGoodsList = []
-            this.goodsList.forEach(delitem => {
-                let products = delitem.productList
-                products.forEach(pros => {
-                    if (pros.productsChecked) {
-                        this.delGoodsList += pros.cartId + ','
-                    }
-                })
-            })
-            this.failureList.forEach(failure => {
-                if (failure.productsChecked) {
-                    this.delGoodsList += failure.cartId + ','
-                }
-            })
-            if (this.delGoodsList.length == 0) {
-                this.$util.msg('请选择要删除的商品~', 2000)
-                return
+            if (this.cartIds.length <= 0) {
+                return this.$util.msg('请选择要删除的商品~', 2000)
             } else {
                 this.modal = true
                 this.contentModalText = '确定删除选中的商品吗?'
                 this.deleteType = 1
             }
         },
+        // 清空失效商品
         deletefailureList() {
-            this.delGoodsList = ''
-            this.failureList.forEach(failure => {
-                this.delGoodsList += failure.cartId + ','
-            })
             this.modal = true
             this.contentModalText = '确定清除所有失效商品吗?'
             this.deleteType = 2
         },
+        //从购物车移除商品
         handleClick(e) {
-            //用户操作订单
-            let index = e.index
-            if (index == 1) {
-                this.ProductService.ShoppingCartDelete({
-                    cartIds: this.delGoodsList
+            if (e.index !== 1) return (this.modal = false)
+            if (this.deleteType === 1) {
+                // 删除所有勾选的商品
+                this.removeFromCart().finally(() => {
+                    this.isshowDelbtn = false
+                })
+            } else {
+                //一键删除失效商品
+                this.removeFailureFromCart().finally(() => {
+                    this.isshowDelbtn = false
                 })
-                    .then(response => {
-                        this.$util.msg('删除成功', 2000)
-                        setTimeout(() => {
-                            this.isshowDelbtn = false
-                            this.InitGetCartGoodsList()
-                        }, 1000)
-                    })
-                    .catch(error => {
-                        this.$util.msg(error.msg, 2000)
-                    })
-                    .finally(() => {
-                        this.GetCartNumber()
-                    })
             }
             this.modal = false
         },
-        hideMobel() {
-            this.modal = false
+        //跳转确认订单页面
+        toConfirmation() {
+            if (this.cartIds.length <= 0) {
+                return this.$util.msg('请先选择结算商品~', 2000)
+            }
+            let cartPramsData = {
+                allPrice: this.allPrice,
+                allCount: this.allCount,
+                cartIds: this.cartIds.join(','),
+                productCount: ''
+            }
+            this.$api.navigateTo(`/pages/user/order/create-order?data=${JSON.stringify({ data: cartPramsData })}`)
         },
-        GetCartNumber() {
-            //查询购物车数量
-            this.ProductService.QueryShoppingQuantity({
-                userId: this.userId
-            })
-                .then(response => {
-                    this.$store.commit('app/updateAllNum', response.data)
-                })
-                .catch(error => {
-                    console.log('查询购物车数量错误信息', error)
-                })
+        hideModal() {
+            this.modal = false
         },
         navToListPage(item) {
-            this.isModallayer = true
             this.$api.navigateTo(`/pages/goods/product?productId=${item.productId}`)
         },
-        setHeaderBtnPosi() {
-            // 获得胶囊按钮位置信息
-            let headerBtnPosi = uni.getMenuButtonBoundingClientRect()
-            return headerBtnPosi
-        },
-        setSysteminfo() {
-            let systeminfo
-            uni.getSystemInfo({
-                // 获取设备信息
-                success: res => {
-                    systeminfo = res
-                }
-            })
-            return systeminfo
-        },
-        PromotionsFormat(promo) {
-            //促销活动类型数据处理
-            if (promo != null) {
-                if (promo.type == 1 && promo.mode == 1) {
-                    return true
-                } else {
-                    return false
-                }
-            }
-            return false
-        }
-    },
-    watch: {
-        //深度监听所有数据,每次改变重新计算总价和总数
-        goodsList: {
-            deep: true,
-            handler(val, oldval) {
-                this.totalPeice()
-                this.totalCount()
-            }
-        }
-    },
-    onPullDownRefresh() {
-        //下拉刷新
-        this.InitGetCartGoodsList()
-        uni.stopPullDownRefresh()
-    },
-    onShow() {
-        if (this.hasLogin) {
-            this.initData()
-        } else {
-            this.$api.redirectTo('/pages/login/login')
+        // 窗口高度-footer高度
+        setScrollHeight() {
+            const { windowHeight, pixelRatio } = uni.getSystemInfoSync()
+            setTimeout(() => {
+                const query = uni.createSelectorQuery().in(this)
+                query.selectAll('.footer').boundingClientRect()
+                query.exec(res => {
+                    this.windowHeight = windowHeight
+                    if (res[0][0]) {
+                        this.scrollHeight = windowHeight - res[0][0].height
+                    }
+                })
+            }, 500)
         }
     }
 }

+ 16 - 85
pages/tabBar/index/index.vue

@@ -77,14 +77,14 @@
             </view>
         </view>
         <!-- 侧边 -->
-        <scroll-top :isScrollTop="isScrollTop" :bottom="160"></scroll-top> 
+        <scroll-top :isScrollTop="isScrollTop" :bottom="160"></scroll-top>
     </view>
-</template> 
+</template>
 
 <script>
 import authorize from '@/common/authorize.js'
 import banner from '@/components/cm-module/homeIndex/banner.vue'
-import { mapGetters, mapMutations } from 'vuex' 
+import { mapGetters, mapMutations, mapActions } from 'vuex'
 export default {
     components: {
         banner
@@ -109,10 +109,8 @@ export default {
             screenWidth: this.screenWidth,
             capsule: this.capsule,
             platformClass: this.platformClass,
-            userId: 0,
             modallayer: false,
             skeletonShow: true,
-            userIdentity: '',
             productFloor: [], //商品列表
             bannerImageList: [], //轮播
             pageNum: 1,
@@ -128,38 +126,20 @@ export default {
             return Number(text).toFixed(2)
         }
     },
-    onLoad() {
+    async onLoad() {
         this.modallayer = false
-        this.InitAuthorize()
+        this.wechatlogin()
+        this.GetHomeBanner()
+        this.GetHomeProductList()
     },
     computed: {
-        ...mapGetters(['hasLogin'])
+        ...mapGetters(['hasLogin', 'userIdentity', 'userId'])
     },
     methods: {
-        ...mapMutations('app', ['login', 'logout']),
-        async GetWxAuthorize() {
-            const wechatCode = await authorize.getCode('weixin') // 根据微信的code获取用户登录状态:1已登录过 -1未登录过
-            this.UserService.UserWechatAuthorLogin({ code: wechatCode })
-                .then(response => {
-                    const _data = JSON.parse(response.data)
-                    uni.setStorageSync('openId', _data.openId)
-                    this.userId = _data.userId
-                    this.userIdentity = _data.userIdentity
-                    this.$store.commit('app/updateStatus', _data)
-                    this.login(_data)
-                    this.GetHomeBanner()
-                    this.GetHomeProductList()
-                })
-                .catch(error => {
-                    console.log(error)
-                    const _data = JSON.parse(error.data)
-                    this.logout()
-                    this.$store.commit('app/updateStatus', _data)
-                    uni.setStorageSync('openId', _data.openId)
-                    this.GetHomeBanner()
-                    this.GetHomeProductList()
-                })
-        },
+        ...mapMutations('app', ['login', 'logout', 'updateStatus']),
+        ...mapActions('user', ['wechatlogin']),
+        ...mapActions('cart', ['addToCart', 'getCartNumber']),
+
         GetHomeBanner() {
             //初始化首页数据
             this.CommonService.GetProductCarousel()
@@ -177,14 +157,12 @@ export default {
             this.ProductService.QueryProductFloor()
                 .then(response => {
                     this.productFloor = response.data
-                    this.GetCartNumber()
                 })
                 .catch(error => {
                     this.$util.msg(error.msg, 2000)
                 })
         },
         NavToDetailPage(floor) {
-            console.log('跳转')
             //跳转
             this.$api.navigateTo(`/pages/goods/good-floorMore?floorId=${floor.floorId}&title=${floor.title}`)
         },
@@ -192,50 +170,7 @@ export default {
             this.$api.navigateTo(`/pages/goods/product?productId=${pro.productId}`)
         },
         handAddCarts(pro) {
-            if (!this.hasLogin) {
-                this.$api.navigateTo('/pages/login/login')
-            } else {
-                this.ProductService.shoppingAddCart({
-                    productId: pro.productId,
-                    userId: this.userId,
-                    productCount: 1,
-                    heUserId: 0
-                })
-                    .then(response => {
-                        this.$util.msg('加入购物车成功', 1500, true, 'success')
-                        this.GetCartNumber()
-                    })
-                    .catch(error => {
-                        this.$util.msg(error.msg, 2000)
-                    })
-            }
-        },
-        GetCartNumber() {
-            //查询购物车数量
-            this.ProductService.QueryShoppingQuantity({
-                userId: this.userId
-            })
-                .then(response => {
-                    this.$store.commit('app/updateAllNum', response.data)
-                })
-                .catch(error => {
-                    console.log('查询购物车数量错误信息', error)
-                })
-        },
-        handleClick(data) {
-            this.$api.navigateTo('/h5/pages/activity/meobohui')
-            this.$store.commit('app/setActivity', data)
-            uni.setStorageSync('lockTime', Date.now())
-            uni.setStorageSync('isActivityStatus', true)
-        },
-        handleCancelClick(data) {
-            this.$store.commit('app/setActivity', data)
-            uni.setStorageSync('lockTime', Date.now())
-            uni.setStorageSync('isActivityStatus', true)
-        },
-        InitAuthorize() {
-            //是否已授权 0:为取消授权 1:为已授权 2:为未操作
-            this.GetWxAuthorize()
+            this.addToCart({ productId: pro.productId })
         }
     },
     onPageScroll(e) {
@@ -259,12 +194,6 @@ export default {
             uni.stopPullDownRefresh()
         }, 2000)
     },
-    // onReachBottom() {
-    // 	console.log("用户把这个页面上拉100时触发我的")
-    // 	if(this.hasNextPage){
-    // 		this.GetOnReachBottomProductList()
-    // 	}
-    // },
     onShareAppMessage(res) {
         //分享转发
         if (res.from === 'button') {
@@ -277,7 +206,9 @@ export default {
         }
     },
     onShow() {
-        this.GetCartNumber()
+        if(this.hasLogin){
+            this.getCartNumber()
+        }
     }
 }
 </script>

+ 18 - 29
pages/tabBar/user/index.vue

@@ -11,12 +11,12 @@
                         :src="StaticUrl + 'icon-default-avatar.png'"
                         mode="widthFix"
                     ></image>
-                    <image class="user_default" v-else :src="UserInfo.headImgUrl" mode="widthFix"></image>
+                    <image class="user_default" v-else :src="userInfo.headImgUrl" mode="widthFix"></image>
                     <view class="user-login" v-if="!hasLogin && isRequest" @click="navigator('/pages/login/login')"
                         >登录</view
                     >
                     <view class="user-text" v-else>
-                        {{ UserInfo.userIdentity == 1 ? UserInfo.nickName : UserInfo.name }}
+                        {{ userIdentity == 1 ? userInfo.nickName : userInfo.name }}
                     </view>
                 </view>
                 <!-- 背景图 -->
@@ -66,7 +66,7 @@
                 <view
                     class="place-menu-cell"
                     @click="navigator('/pages/user/activity/activity-list')"
-                    v-if="UserInfo.userIdentity == 2"
+                    v-if="userIdentity == 2"
                 >
                     <view class="place-left">
                         <image class="place-menu-icon" :src="StaticUrl + 'icon-user-h@2x.png'" mode=""></image>
@@ -91,7 +91,7 @@
             </view>
             <!-- 菜单导航区域END -->
             <!-- 底部 -->
-            <view class="user-support" :class="UserInfo.userIdentity == 2 ? 'top' : ''">
+            <view class="user-support" :class="userIdentity == 2 ? 'top' : ''">
                 <image class="user-support-image" :src="StaticUrl + 'icon-logo@1x.png'" mode=""></image>
                 <view class="user-support-text">采美365网提供商品技术服务</view>
             </view>
@@ -113,44 +113,27 @@ export default {
         return {
             StaticUrl: this.$Static,
             CustomBar: this.CustomBar, // 顶部导航栏高度
-            UserInfo: {}, //用户信息
             isRequest: true,
             paymentCount: 0, //待付款角标
             waitShipmentsCount: 0, //待收货角标
             shipmentsCount: 0, //已发货角标
             salesReturnCount: 0, //退货/款角标
-            userId: 0
         }
     },
-    onLoad() {},
+    onLoad() {
+        if (!this.hasLogin) return
+        this.GetUserInfoPersonal()
+    },
     computed: {
-        ...mapGetters(['hasLogin', 'userInfo', 'isWxAuthorize'])
+        ...mapGetters(['hasLogin', 'userInfo','userId','userIdentity'])
     },
     filters: {
         countNum(value) {
             return value > 99 ? '99+' : value
         }
     },
-    onPullDownRefresh() {
-        //下拉刷新
-        if (this.hasLogin) {
-            this.GetUserInfo()
-            setTimeout(() => {
-                uni.stopPullDownRefresh()
-            }, 2000)
-        } else {
-            uni.stopPullDownRefresh()
-        }
-    },
     methods: {
         ...mapMutations('app', ['login', 'logout']),
-        GetUserInfo() {
-            this.UserInfo = uni.getStorageSync('userInfo')
-            this.$api.getStorage().then(resolve => {
-                this.userId = resolve.userId ? resolve.userId : ''
-                this.GetUserInfoPersonal()
-            })
-        },
         //初始化个人中心数据
         GetUserInfoPersonal() {
             this.UserService.GetUserOrderTotal({
@@ -175,7 +158,7 @@ export default {
         OrderNavigator(state) {
             // 栏目跳转
             if (this.hasLogin) {
-                if (this.UserInfo.userIdentity == 2) {
+                if (this.userIdentity == 2) {
                     this.$api.navigateTo(`/pages/user/order/order-list-retail?state=${state}`)
                 } else {
                     this.$api.navigateTo(`/pages/user/order/order-list?state=${state}`)
@@ -192,11 +175,17 @@ export default {
             }
         }
     },
-    onShow() {
+    onPullDownRefresh() {
+        //下拉刷新
         if (this.hasLogin) {
             this.GetUserInfo()
+            setTimeout(() => {
+                uni.stopPullDownRefresh()
+            }, 2000)
+        } else {
+            uni.stopPullDownRefresh()
         }
-    }
+    },
 }
 </script>
 

+ 1 - 31
pages/user/activity/activity.vue

@@ -110,36 +110,7 @@ export default {
             )
         },
         handAddCarts(pro) {
-            if (!this.hasLogin) {
-                this.$api.navigateTo('/pages/login/login')
-            } else {
-                this.ProductService.shoppingAddCart({
-                    productId: pro.productId,
-                    userId: this.UserId * 1,
-                    productCount: 1,
-                    heUserId: this.listQuery.userId * 1
-                })
-                    .then(response => {
-                        this.$util.msg('加入购物车成功', 1500, true, 'success')
-                        this.GetCartNumber()
-                    })
-                    .catch(error => {
-                        console.log('查询购物车数量错误信息', error)
-                    })
-            }
-        },
-        GetCartNumber() {
-            //查询购物车数量
-            this.ProductService.QueryShoppingQuantity({
-                userId: this.listQuery.userId
-            })
-                .then(response => {
-                    this.$store.commit('app/updateAllNum', response.data)
-                    this.cartNum = response.data
-                })
-                .catch(error => {
-                    console.log('查询购物车数量错误信息', error)
-                })
+            this.addToCart({ productId: pro.productId })
         },
         btnClick() {
             this.$emit('goCartPage')
@@ -166,7 +137,6 @@ export default {
         wxLogin.wxLoginQuick()
         this.$api.getStorage().then(resolve => {
             this.UserId = resolve.userId ? resolve.userId : ''
-            this.GetCartNumber()
         })
     },
     onShareAppMessage(res) {

+ 2 - 1
services/config.env.js

@@ -4,8 +4,9 @@ if (process.env.NODE_ENV === 'development') {
     // URL_CONFIG = 'http://192.168.2.75:8011'	 //采美测试地址
     // URL_CONFIG = 'http://192.168.2.67:8011'	 //裴裴联调地址
     // URL_CONFIG = 'http://192.168.2.68:8011'	 //涛涛联调地址
+    URL_CONFIG = 'http://127.0.0.1:8011'	 //涛涛联调地址
     // URL_CONFIG = 'https://mall2c-b.caimei365.com'
-    URL_CONFIG = 'https://mall2c.caimei365.com'
+    // URL_CONFIG = 'https://mall2c.caimei365.com'
 } else {
     // 生产环境
     URL_CONFIG = 'https://mall2c.caimei365.com'

+ 13 - 4
store/getters.js

@@ -1,11 +1,20 @@
 const getters = {
-    isWxAuthorize: state => state.app.isWxAuthorize,
-    hasLogin: state => state.app.hasLogin,
-    userInfo: state => state.app.userInfo,
-    cartNumber: state => state.app.cartNumber,
+    // 设备信息
     isIphoneX: state => state.app.isIphoneX,
     isIphone: state => state.app.isIphone,
     isActivity: state => state.app.isActivity,
+    // 用户授权
+    isWxAuthorize: state => state.user.isWxAuthorize,
+    userInfo: state => state.user.userInfo,
+    userId: state => state.user.userId,
+    userIdentity: state => state.user.userIdentity,
+    hasLogin: state => state.user.hasLogin,
+    // 购物车
+    kindCount: state => state.cart.kindCount,
+    failureList: state => state.cart.failureList,
+    goodsList: state => state.cart.goodsList,
+    isEmpty: state => state.cart.isEmpty,
+    cartIds: state => state.cart.cartIds,
 }
 
 export default getters

+ 0 - 21
store/modules/app.js

@@ -2,10 +2,6 @@ import authorize from '@/common/authorize.js'
 import { formatDate } from '@/common/utilsTools.js'
 
 const state = {
-    isWxAuthorize: false, //是否授权
-    hasLogin: false,
-    userInfo: {}, //登录用户信息
-    cartNumber: 0,
     isIphoneX: false,
     isIphone: false,
     isActivity: false
@@ -48,23 +44,6 @@ const mutations = {
             data: provider
         })
     },
-    updateAllNum(state, num) {
-        if (num >= 100) {
-            uni.setTabBarBadge({
-                index: 1,
-                text: '99+'
-            })
-        } else if (num > 0) {
-            uni.setTabBarBadge({
-                index: 1,
-                text: String(num)
-            })
-        } else {
-            uni.removeTabBarBadge({
-                index: 1,
-            })
-        }
-    },
     setActivity(state, variable) {
         state.isActivity = variable
     },

+ 212 - 21
store/modules/cart.js

@@ -1,43 +1,234 @@
-import { productService } from '@/services/product.service.js'
+import { productService } from '@/services/index.js'
+import { msg as showMsg } from '@/common/util.js'
+import { navigateTo } from '@/common/utilsTools.js'
+
+// 计算价格
+function totalShopPeice(goodsList) {
+    return goodsList.map((item, index) => {
+        const priceObj = item.productList.reduce((price, pros, i) => {
+            // 处理阶梯价
+            if (pros.activeStatus == 1) {
+                pros.ladderList.forEach((item, index) => {
+                    if (pros.productCount >= item.buyNum) pros.price = item.buyPrice
+                })
+            } else {
+                pros.price = pros.price
+            }
+            // 计算每个商品下商品的价格
+            let _price = pros.price * pros.productCount
+            price.totalOriginalPrice += _price
+            if (pros.promotion && pros.promotion.type != 2 && pros.promotion.mode == 2) {
+                if (_price >= pros.promotion.touchPrice) {
+                    _price = _price - pros.promotion.reducedPrice
+                    price.reducedPrice += pros.promotion.reducedPrice
+                }
+                price.totalPrice += _price
+            } else {
+                price.reducedPrice = 0
+                price.totalPrice += pros.price * pros.productCount
+            }
+            return price
+        }, {
+            totalPrice: 0,
+            reducedPrice: 0,
+            totalOriginalPrice: 0
+        })
+        item.totalPrice = priceObj.totalPrice
+        item.reducedPrice = priceObj.reducedPrice
+        item.totalOriginalPrice = priceObj.totalOriginalPrice
+        return item
+    })
+}
 
 const state = {
+    isEmpty: true,
     goodsList: [], //购物车的商品
     failureList: [], //失效商品列表
-    kindCount: 0 ,//购物车宝贝数量
+    cartIds: [], // 已勾选商品cartId列表
+    kindCount: 0,
 }
 
 const mutations = {
-    setKindCount(state, data) {
-        state.kindCount = data
+    // 设置购物车商品数量
+    setKindCount(state, count) {
+        state.kindCount = count
     },
-    setGoodsList(state, data) {
-        state.goodsList = data
+    // 设置购物车有效商品
+    setGoodsList(state, list) {
+        state.goodsList = list
     },
-    setFailureList(state, data) {
-        state.failureList = data
+    // 设置购物车失效商品
+    setFailureList(state, list) {
+        state.failureList = list
+    },
+    // 设置购物车是否为空
+    setEmptyType(state, flag) {
+        state.isEmpty = flag
+    },
+    saveCartIds(state, ids) {
+        state.cartIds = ids
+    },
+    // 勾选/不勾选 失效商品
+    selectFailure(state, { productId, checked }) {
+        state.failureList.forEach(prod => {
+            if (prod.productId === productId) prod.productsChecked = checked
+        })
+    },
+    // 勾选/取消勾选所有失效商品
+    selectAllFailure(state, checked) {
+        state.failureList.forEach(prod => {
+            prod.productsChecked = checked
+        })
+    },
+    // 重选商品
+    resetSelectProducts(state, cartIds = []) {
+        state.goodsList.forEach((shop) => {
+            shop.productList.forEach(prod => {
+                if (cartIds.includes(prod.cartId)) prod.productsChecked = true
+            })
+            shop.checked = shop.productList.every((prod) => prod.productsChecked === true)
+        })
+    },
+    // 勾选商品
+    selectProduct(state, { shopId, productId, checked }) {
+        state.goodsList.forEach((shop) => {
+            if (shop.shopId !== shopId) return
+            shop.productList.forEach(prod => {
+                if (prod.productId !== productId) return
+                prod.productsChecked = checked
+            })
+            shop.checked = shop.productList.every((prod) => prod.productsChecked === true)
+        })
+    },
+    // 全选/全不选 供应商下所有商品
+    selectAllShopProduct(state, { shopId, checked }) {
+        state.goodsList.forEach((shop) => {
+            if (shop.shopId !== shopId) return
+            shop.checked = checked
+            shop.productList.forEach(prod => {
+                prod.productsChecked = checked
+            })
+        })
+    },
+    // 全选/全不选 部商品
+    selectAllProduct(state, checked) {
+        state.goodsList.forEach((shop) => {
+            shop.checked = checked
+            shop.productList.forEach(prod => {
+                prod.productsChecked = checked
+            })
+        })
+    },
+    // 设置购物车商品数量角标
+    setTabBarBadge(state, num) {
+        if (num >= 100) {
+            uni.setTabBarBadge({
+                index: 1,
+                text: '99+'
+            })
+        } else if (num > 0) {
+            uni.setTabBarBadge({
+                index: 1,
+                text: String(num)
+            })
+        } else {
+            uni.removeTabBarBadge({
+                index: 1,
+            })
+        }
     },
-    totalPeice(){
-        
-    }
 }
 
-const action = {
+const actions = {
     // 初始化购物车
-    initCart({ commit }) {
-        
+    initCart({ rootGetters, commit, state }) {
+        return productService.QueryShoppingCartList({ userId: rootGetters.userId })
+            .then(response => {
+                let data = response.data
+                commit('setTabBarBadge', data.cartQuantity)
+                commit('setKindCount', data.cartQuantity)
+                if (data.shopList.length > 0 || data.products.length > 0) {
+                    commit('setEmptyType', false)
+                } else {
+                    commit('setEmptyType', true)
+                }
+                if (data.shopList && data.shopList.length > 0) {
+                    commit('setGoodsList', totalShopPeice(data.shopList))
+                    commit('resetSelectProducts', state.cartIds) // 勾选已选商品
+                } else {
+                    commit('setGoodsList', [])
+                }
+                if (data.products && data.products.length > 0) {
+                    commit('setFailureList', data.products)
+                } else {
+                    commit('setFailureList', [])
+                }
+            })
+            .catch(error => {
+                showMsg(error.msg, 2000)
+            })
+    },
+    // 获取购物车商品数量
+    getCartNumber({ commit, rootGetters }) {
+        productService.QueryShoppingQuantity({ userId: rootGetters.userId  })
+            .then(response => {
+                commit('setTabBarBadge', response.data)
+                commit('setKindCount', response.data)
+            })
+            .catch(error => {
+                console.log('查询购物车数量错误信息', error)
+            })
     },
     // 添加购物车
-    addToCart({ dispatch }, data) {},
+    addToCart({ dispatch, rootGetters }, { productId, productCount = 1 }) {
+        if (!rootGetters.hasLogin) return navigateTo('/pages/login/login')
+        productService.shoppingAddCart({
+            productId,
+            userId: rootGetters.userId,
+            productCount,
+            heUserId: 0
+        }).then(response => {
+            showMsg('加入购物车成功', 1500, true, 'success')
+            dispatch('getCartNumber')
+        }).catch(error => {
+            showMsg(error.msg, 2000)
+        })
+    },
     // 从购物车移除
-    removeFromCart({ dispatch }, data) {},
-    // 添加商品数量
-    countAdd() {},
-    // 减少商品数量
-    countSub() {}
+    removeFromCart({ dispatch, state }, cartIds = []) {
+        // 从哪里获取cartIds
+        const removeCartIds = cartIds.length > 0 ? cartIds : state.cartIds
+        return productService.ShoppingCartDelete({
+            cartIds: removeCartIds.join(',')
+        }).then(response => {
+            dispatch('initCart')
+            showMsg('删除成功', 2000)
+        }).catch(error => {
+            showMsg(error.msg, 2000)
+        })
+    },
+    // 删除失效商品
+    removeFailureFromCart({ dispatch, state }) {
+        const cartIds = state.failureList.reduce((cartIds, prod) => {
+            cartIds.push(prod.cartId)
+            return cartIds
+        }, [])
+        return dispatch('removeFromCart', cartIds)
+    },
+    // 加减购物车商品更新到后台
+    updateShoppogCount({ dispatch, state }, { cartId, productCount }) {
+        productService.ShoppingCartUpdate({
+            cartId,
+            productCount
+        }).finally(() => {
+            dispatch('initCart')
+        })
+    }
 }
 
 export default {
+    namespaced: true,
     state,
     mutations,
-    action
+    actions
 }

+ 71 - 0
store/modules/user.js

@@ -0,0 +1,71 @@
+import { userService } from '@/services/index.js'
+import authorize from '@/common/authorize.js'
+import { msg as showMsg } from '@/common/util.js'
+import { switchTabTo } from '@/common/utilsTools.js'
+
+const state = {
+    userId: '',
+    userIdentity: '',
+    userInfo: null,
+    hasLogin: false,
+    isWxAuthorize: false,
+}
+const mutations = {
+    // 用户登录
+    LOGIN(state, data) {
+        const userInfo = JSON.parse(data)
+        state.userInfo = userInfo
+        state.hasLogin = true
+        state.isWxAuthorize = true
+        state.userId = userInfo.userId
+        state.userIdentity = userInfo.userIdentity
+        uni.setStorageSync('openId', userInfo.openId)
+    },
+    // 退出登录
+    LOGIN_OUT(state, data) {
+        const userInfo = JSON.parse(data) || null
+        state.userInfo = userInfo
+        state.hasLogin = false
+        state.isWxAuthorize = false
+        state.userId = ''
+        state.userIdentity = ''
+        userInfo && uni.setStorageSync('openId', userInfo.openId)
+    },
+}
+const actions = {
+    // 微信授权登录
+    async wechatlogin({ commit, dispatch, state }) {
+        // 获取code
+        const code = await authorize.getCode('weixin')
+        userService.UserWechatAuthorLogin({ code })
+            .then(response => {
+                commit('LOGIN', response.data)
+                dispatch('cart/getCartNumber', state.userId, { root: true })
+            })
+            .catch(error => {
+                commit('LOGIN_OUT', response.data)
+            })
+    },
+    // 手机号注册登录
+    async customLogin({ commit }, params) {
+        userService.UserMobileLogin(params)
+            .then(response => {
+                // 保存用户信息
+                commit('LOGIN', response.data)
+                // 登录成功提示
+                showMsg('登录成功', 1500, false, 'success')
+                setTimeout(() => {
+                    switchTabTo('/pages/tabBar/index/index')
+                }, 1500)
+            })
+            .catch(error => {
+                showMsg(error.msg, 2000)
+            })
+    }
+}
+export default {
+    namespaced: true,
+    state,
+    mutations,
+    actions
+}