index.vue 20 KB

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