index.vue 23 KB

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