index.vue 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. <template>
  2. <view class="cart-page">
  3. <!-- 购物车列表 -->
  4. <view class="cart-list">
  5. <u-swipe-action :show="item.show" :index="index" v-for="(item, index) in cartList" :key="item.id"
  6. @click="clickAction" @open="openAction" @touchstart="swipeStart" :options="actionOptions">
  7. <cart-item :item="item" @check="handleCheck" @changeNum="handleChangeNum" @reduce="handleReduce"
  8. @selectCondition="onSelectCondition"></cart-item>
  9. </u-swipe-action>
  10. </view>
  11. <!-- 品相切换弹窗 -->
  12. <condition-popup ref="conditionPopup" @select="handleConditionUpdate"></condition-popup>
  13. <!-- 空状态 -->
  14. <view class="empty-cart" v-if="cartList.length === 0 && !loading" style="margin:15% 0">
  15. <u-empty text="购物车空空如也" mode="car"></u-empty>
  16. </view>
  17. <!-- 为你推荐 -->
  18. <view class="recommend-section" v-if="recommendList.length > 0">
  19. <view class="section-title">
  20. <text class="line"></text>
  21. <text class="text">为你推荐</text>
  22. <text class="line"></text>
  23. </view>
  24. <view class="recommend-grid">
  25. <view class="grid-item" v-for="(item, index) in recommendList" :key="index">
  26. <image :src="item.cover" mode="aspectFill" class="cover"></image>
  27. <view class="title">{{ item.title }}</view>
  28. </view>
  29. </view>
  30. </view>
  31. <!-- 底部占位 -->
  32. <view style="height: 120rpx;"></view>
  33. <!-- 悬浮清空按钮 -->
  34. <!-- <view class="floating-clear-btn" v-if="cartList.length > 0" @click="handleClearCart">
  35. <u-icon name="trash" size="36" color="#fa3534"></u-icon>
  36. </view> -->
  37. <!-- 底部结算栏 -->
  38. <view class="bottom-fixed" v-if="cartList.length > 0">
  39. <view class="left-part">
  40. <view class="checkbox-wrap" @click="toggleSelectAll" style="display: flex; align-items: center; height: 100%; padding-right: 20rpx;">
  41. <u-checkbox v-model="isAllSelected" shape="circle" active-color="#38C148" :disabled="false"
  42. @change="onAllCheckChange" style="pointer-events: none;">全选</u-checkbox>
  43. </view>
  44. </view>
  45. <view class="right-part">
  46. <view class="info-wrapper">
  47. <view class="total-info">
  48. <view class="total-price">
  49. <text class="label">合计:</text>
  50. <text class="price">¥{{ totalPrice }}</text>
  51. </view>
  52. <view class="reduced-tip" v-if="totalReduced > 0">已降 ¥{{ totalReduced }}</view>
  53. </view>
  54. <view class="freight-template" @click="handleGetFreightTemplate" v-if="shippingText">
  55. {{ shippingText }}
  56. </view>
  57. </view>
  58. <view class="checkout-btn" @click="checkout">
  59. 结算({{ selectedCount }})
  60. </view>
  61. </view>
  62. </view>
  63. <!-- 减钱弹窗 -->
  64. <price-reduction-popup ref="reducePopup" @share="handleShare" @scan="handleScan"></price-reduction-popup>
  65. <reduce-qrcode ref="reduceQrcode"></reduce-qrcode>
  66. <common-dialog ref="reduceDialog" title="温馨提示" @confirm="onNext">
  67. <text>购物车中有可减钱的商品,如您提交订单,则失去该资格哦~</text>
  68. </common-dialog>
  69. </view>
  70. </template>
  71. <script>
  72. import CartItem from '../components/cart-item.vue';
  73. import PriceReductionPopup from '@/components/price-reduction-popup/price-reduction-popup.vue';
  74. import ReduceQrcode from '@/components/reduce-qrcode/reduce-qrcode.vue';
  75. import CommonDialog from '@/components/common-dialog.vue';
  76. import ConditionPopup from '../components/condition-popup.vue';
  77. export default {
  78. components: {
  79. CartItem,
  80. PriceReductionPopup,
  81. ReduceQrcode,
  82. CommonDialog,
  83. ConditionPopup
  84. },
  85. data() {
  86. return {
  87. loading: true,
  88. currentItem: null,
  89. isAllSelected: false,
  90. cartList: [],
  91. actionOptions: [
  92. {
  93. text: '删除',
  94. style: {
  95. backgroundColor: '#fa3534'
  96. }
  97. }
  98. ],
  99. recommendList: [],
  100. shippingText: ''
  101. };
  102. },
  103. onShow() {
  104. this.loadData();
  105. this.getShippingText();
  106. this.$updateCartBadge();
  107. },
  108. mounted() {
  109. this.loadData();
  110. this.getShippingText();
  111. },
  112. // 分享配置
  113. onShareAppMessage(res) {
  114. console.log(res, '分享');
  115. if (res.from === "button") {
  116. let reduceCode = uni.getStorageSync("reduceCodeShare");
  117. // 调用分享接口
  118. this.$u.api.goToReduceShareAjax({ reduceCode: reduceCode });
  119. return {
  120. title: "快来帮我减钱买书吧!",
  121. path: "/pages/home/index?reduceCode=" + reduceCode,
  122. imageUrl: "https://shuhi.oss-cn-qingdao.aliyuncs.com/mini/share.jpg",
  123. desc: "书嗨,专注于书籍交易的平台,提供新书和二手书的买卖服务",
  124. };
  125. } else {
  126. return {
  127. title: "书嗨",
  128. page: "/pages/home/index",
  129. };
  130. }
  131. },
  132. // 分享到朋友圈
  133. onShareTimeline(res) {
  134. if (res.from === "button") {
  135. let reduceCode = uni.getStorageSync("reduceCodeShare");
  136. // 调用分享接口
  137. this.$u.api.goToReduceShareAjax({ reduceCode: reduceCode });
  138. return {
  139. title: "快来帮我减钱买书吧!",
  140. path: "/pages/home/index?reduceCode=" + reduceCode,
  141. imageUrl: "https://shuhi.oss-cn-qingdao.aliyuncs.com/mini/share.jpg",
  142. desc: "书嗨,专注于书籍交易的平台,提供新书和二手书的买卖服务",
  143. };
  144. } else {
  145. return {
  146. title: "书嗨",
  147. page: "/pages/home/index",
  148. };
  149. }
  150. },
  151. computed: {
  152. selectedItems() {
  153. return this.cartList.filter(item => item.checked && item.stockStatus !== 3 && item.availableStock > 0);
  154. },
  155. totalPrice() {
  156. const sumPrice = this.selectedItems.reduce((sum, item) => sum + item.price * item.quantity, 0);
  157. const sumReduce = this.selectedItems.reduce((sum, item) => sum + (item.currReduceMoney || 0), 0);
  158. const result = sumPrice - sumReduce;
  159. return result > 0 ? result.toFixed(2) : "0.00";
  160. },
  161. totalReduced() {
  162. return this.selectedItems.reduce((sum, item) => sum + (item.currReduceMoney || 0), 0).toFixed(2);
  163. },
  164. selectedCount() {
  165. return this.selectedItems.reduce((sum, item) => sum + item.quantity, 0);
  166. }
  167. },
  168. watch: {
  169. cartList: {
  170. handler(val) {
  171. const validItems = val.filter(item => item.stockStatus !== 3 && item.availableStock > 0);
  172. if (validItems.length === 0) {
  173. this.isAllSelected = false;
  174. return;
  175. }
  176. this.isAllSelected = validItems.every(item => item.checked);
  177. },
  178. deep: true
  179. }
  180. },
  181. methods: {
  182. getShippingText() {
  183. this.$u.api.getShippingTempleteAjax().then(res => {
  184. if (res.code === 200) {
  185. this.shippingText = res.data.templeteName;
  186. }
  187. });
  188. },
  189. handleGetFreightTemplate() {
  190. console.log('获取运费模版');
  191. },
  192. swipeStart(index) {
  193. this.cartList.forEach((item, idx) => {
  194. if (index !== idx) {
  195. item.show = false;
  196. }
  197. });
  198. },
  199. clickAction(index, index1) {
  200. if (this.actionOptions[index1].text == '删除') {
  201. const item = this.cartList[index];
  202. this.handleDelete(item);
  203. }
  204. },
  205. openAction(index) {
  206. this.cartList[index].show = true;
  207. this.cartList.map((val, idx) => {
  208. if (index != idx) this.cartList[idx].show = false;
  209. })
  210. },
  211. loadData() {
  212. this.loading = true;
  213. // 获取购物车列表
  214. this.$u.api.getShopCartListAjax({}).then(res => {
  215. this.loading = false;
  216. // 获取本地缓存的选中状态,和当前列表的选中状态合并
  217. let storageCheckedIds = uni.getStorageSync('cartCheckedIds') || [];
  218. const currentCheckedIds = this.cartList.filter(i => i.checked).map(i => i.id);
  219. // 合并并去重
  220. let checkedIds = [...new Set([...storageCheckedIds, ...currentCheckedIds])];
  221. // 本地添加选中状态属性
  222. const list = res.rows || [];
  223. this.cartList = list.map(item => {
  224. return {
  225. ...item,
  226. checked: checkedIds.includes(item.id),
  227. show: false
  228. };
  229. });
  230. // 更新缓存中存在的且当前在购物车里的项
  231. const finalCheckedIds = this.cartList.filter(i => i.checked).map(i => i.id);
  232. uni.setStorageSync('cartCheckedIds', finalCheckedIds);
  233. }).catch(() => {
  234. this.loading = false;
  235. });
  236. // 获取推荐列表
  237. this.$u.api.getSearchRecommendAjax().then(res => {
  238. if (res.code == 200) {
  239. this.recommendList = res.data || [];
  240. }
  241. });
  242. },
  243. handleCheck({ id, checked }) {
  244. const item = this.cartList.find(i => i.id === id);
  245. if (item) {
  246. item.checked = checked;
  247. // 更新本地缓存
  248. const finalCheckedIds = this.cartList.filter(i => i.checked).map(i => i.id);
  249. uni.setStorageSync('cartCheckedIds', finalCheckedIds);
  250. }
  251. },
  252. handleChangeNum({ id, num }) {
  253. const item = this.cartList.find(i => i.id === id);
  254. if (item) {
  255. // 乐观更新还是等待服务器?
  256. // 通常是服务器优先。
  257. this.$u.api.updateCartNumAjax({
  258. id: id,
  259. quantity: num
  260. }).then(() => {
  261. item.quantity = num;
  262. // 通过 computed 重新计算总额
  263. this.$updateCartBadge();
  264. }).catch(() => {
  265. });
  266. }
  267. },
  268. handleReduce(item) {
  269. console.log('handleReduce item:', item);
  270. this.$nextTick(() => {
  271. if (this.$refs.reducePopup) {
  272. this.$refs.reducePopup.open({
  273. isbn: item.isbn,
  274. conditionType: item.conditionType,
  275. orderId: item.id
  276. });
  277. } else {
  278. console.error('reducePopup ref not found');
  279. }
  280. });
  281. },
  282. onAllCheckChange(e) {
  283. const checked = e.value;
  284. this.cartList.forEach(item => {
  285. if (item.stockStatus !== 3 && item.availableStock > 0) {
  286. item.checked = checked;
  287. }
  288. });
  289. // 保存选中状态到本地缓存
  290. const finalCheckedIds = this.cartList.filter(i => i.checked).map(i => i.id);
  291. uni.setStorageSync('cartCheckedIds', finalCheckedIds);
  292. },
  293. toggleSelectAll() {
  294. this.isAllSelected = !this.isAllSelected;
  295. this.onAllCheckChange({ value: this.isAllSelected });
  296. },
  297. handleClearCart() {
  298. uni.showModal({
  299. title: '提示',
  300. content: '确定要清空购物车吗?',
  301. success: (res) => {
  302. if (res.confirm) {
  303. this.$u.api.clearCartAjax().then(() => {
  304. this.$u.toast('清空成功');
  305. this.cartList = [];
  306. this.$updateCartBadge();
  307. });
  308. }
  309. }
  310. });
  311. },
  312. checkout() {
  313. if (this.selectedCount === 0) {
  314. uni.showToast({ title: '请选择商品', icon: 'none' });
  315. return;
  316. }
  317. // 如果需要,检查减价商品逻辑
  318. // 如果有选中的商品可以减价,显示对话框?
  319. const hasReduceItem = this.selectedItems.some(item => (item.reduceNum < item.maxReduceNum) && (item.reduceMoney > 0));
  320. if (hasReduceItem) {
  321. this.$refs.reduceDialog.openPopup();
  322. } else {
  323. this.onNext();
  324. }
  325. },
  326. onNext() {
  327. // 提交订单 - 传递选中的 ID
  328. if (this.selectedItems.length === 0) {
  329. this.$u.toast('请选择商品');
  330. return;
  331. }
  332. const ids = this.selectedItems.map(item => item.id);
  333. // 调用预提交接口检查
  334. uni.showLoading({ title: '处理中' });
  335. this.$u.api.preSubmitOrderAjax({ cartIdList: ids }).then(res => {
  336. uni.hideLoading();
  337. if (res.code === 200) {
  338. if (res.data.code === 2) {
  339. return this.$u.toast('库存不足');
  340. } else if (res.data.code === 3) {
  341. return this.$u.toast('图书已下架');
  342. }
  343. uni.navigateTo({
  344. url: `/pages-car/pages/confirm-order`
  345. });
  346. //存储提交的数据
  347. res.data.cartIdList = ids;
  348. uni.setStorageSync('preSubmitOrderData', res.data);
  349. } else {
  350. // 失败,显示错误信息
  351. this.$u.toast(res.msg || '无法提交订单');
  352. }
  353. }).catch(() => {
  354. uni.hideLoading();
  355. });
  356. },
  357. handleShare() {
  358. console.log('share');
  359. },
  360. handleScan(bookInfo) {
  361. this.$refs.reduceQrcode.open(bookInfo);
  362. },
  363. handleDelete(item) {
  364. uni.showModal({
  365. title: '提示',
  366. content: '确定要删除该商品吗?',
  367. success: (res) => {
  368. if (res.confirm) {
  369. this.$u.api.deleteCartItemAjax(item.id).then(async () => {
  370. await this.$updateCartBadge();
  371. this.$u.toast('删除成功');
  372. // 从本地列表中移除
  373. const index = this.cartList.findIndex(i => i.id === item.id);
  374. if (index > -1) {
  375. this.cartList.splice(index, 1);
  376. }
  377. });
  378. } else {
  379. item.show = false;
  380. }
  381. }
  382. });
  383. },
  384. onSelectCondition(item) {
  385. this.currentItem = item;
  386. // 获取商品详情中的 SKU 列表
  387. // 注意:这里使用 isbn,假设 item 中包含 isbn
  388. if (!item.isbn) {
  389. this.$u.toast('无法获取商品信息');
  390. return;
  391. }
  392. uni.showLoading({ title: '加载中' });
  393. this.$u.http.get('/token/shop/bookDetail', { isbn: item.isbn }).then(res => {
  394. uni.hideLoading();
  395. if (res.code === 200 && res.data && res.data.skuList) {
  396. this.$refs.conditionPopup.open(res.data.skuList, item.conditionType);
  397. } else {
  398. this.$u.toast('获取品相信息失败');
  399. }
  400. }).catch(() => {
  401. uni.hideLoading();
  402. this.$u.toast('网络请求失败');
  403. });
  404. },
  405. handleConditionUpdate(sku) {
  406. if (!this.currentItem) return;
  407. uni.showLoading({
  408. title: '更新中'
  409. });
  410. this.$u.api.updateCartConditionAjax({
  411. id: this.currentItem.id,
  412. conditionType: sku.conditionType
  413. }).then(() => {
  414. uni.hideLoading();
  415. this.$u.toast('更新成功');
  416. this.loadData();
  417. }).catch(() => {
  418. uni.hideLoading();
  419. });
  420. }
  421. }
  422. }
  423. </script>
  424. <style lang="scss" scoped>
  425. .cart-page {
  426. min-height: 100vh;
  427. background-color: #f5f5f5;
  428. padding-bottom: 120rpx; // 底部栏的留白
  429. }
  430. .ad-banner {
  431. background-color: #d1f2d6; // 浅绿色
  432. padding: 20rpx 30rpx;
  433. display: flex;
  434. justify-content: space-between;
  435. align-items: center;
  436. color: #666;
  437. font-size: 26rpx;
  438. }
  439. .cart-list {
  440. padding: 20rpx;
  441. }
  442. .recommend-section {
  443. padding: 0 20rpx;
  444. .section-title {
  445. display: flex;
  446. align-items: center;
  447. justify-content: center;
  448. margin: 30rpx 0;
  449. .line {
  450. width: 60rpx;
  451. height: 2rpx;
  452. background-color: #ccc;
  453. }
  454. .text {
  455. margin: 0 20rpx;
  456. font-size: 28rpx;
  457. color: #333;
  458. font-weight: bold;
  459. }
  460. }
  461. .recommend-grid {
  462. display: flex;
  463. flex-wrap: wrap;
  464. justify-content: space-between;
  465. .grid-item {
  466. width: 32%; // 3 列
  467. background-color: #fff;
  468. border-radius: 12rpx;
  469. margin-bottom: 20rpx;
  470. padding: 20rpx;
  471. box-sizing: border-box;
  472. display: flex;
  473. flex-direction: column;
  474. align-items: center;
  475. .cover {
  476. width: 100%;
  477. height: 220rpx;
  478. border-radius: 8rpx;
  479. background-color: #eee;
  480. }
  481. .title {
  482. margin-top: 10rpx;
  483. font-size: 24rpx;
  484. color: #333;
  485. line-height: 1.4;
  486. display: -webkit-box;
  487. -webkit-box-orient: vertical;
  488. -webkit-line-clamp: 2;
  489. overflow: hidden;
  490. width: 100%;
  491. }
  492. }
  493. }
  494. }
  495. .floating-clear-btn {
  496. position: fixed;
  497. right: 30rpx;
  498. bottom: 160rpx; /* 留出底部结算栏的空间 */
  499. /* #ifdef H5 */
  500. bottom: calc(160rpx + 50px);
  501. /* #endif */
  502. width: 80rpx;
  503. height: 80rpx;
  504. background-color: #fff;
  505. border: 2rpx solid #f56c6c;
  506. border-radius: 50%;
  507. display: flex;
  508. justify-content: center;
  509. align-items: center;
  510. z-index: 98;
  511. box-shadow: 0 4rpx 10rpx rgba(250, 53, 52, 0.2);
  512. &:active {
  513. background-color: #fef0f0;
  514. }
  515. }
  516. .bottom-fixed {
  517. position: fixed;
  518. bottom: 0;
  519. /* #ifdef H5 */
  520. bottom: 50px;
  521. /* #endif */
  522. left: 0;
  523. width: 100%;
  524. background-color: #fff;
  525. display: flex;
  526. align-items: center;
  527. justify-content: space-between;
  528. padding: 24rpx 30rpx;
  529. box-sizing: border-box;
  530. box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  531. z-index: 99;
  532. .left-part {
  533. display: flex;
  534. align-items: center;
  535. }
  536. .right-part {
  537. display: flex;
  538. align-items: center;
  539. .info-wrapper {
  540. display: flex;
  541. flex-direction: column;
  542. align-items: flex-end;
  543. margin-right: 20rpx;
  544. .total-info {
  545. display: flex;
  546. align-items: center;
  547. .total-price {
  548. display: flex;
  549. align-items: center;
  550. .label {
  551. font-size: 28rpx;
  552. color: #333;
  553. }
  554. .price {
  555. font-size: 36rpx;
  556. color: #e02020;
  557. font-weight: bold;
  558. }
  559. }
  560. .reduced-tip {
  561. font-size: 22rpx;
  562. color: #38C148;
  563. border: 1rpx solid #38C148;
  564. border-radius: 4rpx;
  565. padding: 0 10rpx;
  566. margin-left: 10rpx;
  567. }
  568. }
  569. .freight-template {
  570. font-size: 24rpx;
  571. color: #d79f5f;
  572. margin-top: 6rpx;
  573. }
  574. }
  575. .checkout-btn {
  576. background-color: #e02020;
  577. color: #fff;
  578. font-size: 30rpx;
  579. padding: 16rpx 40rpx;
  580. border-radius: 40rpx;
  581. }
  582. }
  583. }
  584. </style>