index.vue 25 KB

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