index.vue 21 KB

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