cart.vue 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. <template>
  2. <view class="cart">
  3. <tui-skeleton v-if="isRequest" :loadingType="3" :isLoading="true"></tui-skeleton>
  4. <!-- 购物车列表为空 -->
  5. <template v-if="shopList.length === 0 && expiredProducts.length === 0">
  6. <tui-no-data :imgUrl="staticUrl + 'icon-empty-cart.png'" :imgHeight="230" :imgWidth="290">
  7. <view class="empty-tip">购物车空空的,快去逛逛吧~</view>
  8. </tui-no-data>
  9. </template>
  10. <template v-else>
  11. <!-- 顶部 -->
  12. <template v-if="!isDeleted">
  13. <view class="sticky-top">
  14. <view class="goods-total">
  15. <view class="total">共{{ kindCount }}件商品</view>
  16. <tui-button
  17. :size="24"
  18. width="88rpx"
  19. height="42rpx"
  20. shape="circle"
  21. :plain="true"
  22. type="base"
  23. @click="isDeleted = true"
  24. >
  25. 删除
  26. </tui-button>
  27. </view>
  28. <view class="receive-coupon">
  29. <view class="tip-text" v-text="couponTipText"></view>
  30. <tui-button
  31. :size="24"
  32. width="88rpx"
  33. height="42rpx"
  34. shape="circle"
  35. type="base"
  36. @click="visiable = true"
  37. >
  38. 领券
  39. </tui-button>
  40. </view>
  41. </view>
  42. </template>
  43. <view class="list-content">
  44. <!-- 有效商品 -->
  45. <view class="supplier-area" v-for="item in shopList" :key="item.shopId">
  46. <cm-cart-supplier-area
  47. :shopInfo="item"
  48. :isDeleted="isDeleted"
  49. @change="checkedProductChange"
  50. @countChange="onCountChange"
  51. @unitChange="onUnitChange"
  52. ref="supplierArea"
  53. ></cm-cart-supplier-area>
  54. </view>
  55. <!-- 失效商品 -->
  56. <view class="supplier-area" v-if="expiredProducts.length > 0">
  57. <cm-cart-expired-area :expiredList="expiredProducts" @clear="onClearExp"></cm-cart-expired-area>
  58. </view>
  59. </view>
  60. <view style="height: 100rpx;"></view>
  61. <!-- 购物车导航 -->
  62. <cm-cart-navbar
  63. :isCheckedAll="isChekedAll"
  64. :isDeleted="isDeleted"
  65. :data="navbarData"
  66. @all="onCheckedAll"
  67. @submit="onSumit"
  68. @cancel="isDeleted = false"
  69. @remove="removeModal = true"
  70. ></cm-cart-navbar>
  71. </template>
  72. <!-- 优惠券列表 -->
  73. <cm-coupon-popup
  74. :visiable="visiable"
  75. :list="couponList"
  76. :couponTabs="couponTabs"
  77. :hasTabs="true"
  78. :hasConfirm="false"
  79. :hasSafeArea="false"
  80. @close="visiable = false"
  81. @change="onCouponChange"
  82. @couponClick="onCouponClick"
  83. ></cm-coupon-popup>
  84. <!-- 确认弹框 -->
  85. <tui-modal :show="removeModal" content="确认删除选中的商品吗?" @click="onConfirmRemove"></tui-modal>
  86. <!-- 清空失效商品确认 -->
  87. <tui-modal :show="removeExpModal" content="确认清空失效商品?" @click="onConfirmRemoveExp"></tui-modal>
  88. <!-- 重新选择商品规格 -->
  89. <cm-goods-buy-popup
  90. v-model="goodsBuyPopup"
  91. :product="productInfo"
  92. :couponList="goodsCouponList"
  93. :useType="useType"
  94. :buttonType="buttonType"
  95. @confirm="onSaveNewUnit"
  96. v-if="productInfo"
  97. ></cm-goods-buy-popup>
  98. </view>
  99. </template>
  100. <script>
  101. import { fetchCartInfo } from '@/services/api/cart.js'
  102. import { fetchCouponListByProductIds } from '@/services/api/coupon.js'
  103. import { arrayUnique } from '@/common/utils.js'
  104. import { mapGetters, mapActions } from 'vuex'
  105. import CouponUtils from '@/common/couponUtils.js'
  106. import goodsDetailMixin from '@/mixins/goodsDetail.js'
  107. // 业务帮助函数
  108. import {
  109. totalAllCheckedProduct,
  110. computeTotalPrice,
  111. initFormatCouponList,
  112. makeCouponUseTip
  113. } from '@/common/business.helper.js'
  114. import { setTimeout } from 'timers'
  115. const resetData = () => ({
  116. isRequest: true,
  117. tabLoading: false,
  118. isDeleted: false,
  119. expiredProducts: [], // 失效商品列表
  120. shopList: [], // 供应商&&商品列表
  121. checkedShopMap: {},
  122. isChekedAll: false,
  123. removeModal: false,
  124. removeExpModal: false,
  125. // 商品价格
  126. checkedProductList: [],
  127. allPrice: 0, // 商品总价
  128. // 优惠券列表
  129. visiable: false,
  130. currentTab: 0,
  131. receiveCouponList: [], // 已领取优惠券
  132. ableCouponList: [], // 可领取优惠券
  133. couponTabs: [],
  134. currentCoupon: null,
  135. nextCoupon: null,
  136. couponTipText: '', // 可用优惠券提示
  137. // 保存变动
  138. changeRef: null,
  139. // 选择商品规格
  140. cartId: 0,
  141. goodsBuyPopup: false,
  142. useType: 'cart',
  143. buttonType: 'left',
  144. goodsCouponList: [],
  145. productInfo: null
  146. })
  147. export default {
  148. mixins: [goodsDetailMixin],
  149. data() {
  150. return resetData()
  151. },
  152. computed: {
  153. ...mapGetters(['userId', 'kindCount']),
  154. couponList() {
  155. return this.currentTab === 0 ? this.receiveCouponList : this.ableCouponList
  156. },
  157. navbarData() {
  158. const result = {
  159. finallyPrice: 0, // 实际应付
  160. couponAmount: 0,
  161. allPrice: 0,
  162. discountedPrice: 0,
  163. count: 0
  164. }
  165. if (this.currentCoupon) {
  166. result.couponAmount = this.currentCoupon.couponAmount
  167. result.discountedPrice = this.currentCoupon.couponAmount
  168. }
  169. result.allPrice = this.allPrice
  170. if (this.allPrice - result.discountedPrice > 0) {
  171. result.finallyPrice = this.allPrice - result.couponAmount
  172. }
  173. result.count = this.checkedProductList.length
  174. return result
  175. }
  176. },
  177. onPullDownRefresh() {
  178. this.resetData()
  179. this.fetchCartInfo()
  180. },
  181. onShow() {
  182. this.resetData()
  183. this.fetchCartInfo()
  184. this.fetchCartKindCount()
  185. },
  186. methods: {
  187. ...mapActions('cart', ['removeFromCart', 'fetchCartKindCount']),
  188. // 初始化数据
  189. resetData() {
  190. const data = resetData()
  191. for (let key in data) {
  192. this[key] = data[key]
  193. }
  194. },
  195. // 清空失效商品
  196. onClearExp() {
  197. this.removeExpModal = true
  198. },
  199. // 确认清空失效商品
  200. async onConfirmRemoveExp(e) {
  201. // removeProductFromCart
  202. if (!e.index) return
  203. try {
  204. await this.removeFromCart(this.expiredProducts.map(product => product.cartId))
  205. this.resetData()
  206. this.fetchCartInfo()
  207. } catch (e) {
  208. console.log('删除失效商品失败')
  209. } finally {
  210. this.removeExpModal = false
  211. }
  212. },
  213. // 提交订单
  214. onSumit() {
  215. if (this.checkedProductList.length <= 0) {
  216. return this.$toast.error('请选择商品')
  217. }
  218. const params = {}
  219. params.allPrice = this.allPrice
  220. params.allCount = this.checkedProductList.length
  221. params.cartIds = this.checkedProductList.map(product => product.cartId)
  222. params.productIds = this.checkedProductList.map(product => product.productId)
  223. params.productCount = ''
  224. uni.setStorageSync('COMMIT_CART_INFO', params)
  225. this.$router.navigateTo('order/order-create')
  226. },
  227. // 优惠券列表类型更换
  228. onCouponChange(index) {
  229. this.currentTab = index
  230. },
  231. // 优惠券点击事件
  232. onCouponClick(coupon) {
  233. if (coupon.controlType === 'receive') {
  234. this.fetchCouponList()
  235. } else {
  236. this.visiable = false
  237. }
  238. },
  239. // 设置couponTab数据
  240. makeCouponTabs() {
  241. return [
  242. {
  243. name: '已领取优惠券',
  244. num: this.receiveCouponList.length,
  245. isDot: false,
  246. disabled: false
  247. },
  248. {
  249. name: '可领取优惠券',
  250. num: this.ableCouponList.length,
  251. isDot: false,
  252. disabled: false
  253. }
  254. ]
  255. },
  256. // 获取购物车商品可用优惠券
  257. async fetchCouponList() {
  258. const productIds = []
  259. this.shopList.forEach(shop => shop.productList.forEach(product => productIds.push(product.productId)))
  260. try {
  261. const res = await fetchCouponListByProductIds({ userId: this.userId, productIds: productIds.join(',') })
  262. this.receiveCouponList = initFormatCouponList(res.data.receiveCouponList, 'search', true)
  263. this.ableCouponList = initFormatCouponList(res.data.ableCouponList, 'receive', true)
  264. this.couponTabs = this.makeCouponTabs()
  265. } catch (e) {
  266. console.log(e)
  267. } finally {
  268. this.isRequest = false
  269. }
  270. },
  271. // 获取购物车信息
  272. async fetchCartInfo() {
  273. try {
  274. const res = await fetchCartInfo({ userId: this.userId })
  275. this.expiredProducts = res.data.products
  276. this.shopList = res.data.shopList
  277. if (this.shopList.length > 0) {
  278. // 获取优惠券列表
  279. this.fetchCouponList()
  280. }
  281. this.isRequest = false
  282. return res
  283. } catch (e) {
  284. return e
  285. } finally {
  286. uni.stopPullDownRefresh()
  287. }
  288. },
  289. // 确认删除
  290. async onConfirmRemove({ index }) {
  291. if (!index) return (this.removeModal = false)
  292. const cartIds = this.checkedProductList.map(product => product.cartId)
  293. try {
  294. await this.removeFromCart(cartIds)
  295. this.fetchCartInfo()
  296. } catch (e) {
  297. console.log(e)
  298. } finally {
  299. this.isDeleted = false
  300. this.removeModal = false
  301. }
  302. },
  303. // 选中/取消全部商品
  304. onCheckedAll() {
  305. if (this.isChekedAll) {
  306. this.$refs.supplierArea.forEach(item => item.unSelectAll())
  307. } else {
  308. this.$refs.supplierArea.forEach(item => item.selectAll())
  309. }
  310. },
  311. // 选中商品变化
  312. checkedProductChange(e) {
  313. this.changeRef = e
  314. this.handleCartManager()
  315. },
  316. // 修改商品checked属性
  317. updatePorudctChecked(row) {
  318. const shopInfo = this.shopList.find(item => row.shopId === item.shopId)
  319. if (!shopInfo) return
  320. shopInfo.productList.forEach(item => {
  321. if (row.checkedList.includes(item.productId.toString())) {
  322. this.$set(item, 'checked', true)
  323. } else {
  324. this.$set(item, 'checked', false)
  325. }
  326. })
  327. },
  328. // 购物车数据处理器
  329. handleCartManager() {
  330. if (!this.changeRef) return
  331. this.updatePorudctChecked(this.changeRef)
  332. // 保存选中商品id与供应商id的k-v关系
  333. this.$set(this.checkedShopMap, this.changeRef.shopId, this.changeRef.checkedList)
  334. this.isChekedAll = this.validateIsChekedAll()
  335. // 获取已选商品列表
  336. this.checkedProductList = totalAllCheckedProduct(this.shopList)
  337. // 计算商品总价
  338. this.allPrice = computeTotalPrice(this.checkedProductList)
  339. const couponUtils = new CouponUtils(this.receiveCouponList, this.checkedProductList)
  340. this.currentCoupon = couponUtils.bestCoupon
  341. this.nextCoupon = couponUtils.secondCoupon
  342. this.couponTipText = makeCouponUseTip(this.currentCoupon, this.nextCoupon, this.allPrice)
  343. },
  344. // 商品数量变化
  345. async onCountChange(e) {
  346. await this.$store.dispatch('cart/updateProductCount', {
  347. cartId: e.cartId,
  348. productCount: e.count
  349. })
  350. await this.fetchCartInfo()
  351. this.handleCartManager()
  352. },
  353. // 商品规格修改
  354. async onUnitChange(e) {
  355. try {
  356. this.cartId = e.cartId
  357. uni.showLoading({ title: '加载中...' })
  358. this.productInfo = await this.fetchProductDetail(e.productId)
  359. this.goodsCouponList = await this.fetchCouponListByProduct(e.productId)
  360. setTimeout(() => {
  361. this.goodsBuyPopup = true
  362. uni.hideLoading()
  363. }, 1000)
  364. } catch (e) {
  365. console.log(e)
  366. }
  367. },
  368. // 保存商品规格
  369. async onSaveNewUnit(e) {
  370. try {
  371. console.log(e)
  372. await this.$store.dispatch('cart/updateProductUnit', {
  373. newSkuId: e.sku.skuId,
  374. cartId: this.cartId,
  375. productCount: e.count
  376. })
  377. this.$toast.success('规格修改成功')
  378. this.resetData()
  379. this.fetchCartInfo()
  380. this.fetchCartKindCount()
  381. } catch (e) {
  382. console.log(e)
  383. this.$toast.error('修改规格失败')
  384. }
  385. },
  386. // 验证是否全选
  387. validateIsChekedAll() {
  388. return this.shopList.every(item => {
  389. const checkedList = this.checkedShopMap[item.shopId] || []
  390. return item.productList.filter(item => item.stock !== 0 || this.isDeleted).length === checkedList.length
  391. })
  392. }
  393. }
  394. }
  395. </script>
  396. <style scoped lang="scss">
  397. .goods-total {
  398. @extend .cm-flex-between;
  399. background: #f7f7f7;
  400. padding: 0 24rpx;
  401. height: 80rpx;
  402. .total {
  403. font-size: 30rpx;
  404. color: #333;
  405. }
  406. }
  407. .receive-coupon {
  408. @extend .cm-flex-between;
  409. background: #fff;
  410. padding: 0 24rpx;
  411. height: 80rpx;
  412. .tip-text {
  413. font-size: 26rpx;
  414. color: #ff457b;
  415. white-space: nowrap;
  416. overflow: hidden;
  417. text-overflow: ellipsis;
  418. }
  419. }
  420. .supplier-area {
  421. margin-bottom: 24rpx;
  422. }
  423. </style>