index.vue 21 KB

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