/** * 取出优惠券列表中的最优优惠券和次优优惠券 * */ class CouponUtils { constructor(couponList, productList) { this.couponList = this.couponSort(this.getCanBeUseCouponList(couponList, productList)) this.productList = productList this.bestCoupon = null this.secondCoupon = null this.currentIndex = this.couponList.length this.fetchBestCoupon() } // 获取最高可用金额的优惠券 fetchBestCoupon() { if (this.couponList.length === 0 || this.productList.length === 0) { this.bestCoupon = null return } this.bestCoupon = this.couponList.find(coupon => this.couponCanBeUse(coupon, this.productList)) || null if (this.bestCoupon) { this.currentIndex = this.couponList.findIndex(coupon => coupon.uniqueId === this.bestCoupon.uniqueId) } this.fetchSecondCoupon() } // 获取下一阶段可用优惠券 fetchSecondCoupon() { if (this.couponList.length === 0 || this.productList.length === 0) { this.secondCoupon = null return } this.secondCoupon = this.currentIndex > 0 ? this.couponList[this.currentIndex - 1] : null } // 勾选商品满足优惠券使用条件 && 满足使用条件 couponCanBeUse(coupon, productList) { return ( this.isNoThreshold(coupon) || this.isSomeProductUse(coupon, productList) || this.isAllProductUse(coupon, productList) ) } // 获取当前选中商品都能使用的优惠券 getCanBeUseCouponList(couponList, productList) { return couponList.filter(coupon => coupon.productType === 1 || this.isCanUseByAllProduct(coupon, productList)) } // 全部商品可用 isCanUseByAllProduct(coupon, productList) { return productList.every(product => coupon.productIds.indexOf(product.productId.toString()) > -1) } // 优惠券是否无门槛 isNoThreshold(coupon) { return coupon.noThresholdFlag === 1 } // 全部商品可用 && 满足使用条件 isAllProductUse(coupon, productList) { if (coupon.productType !== 1) { return false } const countPrice = productList.reduce((countPrice, product) => { return countPrice + this.totalProductPrice(product) }, 0) return countPrice >= coupon.touchPrice } // 部分商品可用 && 满足使用条件 isSomeProductUse(coupon, productList) { if (coupon.productType !== 2) { return false } const countPrice = productList.reduce((countPrice, product) => { const isIncludes = coupon.productIds.indexOf(product.productId.toString()) > -1 return isIncludes ? countPrice + this.totalProductPrice(product) : countPrice }, 0) return countPrice >= coupon.touchPrice } // 统计商品价格 totalProductPrice(product) { return product.price * product.num } // 排序 couponSort(couponList) { return couponList.sort((a, b) => b.couponAmount - a.couponAmount) } } export default CouponUtils