index.vue 21 KB

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