<template>
	<view class="w-full">
		<view>
			<u-row justify="space-between" customStyle="margin-bottom: 10px">
				<u-col span="3">
					<view class="icon-container-l" @click="onOrder">
						<uni-badge size="normal" :text="txts" absolute="rightTop">
							<u-icon :name="iconCooking" label="自提" labelPos="bottom" size="32"></u-icon>
						</uni-badge>
					</view>
				</u-col>
				<view class="container">
					<u-tag plain :text="cList.openState ? '营业中' : '离线'" :type="cList.openState ? 'success' : 'error'"
						size="mini"></u-tag>
					<view @click="btnIc">
						<u-icon :label="cList.name" labelPos="left" size="16" name="arrow-down"></u-icon>
					</view>
				</view>
				<u-col span="3">
					<view class="icon-container-r" @click="onMyInfo">
						<u-icon label="我的" labelPos="bottom" size="32" :name="iconPeople"></u-icon>
					</view>
				</u-col>
			</u-row>
		</view>
		<view class="w-full dflex-b padding-xs box-sizing-b dflex-wrap-w">
			<view class="goods-item margin-bottom-sm" v-for="(item, gindex)  in goods" :key="gindex">
				<view class="img dflex-c" @click="toDetial(item)">
					<image mode="aspectFit" :src="item.imgList[0].url"></image>
				</view>
				<view class="title">{{item.spuName}}</view>
				<view class="dflex padding-bottom-xs">
					<u-tag plain text="销量: 199" borderColor="#FF6D20" color="#FF6D20" size="mini"></u-tag>
				</view>
				<view class="w-full dflex-b">
					<view class="price">{{item.minPrice ? item.minPrice : '无'}}</view>
					<view>
						<u-button type="primary" shape="circle" size="small"
							color="linear-gradient(to right, #F54319, #FF6D20)" @click="goCart(item)">
							<u-icon name="shopping-cart-fill" size="28" color="#fff"></u-icon>
						</u-button>
					</view>
				</view>
			</view>
		</view>
		<my-gap :height="10" />
		<specPopup class='spec-box' ref="specPopup" :cardMsg="cardMsg" @update-shopmsg="handleUpdateShopMsg"
			@addShop="carListMeg">
		</specPopup>
		<view class="cart-bottom padding-sm dflex-b">
			<view class="cart padding-lr">
				<uni-badge size="small" :text="buyCount" absolute="rightTop">
					<u-icon name="shopping-cart-fill" size="28" color="#FF873D" @click="showCart"></u-icon>
				</uni-badge>
				<text class="cart-total">总计：￥{{total}}</text>
			</view>
			<view class="balance dflex-c background-gradient" @click="toBuy">去结算</view>
		</view>
		<cartPopupVue ref="cartPopup" @selected-changed="handleSelectedChanged" />
		<u-modal ref="uModal" :show="modalShow" :title="modalTitle" :content="modalContent" :closeable="true"
			@close="modalClose" @confirm="confirm"></u-modal>
	</view>
</template>

<script>
	import cartPopupVue from '../../components/cartPopup.vue'
	import specPopup from '@/components/specPopup.vue'
	import iconCooking from '../../static/cooking.png'
	import iconPeople from '../../static/people.png'
	import shoppingCart from '../../static/shoppingCart.png'
	export default {
		components: {
			cartPopupVue,
			specPopup
		},
		data() {
			return {
				onIndex: 0,
				show: false,
				iconCooking: iconCooking,
				iconPeople: iconPeople,
				shoppingCart: shoppingCart,
				tags: 1,
				txts: 1,
				carList: [],
				goods: [],
				total: 0,
				cList: {},
				cardMsg: {},
				selectedList: [],
				buyCount: 0,
				modalShow: false,
				modalTitle: '您还未登录',
				modalContent: '您是否确定要登录'
			}
		},
		onLoad() {
			const e = uni.getStorageSync('carl')
			this.cList = e
			this.fatchDate()
			this.carListMeg()
			uni.$on('register_refresh', () => {
				this.fatchDate()
				this.carListMeg()
				this.total = 0
			})
			const token = uni.getStorageSync('token')
			if (!token) {
				this.modalShow = true;
			}
		},
		methods: {
			modalClose() {
				this.modalShow = false;
			},
			confirm() {
				//调用登录方法，autoLogin方法在mian.js中
				this.autoLogin()
				this.modalShow = false
			},
			// 加购
			goCart(e) {
				// console.log('================', e)
				this.cardMsg = e
				this.$nextTick(() => {
					this.$refs.specPopup.open();
				});
			},
			handleSelectedChanged(selectedItems) {
				//console.log('选中的数据:', selectedItems)
				this.carList = selectedItems
				this.carListMeg()
				this.totalPrice()
			},

			//计算selected为true的
			totalPrice() {
				let total = 0;
				for (let i = 0; i < this.carList.length; i++) {
					// 检查商品是否有 selected 属性
					if (this.carList[i].hasOwnProperty('selected')) {
						// 如果 selected 属性存在，只有当它为 true 时才计算
						if (this.carList[i].selected) {
							let priceInCents = Math.round(this.carList[i].price * 100);
							let quant = this.carList[i].quantity;
							total += priceInCents * quant;
						}
					} else {
						// 如果 selected 属性不存在，直接计算所有商品
						let priceInCents = Math.round(this.carList[i].price * 100);
						let quant = this.carList[i].quantity;
						total += priceInCents * quant;
					}
				}

				// 将总价格转换回浮点数（以元为单位）
				this.total = (total / 100).toFixed(2);
			},
			showCart() {
				this.$nextTick(() => {
					this.$refs.cartPopup.setShow(true)
				})
			},
			btnIc() {
				uni.navigateTo({
					url: `/pages/diningList/diningList`
				})
			},
			toDetial(e) {
				// console.log('eeeeee====================', e)
				const data = {
					spuId: e.spuId,
					tobyC: this.buyCount
				}
				uni.navigateTo({
					url: `/pages/goodDetail/goodDetail?data=${encodeURIComponent(JSON.stringify(data))}`
				})
			},
			toBuy() {
				// console.log('e========carList', this.carList)
				const carlist = {
					carlist: this.carList,
					total: this.total
				}
				if (carlist.carlist.length <= 0) {
					// this.$refs.uNotify.show({'请选择'})
					uni.showToast({
						title: '请选择',
						icon: 'error',
						duration: 2000
					});
				} else {
					uni.navigateTo({
						url: `/pages/order/submitOrder/submitOrder?data=${encodeURIComponent(JSON.stringify(carlist))}`
					})
					this.$nextTick(() => {
						this.$refs.cartPopup.setShow(false)
						this.total = 0
					})
				}
			},
			onOrder() {
				uni.navigateTo({
					url: `/pages/order/myOrder/myOrder?type=0`
				})
			},
			onMyInfo() {
				const info = {
					customerPhone: this.cList.customerPhone
				}
				uni.setStorageSync("info", info)
				uni.navigateTo({
					url: `/pages/user/user`
				})
			},
			// 获取餐车列表
			async fatchDate() {
				var queryParmas = {
					id: this.cList.id
				}
				// console.log('idididididid', queryParmas)
				const result = await this.$request('post', '/sale/diningCarProduct/queryDiningCarProduct', queryParmas,
					true)
				if (result) {
					// this.goods = result.rows
					const queIds = new Set(result.rows.map(item => item.spuId));
					const spuIds = Array.from(queIds).join(',');
					const res = await this.$request('get', `/item/spu/queryByIds?spuIds=${spuIds}`)
					const data = res.data
					this.goods = data.filter(item => item.status !== 1)
				}
				const params = {
					storeId: this.cList.id
				}
				const res = await this.$request('get', '/order/tradeOrder/queryTradeOrder', params)
				if (res) {
					console.log('result', res.rows)
					this.txts = res.rows.length
				}
			},
			async carListMeg() {
				const res = await this.$request('get', `/front/shoppingCart/list`, {
					storeId: this.cList.id
				})
				if (res) {
					const carList = res.data
					this.buyCount = carList.length
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	.goods-category {
		width: calc(100% - 100rpx);
		border-radius: 14rpx;
		overflow: hidden;

		.category-box {
			height: 70rpx;
			width: 100%;
			display: flex;
			align-items: center;

			.category-item {
				font-size: 14px;
				flex-shrink: 0;
				height: 100%;
				line-height: 70rpx;
			}

			.on-category {
				color: #FFF;
				background-color: #000;
			}
		}

		.classify-icon {
			width: 100rpx;
			display: flex;
			align-items: center;
			justify-content: flex-end;
		}
	}

	.goods-item {
		width: 48%;
		overflow: hidden;
		box-sizing: border-box;
		border: solid 4px #FFF;
		border-radius: 5px;
		box-shadow: 0px 3px 10px 0px rgba(213, 221, 232, 0.5);

		.img {
			width: 100%;
			height: 180rpx;
			overflow: hidden;
			background: #EEE;
		}

		.title {
			width: 100%;
			overflow: hidden;
			white-space: nowrap;
			text-overflow: ellipsis;
			padding: 10rpx;
		}
	}

	.cart-bottom {
		width: 100%;
		position: fixed;
		left: 0;
		bottom: 0;
		height: 130rpx;
		box-sizing: border-box;
		background-color: #FFF;
		box-shadow: 0px -4px 16px 0px rgba(0, 0, 0, 0.15);
		z-index: 10800;

		.cart {
			width: calc(100% - 220rpx);
			border-radius: 5px;
			background-color: #FEEEE4;
			display: flex;
			align-items: center;
			height: 100%;

			.cart-total {
				padding-left: 40rpx;
				font-size: 16px;
				font-weight: 700;
			}
		}

		.balance {
			width: 200rpx;
			height: 100%;
			background-color: #FF0000;
			font-size: $uni-font-size-lg;
			border-radius: 5px;
			color: #FFF;
		}
	}

	.spec-box {
		position: relative;
		z-index: 99999;
	}

	.classify-popup {
		width: 400rpx;
	}

	.container {
		display: flex;
		flex-direction: column;
		/* 垂直排列子元素 */
		align-items: center;
		/* 垂直居中子元素 */
		justify-content: center;
		/* 水平居中子元素 */
	}

	.icon-container-l {
		margin-top: 10px;
		margin-left: 15px;
	}

	.icon-container-r {
		margin-left: 20px;
	}
</style>