cart.vue 15 KB

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