index.vue 20 KB

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