<script setup>
	import {
		onMounted,
		ref,
		defineEmits,
		onBeforeMount,
		onBeforeUnmount
	} from 'vue'
	import merchantVue from './merchant.vue';
	import {
		watch
	} from 'vue';
	import {
		apiImageUrl
	} from '../../API/api'
	const resultArray = ref([]);


	const orderTabs = ref([{
			orderState: 0,
			url: '/pages/sort/sort',
			title: '点餐'
		},
		{
			orderState: 1,
			url: '/pages/evaluate/evaluate',
			title: '评价'
		},
		{
			orderState: 2,
			url: '/pages/details/details',
			title: '商家'
		},
	])

	const currentIndex = ref(0);
	const tabs = ref([]);
	//1234265296552582582
	const businessId = ref('');
	const merchantId = ref(props.merchantId)
	const props = defineProps({
		merchantId: {
			type: String,
			required: true
		}
	});

	watch(() => props.merchantId, async (newVal) => {
		console.log('传过来的商家id', newVal);
		businessId.value = newVal;
		await leftGroup();
		await rightList();
	});

	onMounted(() => {});

	const leftGroup = async () => {
		try {
			console.log(businessId.value);
			const res = await uni.request({
				url: apiImageUrl + '/api/dishesGroup/list/dishesGroup',
				method: 'POST',
				data: {
					businessId: businessId.value
				},
			});
			if (res.data.code === 0) {
				console.log(res.data.data);
				const length = res.data.data.length;
				for (let i = 0; i < length; i++) {
					const index = i + 1;
					const groupName = res.data.data[i].groupName;
					resultArray.value.push(groupName);
				}

				console.log(resultArray.value);
			}
		} catch (error) {
			console.log('error', error);
		}
	};


const rightList = async () => {
  try {
    const res = await uni.request({
      url: apiImageUrl + '/api/dishes/list/dishes',
      method: 'POST',
      data: {
        businessId: businessId.value
      },
    });
    if (res.data.code === 0) {
      const filteredData = res.data.data.filter(item => item.status !== '1');
      historyList.value = filteredData;
      console.log('更新后的菜品列表:', historyList.value); 
    } else {
      console.error('请求失败:', res.data.message);
    }
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};

	const contentArea = ref(null);

	const switchTab = async (index) => {
	  currentIndex.value = index;
	  const updatedDishesQueryRequest = {
	    businessId: businessId.value,
	    dishesGroupId: index + 1,
	  };
	  try {
	    const res = await uni.request({
	      url: apiImageUrl + '/api/dishes/list/dishesVO',
	      method: 'POST',
	      data: JSON.stringify(updatedDishesQueryRequest),
	    });
	    if (res.data.code === 0) {
	      const filteredData = res.data.data.filter(item => item.status !== '1');
	      historyList.value = filteredData;
	    } else {
	      console.error('请求失败:', res.data.message);
	    }
	  } catch (error) {
	    console.error('Error fetching data:', error);
	  }
	  uni.scrollIntoView({
	    id: 'contentArea',
	    duration: 300,
	  });
	};
	const historyList = ref()

	// 口味的数组
	//const flavors = ref(['麻辣', '微辣', '酸甜', '清淡']);


	/* const showFlavorOptions = () => {
	  uni.showActionSheet({
	    itemList: flavors.value,
	    success: (res) => {
	      console.log('选择的口味:', flavors.value[res.tapIndex]);
	    },
	    fail: () => {
	      console.log('取消选择');
	    }
	  });
	}; */
const emit = defineEmits(['update-cart'])
	const cartItems = ref([]); 

        const addToCart = (item) => {

          cartItems.value.push({
            ...item,
            quantity: 1
          });
    
          uni.setStorageSync('cartItems', (cartItems.value));
    
          cartItems.value.forEach(item => {
            console.log(item.dishesName);
          });
    
          emit('update-cart', cartItems.value);
        };


</script>

<template>
	<view class="viewport">
		
		<view class="categories">
			
			<scroll-view class="primary" scroll-y>
				<view class="item" v-for="(tab, index) in resultArray" :key="index"
					:class="{ active: currentIndex === index }" @click="switchTab(index)">
					{{ tab }}
				</view>
			</scroll-view>
			
			<scroll-view class="secondary" scroll-y>
				
				<block v-if="currentIndex === 0">

				</block>
				<view class="panel">
					<view class="container">
						<view class="history-list">
							<view class="history-item" v-for="(item, index) in historyList" :key="index">

								<image class="history-img" :src="item.dishesImage"></image>
								<view class="history-info">
									<text class="history-title">{{ item.dishesName }}</text>
									<text class="history-description">玉米、蘑菇</text>
									<text class="history-time">月售234</text>
									<text class="history-money">￥{{ item.dishesPrice }}</text>

								</view>
								<view class="icon plus-animated" @click="() => addToCart(item)">
								  <uni-icons type="plus-filled" size="30" color="#4095e5"></uni-icons>
								</view>
								<!-- 模态框 -->
								<!-- <view v-if="isModalVisible" class="modal-mask">
				      <view class="modal-dialog">
				        <view class="modal-content">
				          <view class="modal-header">
				            请选择口味
				          </view>
				          <view class="modal-body">
				            <picker mode="selector" :range="flavors" range-key="name" @change="handleFlavorChange">
				              <view class="picker">
				                {{ selectedFlavor.value.name }}
				              </view>
				            </picker>
				          </view>
				          <view class="modal-footer">
				            <button type="primary" @tap="addToCart">加入购物车</button>
				          </view>
				        </view>
				      </view>
				    </view> -->
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<style lang="scss">
	page {
		height: 100%;
		overflow: hidden;
	}

	.viewport {
		height: 100%;
		display: flex;
		flex-direction: column;
	}

	.search {
		padding: 0 30rpx 20rpx;
		background-color: #fff;

		.input {
			display: flex;
			align-items: center;
			justify-content: space-between;
			height: 64rpx;
			padding-left: 26rpx;
			color: #8b8b8b;
			font-size: 28rpx;
			border-radius: 32rpx;
			background-color: #f3f4f4;
		}
	}

	.icon-search {
		&::before {
			margin-right: 10rpx;
		}
	}


	.primary {
		overflow: hidden;
		width: 180rpx;
		flex: none;
		background-color: #f6f6f6;

		.item {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 96rpx;
			font-size: 26rpx;
			color: #595c63;
			position: relative;

			&::after {
				content: '';
				position: absolute;
				left: 42rpx;
				bottom: 0;
				width: 96rpx;
				border-top: 1rpx solid #e3e4e7;
			}
		}

		.active {
			background-color: #fff;

			&::before {
				content: '';
				position: absolute;
				left: 0;
				top: 0;
				width: 8rpx;
				height: 100%;
				background-color: #4095e5;
			}
		}
	}

	.primary .item:last-child::after,
	.primary .active::after {
		display: none;
	}


	.secondary {
		background-color: #fff;
		width: 100%;

		.carousel {
			height: 400rpx;
			margin: 0 30rpx 20rpx;
			border-radius: 4rpx;
			overflow: hidden;
		}

		.panel {
			margin: 0 30rpx 0rpx;
		}

		.container {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 20rpx;
		}

		.history-list {
			width: 100%;
		}

		.history-item {
			display: flex;
			margin-bottom: 20rpx;
			flex-direction: row;
		}

		.history-img {
			width: 200rpx;
			height: 150rpx;
			margin-right: 20rpx;
			border-radius: 10px;
		}

		.history-info {
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			width: 100px;
		}

		.history-title {
			font-size: 32rpx;
			font-weight: bold;
		}

		.history-description {
			font-size: 28rpx;
		}

		.history-time {
			font-size: 20rpx;
			color: #999;
		}

		.history-money {
			font-size: 30rpx;
			color: black;
			font-weight: 700;
		}
	}

	.icon {
		margin-top: 30rpx;
	}
	
	@keyframes plus-slide-down {
	  0% {
	    transform: translateY(0);
	  }
	  50% {
	    transform: translateY(10px); 
	  }
	  100% {
	    transform: translateY(0);
	  }
	}
	
	.plus-animated {
	  animation-name: plus-slide-down;
	  animation-duration: 0.5s; 
	  animation-timing-function: ease-in-out; 
	  animation-iteration-count: 1; 
	  animation-fill-mode: forwards; 
	}
</style>