index.vue 25 KB

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