<template>
<view class="container">
<view class="header">
<view @click="goBack" class="icon">
<image src="https://www.zixun61.com/image/sales.machine.app/img/back.png" class="back-icon"></image>
</view>
<view class="item">
<text class="title">商品规格</text>
</view>
</view>
<!-- 顶部banner -->
<view class="banner" v-if="packageBeanList.length>0">
<image :src="packageBeanList[0].image_path" mode="aspectFill"></image>
<view class="banner-text">
<view class="title" style="margin-left: 10rpx;">{{packageBeanList[0].name}}</view>
<view class="tag-wrap">
<text class="tag">{{packageBeanList[0].details}}</text>
<text class="tag">{{packageBeanList[0].memo}}</text>
</view>
</view>
</view>
<!-- 规格选择区域 循环渲染分组 -->
<view class="spec-wrap">
<view class="spec-block" v-for="(group, gIdx) in specGroupList" :key="gIdx">
<view class="spec-title">{{group.title}}</view>
<view class="grid-row">
<view v-for="(item,idx) in group.list" :key="idx" class="grid-item"
:class="{active: isItemActive(group, item)}" @click="handleSelect(group, item)">
<view class="check-icon" v-if="isItemActive(group, item)">✓</view>
<image :src="item.img || '/static/default.png'" mode="aspectFit"></image>
<view class="name">{{item.name}}</view>
<view class="add-price" v-if="item.addPrice > 0">+¥{{item.addPrice}}</view>
</view>
</view>
</view>
</view>
<!-- 底部固定栏 -->
<view class="bottom-bar">
<view class="bar-top">
<!-- 替换原来 bar-top 里面 scroll-view 这一段 -->
<scroll-view scroll-x class="selected-preview" enable-flex>
<view class="preview-wrap">
<!-- 已选中图片 -->
<view class="preview-item" v-for="(item, index) in previewAll.selectedList" :key="index">
<image :src="item.img || '/static/default.png'" mode="aspectFill"></image>
</view>
<!-- 统一补齐全部空位 -->
<view class="preview-item empty" v-for="k in previewAll.emptyCount" :key="'empty_'+k">
<image src="/static/default.png" mode="aspectFill"></image>
</view>
</view>
</scroll-view>
<view class="price-area">
<text class="price">¥{{totalPrice}}</text>
<text class="old-price" v-if="originPrice > totalPrice">¥{{originPrice}}</text>
</view>
</view>
<view class="bar-bottom">
<button :disabled="submit_status" class="btn btn-buy" @click="onBuy">立即购买</button>
<button :disabled="submit_status" class="btn btn-cart" @click="onAddCart">加入购物车</button>
</view>
</view>
</view>
</template>
<script>
import {
getShortCode
} from '../../store/storeUtil.js'
export default {
data() {
return {
cartList: [],
submit_status: false,
shop_code: '',
form_type: '',
package_id: '',
groupList: [],
packageBeanList: [],
packageDetailList: [],
baseLocalUrl: '',
token: '',
originPrice: 0,
basePrice: 0,
specGroupList: [],
selectedMap: {},
openid: '' // 新增
}
},
created() {
this.baseLocalUrl = this.$api.config.baseLocalUrl
this.appid = this.$api.config.appid
var that = this
uni.getStorage({
key: 'openid',
success: function(res) {
if (res.data != undefined && res.data != '') {
that.openid = res.data
} else {
uni.switchTab({
url: '/pages/index/index'
})
}
},
fail: function(e) {
uni.showToast({
icon: 'none',
title: '请先点击授权',
mask: true,
duration: 2000
})
setTimeout(() => {
uni.switchTab({
url: '/pages/index/index'
})
}, 2000)
}
})
},
onLoad(options) {
this.shop_code = options.shop_code
this.package_id = options.package_id
this.form_type = options.form_type
this.getCartFromStorage()
this.HanldMethod('s')
},
computed: {
totalPrice() {
let extra = 0
Object.values(this.selectedMap).forEach(sel => {
if (Array.isArray(sel)) {
sel.forEach(item => {
extra += Number(item.addPrice || 0)
})
} else if (sel && sel.id) {
extra += Number(sel.addPrice || 0)
}
})
return (this.basePrice + extra).toFixed(1)
},
previewAll() {
const selectedList = []
let totalMax = 0
this.specGroupList.forEach(g => {
totalMax += g.max
const sel = this.selectedMap[g.set_meal_id]
if (Array.isArray(sel)) {
sel.forEach(item => selectedList.push(item))
} else if (sel && sel.id) {
selectedList.push(sel)
}
})
return {
selectedList,
totalMax,
emptyCount: totalMax - selectedList.length
}
}
},
methods: {
// 读取本地购物车
getCartFromStorage() {
this.cartList = uni.getStorageSync("cartList") || []
},
// 保存购物车到本地
saveCartToStorage(cartList) {
uni.setStorageSync("cartList", cartList)
},
// 加入购物车,和首页逻辑保持完全一致
addCart(goodsItem) {
//this.cartList = this.getCartFromStorage()
const index = this.cartList.findIndex(item => {
if (goodsItem.package_type === '多规格') {
// 多规格:id+spec_id双重匹配
return item.id === goodsItem.id && item.spec_id === goodsItem.spec_id
} else {
return item.id === goodsItem.id
}
})
if (index > -1) {
this.cartList[index].buy_number += goodsItem.buy_number
if (this.cartList[index].buy_number > 5) this.cartList[index].buy_number = 5
} else {
this.cartList.push({
...goodsItem
})
}
this.saveCartToStorage(this.cartList)
},
goBack() {
uni.navigateBack()
},
buildGroupData() {
const map = {}
if (!this.packageDetailList || this.packageDetailList.length === 0) {
this.specGroupList = []
this.selectedMap = {}
return
}
this.packageDetailList.forEach(row => {
if (!row.setMeal || !row.product) return
const mid = row.setMeal.id
if (!map[mid]) {
map[mid] = {
// title: row.setMeal.name 份,
title: row.product.productType.name+'('+row.setMeal.selected_count+')',
max: Number(row.setMeal.selected_count),
list: []
}
}
map[mid].list.push({
id: row.product.id,
name: row.product.name || '商品',
img: row.product.image_path,
product_id: row.product.id || '0',
product_type_id: row.product.productType.id || '0',
addPrice: Number(row.sale_price || 0),
set_meal_id: mid
})
})
this.specGroupList = []
this.selectedMap = {}
Object.keys(map).forEach(mid => {
const groupItem = map[mid]
const itemList = groupItem.list
let type = 'radio'
if (groupItem.max > 1) {
type = 'checkbox'
}
const group = {
title: groupItem.title,
set_meal_id: mid,
max: groupItem.max,
type: type,
list: itemList
}
this.specGroupList.push(group)
if (type === 'radio') {
// 单选:默认选1个
this.selectedMap[mid] = {
...itemList[0]
}
} else {
// 多选:默认选中max个,max是几就默认勾几个
const picks = []
const takeNum = Math.min(groupItem.max, itemList.length)
for (let i = 0; i < takeNum; i++) {
picks.push({
...itemList[i]
})
}
this.selectedMap[mid] = picks
}
})
this.$forceUpdate()
},
isItemActive(group, item) {
const sel = this.selectedMap[group.set_meal_id]
if (!sel) return false
if (group.type === 'radio') {
return sel.id === item.id
} else {
return Array.isArray(sel) && sel.some(s => s.id === item.id)
}
},
handleSelect(group, item) {
const mid = group.set_meal_id
let sel = this.selectedMap[mid]
if (!sel) return
// 先克隆一份整个selectedMap,保证响应式
let newSelectedMap = JSON.parse(JSON.stringify(this.selectedMap))
if (group.type === 'radio') {
newSelectedMap[mid] = {
...item
}
} else {
let arr = newSelectedMap[mid]
const findIndex = arr.findIndex(x => x.id === item.id)
if (arr.length >= group.max) {
arr.shift()
}
if (findIndex > -1) {
arr.splice(findIndex, 1)
}
arr.push({
...item
})
newSelectedMap[mid] = arr
}
// ✅ 整体覆盖赋值,Vue2 可以监听到变化,computed自动刷新
this.selectedMap = newSelectedMap
},
onBuy() {
const sub_goods = []
Object.values(this.selectedMap).forEach(val => {
if (Array.isArray(val)) {
sub_goods.push(...val)
} else if (val && val.id) {
sub_goods.push(val)
}
})
if (sub_goods.length === 0) {
uni.showToast({
title: "请选择规格",
icon: "none"
})
return
}
// 先加入购物车,再跳转支付
const pkg = this.packageBeanList[0]
if (this.cartList.length > 0) {
const hasGoodsId = this.cartList.some(item => item.id === pkg.id)
if (hasGoodsId) {
uni.showToast({
icon: 'none',
title: '套餐已存在~',
mask: true,
duration: 2000
})
return
console.log("购物车已有该商品(任意规格)")
}
}
const _uid = `single_${pkg.id}`
const cartItem = {
id: pkg.id,
name: pkg.name,
image_path: pkg.image_path || '/static/banner.png',
sale_price: pkg.sale_price,
buy_number: 1,
package_type: "多规格",
spec_id: pkg.id,
spec_name: pkg.name,
spec_price: Number(this.totalPrice),
sub_goods: sub_goods,
_uid
}
this.addCart(cartItem)
// uni.navigateBack()
let url = `/sub-main/shop/payment?form_type=` + this.form_type
uni.navigateTo({
url: url
})
},
onAddCart() {
// 1.把selectedMap摊平成子商品数组sub_goods
const sub_goods = []
Object.values(this.selectedMap).forEach(val => {
if (Array.isArray(val)) {
sub_goods.push(...val)
} else if (val && val.id) {
sub_goods.push(val)
}
})
if (sub_goods.length === 0) {
uni.showToast({
title: "请选择规格",
icon: "none"
})
return
}
const pkg = this.packageBeanList[0]
if (this.cartList.length > 0) {
const hasGoodsId = this.cartList.some(item => item.id === pkg.id)
if (hasGoodsId) {
uni.showToast({
icon: 'none',
title: '套餐已存在~',
mask: true,
duration: 2000
})
return
console.log("购物车已有该商品(任意规格)")
}
}
const _uid = `single_${pkg.id}`
// 组装和首页购物车完全兼容的对象
const cartItem = {
id: pkg.id,
name: pkg.name,
image_path: pkg.image_path || '/static/banner.png',
sale_price: pkg.sale_price,
buy_number: 1,
package_type: "多规格",
spec_id: pkg.id,
spec_name: pkg.name,
spec_price: Number(this.totalPrice),
sub_goods: sub_goods,
_uid
}
this.addCart(cartItem)
// uni.showToast({
// title: "加入购物车成功"
// })
// 可选:加入成功之后返回上一页
// uni.navigateBack()
const cacheCode = getShortCode()
let url = `/sub-main/shop/shop_set_meal?form_type=` + this.form_type + `&code=` + cacheCode
uni.navigateTo({
url: url
})
},
HanldMethod(type) {
var that = this
that.token = ''
uni.request({
url: that.baseLocalUrl,
method: 'POST',
dataType: 'json',
data: {
appid: that.appid
},
headers: {
'Content-Type': "application/json;charset=utf-8"
},
success: result => {
if (result.data.status == 'fail') {
uni.hideLoading()
uni.showToast({
icon: 'none',
title: '获取失败',
mask: true,
duration: 2000
})
return
}
that.token = result.data.token
if (type == 's') {
that.loadData()
}
},
fail(ex) {
console.log(ex.message)
uni.showToast({
icon: 'none',
title: ex.message,
mask: true,
duration: 2000
})
}
})
},
loadData() {
var that = this
uni.showLoading({
title: '加载中......'
})
uni.request({
url: that.baseLocalUrl,
method: 'POST',
dataType: 'json',
data: {
shop_code: that.shop_code,
package_id: that.package_id,
token: that.token
},
headers: {
'Content-Type': "application/json;charset=utf-8"
},
success: result => {
if (result.data.status == 'fail') {
uni.hideLoading()
uni.showToast({
icon: 'none',
title: '获取失败',
mask: true,
duration: 2000
})
return
}
uni.hideLoading()
that.groupList = result.data.groupList
that.packageBeanList = result.data.packageBeanList
that.packageDetailList = result.data.packageDetailList
if (that.packageBeanList[0]) {
that.basePrice = Number(that.packageBeanList[0].sale_price || 0)
that.originPrice = Number(that.packageBeanList[0].original_price || 0)
}
that.submit_status = result.data.submit_status
that.buildGroupData()
},
fail(ex) {
uni.hideLoading()
console.log(ex.message)
uni.showToast({
icon: 'none',
title: ex.message,
mask: true,
duration: 2000
})
}
})
},
}
}
</script>
<style lang="scss" scoped>
.container {
padding-bottom: calc(300rpx + env(safe-area-inset-bottom));
}
.banner {
position: relative;
background: #fff;
}
.banner image {
width: 100%;
height: 360rpx;
}
.banner-text {
padding: 20rpx 30rpx;
}
.title {
font-size: 36rpx;
font-weight: bold;
margin-bottom: 12rpx;
}
.tag-wrap {
display: flex;
gap: 16rpx;
}
.tag {
background: #ffe9e9;
color: #e63946;
padding: 4rpx 12rpx;
border-radius: 8rpx;
font-size: 24rpx;
}
.spec-wrap {
margin-top: 20rpx;
background: #fff;
}
.spec-block {
padding: 24rpx 30rpx;
border-bottom: 1rpx solid #eee;
}
.spec-title {
font-weight: bold;
font-size: 26rpx;
color: #333;
margin-bottom: 24rpx;
}
.grid-row {
display: flex;
flex-wrap: wrap;
gap: 20rpx;
}
.grid-item {
width: calc((100% - 40rpx) / 3);
border: 2rpx solid #eee;
border-radius: 12rpx;
overflow: hidden;
position: relative;
background: #fff;
}
.grid-item.active {
border-color: #e63946;
}
.check-icon {
position: absolute;
top: 6rpx;
right: 6rpx;
width: 32rpx;
height: 32rpx;
background: #e63946;
color: #fff;
border-radius: 50%;
text-align: center;
line-height: 32rpx;
font-size: 24rpx;
z-index: 2;
}
.grid-item image {
width: 100%;
height: 140rpx;
background: #f7f7f7;
}
.name {
padding: 8rpx 6rpx;
text-align: center;
font-size: 24rpx;
line-height: 1.3;
}
.add-price {
text-align: center;
color: #e63946;
font-size: 24rpx;
padding-bottom: 8rpx;
}
.bottom-bar {
position: fixed;
bottom: 0;
left: 0;
width: 100%;
background: #fff;
padding: 20rpx 20rpx calc(20rpx + env(safe-area-inset-bottom)) 20rpx;
box-sizing: border-box;
border-top: 1rpx solid #eee;
z-index: 999;
}
.bar-top {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 16rpx;
gap: 20rpx;
}
.selected-preview {
flex: 1;
height: 96rpx;
overflow: hidden;
white-space: nowrap;
}
.preview-wrap {
display: inline-flex;
gap: 12rpx;
height: 100%;
align-items: center;
white-space: nowrap;
}
.preview-item {
width: 76rpx;
height: 76rpx;
flex-shrink: 0;
border-radius: 10rpx;
overflow: hidden;
border: 2rpx solid #d4b878;
}
.preview-item image {
width: 100%;
height: 100%;
display: block;
}
.price-area {
flex-shrink: 0;
white-space: nowrap;
}
.price {
font-size: 44rpx;
color: #e63946;
font-weight: bold;
}
.old-price {
font-size: 26rpx;
color: #999;
text-decoration: line-through;
margin-left: 8rpx;
}
.bar-bottom {
display: flex;
gap: 12rpx;
}
.btn {
flex: 1;
height: 88rpx;
line-height: 88rpx;
border-radius: 12rpx;
font-size: 28rpx;
margin: 0 !important;
padding: 0 !important;
border: none;
overflow: hidden;
}
.btn-buy {
background: #fff;
color: #e63946;
border: 2rpx solid #e63946;
}
.btn-cart {
background: #e63946;
color: #fff;
}
.header {
display: flex;
align-items: center;
margin-top: 90rpx;
padding: 20rpx;
background-color: #f8f8f8;
}
.icon {
width: 80rpx;
}
.item {
width: 100%;
justify-content: center;
display: flex;
}
.title {
font-size: 30rpx;
margin-left: -40rpx;
}
.back-icon {
width: 30px;
height: 30px;
}
</style>