cart.vue 14 KB

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