index.vue 22 KB

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