<template>
	<view class="filter-container">
		<!-- 筛选标签栏 -->
		<view class="filter-bar">
			<view 
				v-for="(item, index) in filterTabs" 
				:key="index"
				class="filter-item"
				:class="{ 
					'active': activeIndex === index,
					'has-value': hasValue(item.key)
				}"
				@click.stop="toggleFilter(index)"
			>
				<text class="filter-text">{{ item.label }}</text>
				<image 
					class="arrow-icon"
					:src="activeIndex === index ? arrowUp : arrowDown" 
					mode="widthFix"
				/>
			</view>
		</view>

		<!-- 遮罩层 - 只覆盖tab栏以下区域 -->
		<view 
			v-if="showDropdown || isAnimating" 
			class="filter-mask"
			:class="{ 'mask-show': showDropdown, 'mask-hide': !showDropdown && isAnimating }"
			:style="{ top: maskTop + 'px' }"
			@click="closeFilter"
		></view>

		<!-- 下拉筛选面板 -->
		<view 
			class="filter-panel"
			:class="{ 
				'panel-show': showDropdown, 
				'panel-hide': !showDropdown && isAnimating 
			}"
			:style="{ top: panelTop + 'px' }"
			v-if="showDropdown || isAnimating"
		>
			<!-- 服务类型 -->
			<view v-if="activeIndex === 0" class="filter-content service-type" :class="{ 'content-active': showDropdown }">
				<view class="option-list">
					<view 
						v-for="(option, idx) in serviceOptions" 
						:key="idx"
						class="option-item"
						:class="{ 'active': selectedService === option.value }"
						@click="selectService(option.value)"
					>
						<text class="option-text">{{ option.label }}</text>
						<image 
							v-if="selectedService === option.value"
							class="check-icon"
							:src="checkIcon" 
							mode="widthFix"
						/>
					</view>
				</view>
			</view>

			<!-- 附近筛选 -->
			<view v-if="activeIndex === 1" class="filter-content distance" :class="{ 'content-active': showDropdown }">
				<view class="option-buttons distance-buttons">
					<view 
						v-for="(option, idx) in distanceOptions" 
						:key="idx"
						class="option-button"
						:class="{ 'active': selectedDistance === option.value }"
						@click="selectDistance(option.value)"
					>
						<text class="button-text">{{ option.label }}</text>
					</view>
				</view>
				<view class="action-buttons">
					<button class="btn reset" @click="resetFilter">重置</button>
					<button class="btn confirm" @click="confirmFilter">完成</button>
				</view>
			</view>

			<!-- 价格筛选 -->
			<view v-if="activeIndex === 2" class="filter-content price" :class="{ 'content-active': showDropdown }">
				<view class="option-buttons price-buttons">
					<view 
						v-for="(option, idx) in priceOptions" 
						:key="idx"
						class="option-button"
						:class="{ 
							'active': selectedPrice === option.value,
							'custom': option.value === 'custom'
						}"
						@click="selectPrice(option.value)"
					>
						<text class="button-text">{{ option.label }}</text>
					</view>
					
					<!-- 自定义价格输入 -->
					<view 
						class="custom-price-container" 
						:class="{ 
							'expanded': selectedPrice === 'custom',
							'active': selectedPrice === 'custom'
						}"
						@click="handleCustomPriceClick"
					>
						<view class="custom-price-inner">
							<view class="custom-button-content">
								<text>自定义</text>
							</view>
							<view class="custom-input-content">
								<input 
									type="number" 
									v-model="customMin" 
									placeholder="最低价"
									class="price-input"
									@input="validatePrice"
									@click.stop
								/>
								<text class="separator">——</text>
								<input 
									type="number" 
									v-model="customMax" 
									placeholder="最高价"
									class="price-input"
									@input="validatePrice"
									@click.stop
								/>
							</view>
						</view>
					</view>
				</view>
				
				<view class="action-buttons">
					<button class="btn reset" @click="resetFilter">重置</button>
					<button class="btn confirm" @click="confirmFilter">完成</button>
				</view>
			</view>

			<!-- 排序 -->
			<view v-if="activeIndex === 3" class="filter-content sort" :class="{ 'content-active': showDropdown }">
				<view class="option-list">
					<view 
						v-for="(option, idx) in sortOptions" 
						:key="idx"
						class="option-item"
						:class="{ 'active': selectedSort === option.value }"
						@click="selectSort(option.value)"
					>
						<text class="option-text">{{ option.label }}</text>
						<image 
							v-if="selectedSort === option.value"
							class="check-icon"
							:src="checkIcon" 
							mode="widthFix"
						/>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: 'filterVue',
		data() {
			return {
				activeIndex: -1,
				showDropdown: false,
				isAnimating: false, // 动画状态
				panelTop: 0,
				maskTop: 0,
				
				// 图标地址
				arrowUp: 'https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/f07dab0b-0211-4e32-be49-8a02835293a0.png',
				arrowDown: 'https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/81040e24-3169-4959-aec4-54867c72c37f.png',
				checkIcon: 'https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/bac1fd8f-402f-4ee7-b61a-3ef86832a4f0.png',
				
        filterTabs: [
					{ label: "服务类型", key: "service" },
					{ label: "附近", key: "distance" },
					{ label: "价格", key: "price" },
					{ label: "排序", key: "sort" }
				],
				
				// 服务类型
				serviceOptions: [
					{ label: "到家服务", value: 1 },
					{ label: "到店服务", value: 2 }
				],
				selectedService: null,

				// 附近 (单位：米)
        distanceOptions: [
					{ label: "500m", value: 500 },
					{ label: "2km", value: 2000 },
					{ label: "5km", value: 5000 },
					{ label: "10km", value: 10000 },
					{ label: "20km", value: 20000 }
				],
				selectedDistance: null,

				// 价格
				priceOptions: [
					{ label: "0-99元", value: "0-99" },
					{ label: "100-199元", value: "100-199" },
					{ label: "200-299元", value: "200-299" },
					{ label: "300-499元", value: "300-499" },
					{ label: "500-1000元", value: "500-1000" }
				],
				selectedPrice: null,
				customMin: '',
				customMax: '',
				
        // 排序
				sortOptions: [
					{ label: "离我最近", value: "distance" },
					{ label: "销量最高", value: "sales" },
					{ label: "价格最低", value: "price_asc" },
					{ label: "价格最高", value: "price_desc" },
				],
				selectedSort: null
			};
		},

    watch: {
      // 过滤弹窗出现时禁止滚动
      showDropdown(newVal) {
        if (newVal) {
          // 获取页面实例并添加锁定类
          const pages = getCurrentPages();
          const currentPage = pages[pages.length - 1];
          if (currentPage && currentPage.$vm && currentPage.$vm.$el) {
            currentPage.$vm.$el.classList.add('scroll-locked');
          }
        } else {
          // 移除锁定类
          const pages = getCurrentPages();
          const currentPage = pages[pages.length - 1];
          if (currentPage && currentPage.$vm && currentPage.$vm.$el) {
            currentPage.$vm.$el.classList.remove('scroll-locked');
          }
        }
      }
    },

		methods: {
			toggleFilter(index) {
				if (this.activeIndex === index && this.showDropdown) {
					// 点击相同的tab，关闭下拉
					this.closeFilter();
				} else {
					// 打开新的筛选面板
					this.isAnimating = true;
					
					// 先计算位置
					this.$nextTick(() => {
						const query = uni.createSelectorQuery().in(this);
						query.select('.filter-bar').boundingClientRect(data => {
							if (data) {
								// 获取筛选栏底部位置
								this.panelTop = data.bottom;
								this.maskTop = data.bottom;
								
								// 设置新的激活索引
								this.activeIndex = index;
								
								// 延迟显示下拉，确保DOM更新
								setTimeout(() => {
									this.showDropdown = true;
								}, 10);
							}
						}).exec();
					});
				}
			},
			
			getIconColor(index) {
				if (this.activeIndex === index) {
					return '#E8101E';
				}
				if (this.hasValue(this.filterTabs[index].key)) {
					return '#E8101E';
				}
				return '#666';
			},
			
			hasValue(key) {
				switch (key) {
					case 'service':
						return this.selectedService !== null;
					case 'distance':
						return this.selectedDistance !== null;
					case 'price':
						return this.selectedPrice !== null || (this.customMin || this.customMax);
					case 'sort':
						return this.selectedSort !== null;
					default:
						return false;
				}
			},
			
			selectService(value) {
				this.selectedService = value;
				// 立即生效并关闭面板
				this.emitFilterChange();
				this.closeFilter();
			},
			
			selectDistance(value) {
				this.selectedDistance = value;
				// 附近筛选需要点击"完成"按钮，这里只记录选择，不立即生效
			},
			
			selectPrice(value) {
				this.selectedPrice = value;
			},
			
			handleCustomPriceClick() {
				this.selectedPrice = 'custom';
			},
			
			validatePrice() {

			},
			
			selectSort(value) {
				this.selectedSort = value;
				// 排序立即生效
				this.emitFilterChange();
				this.closeFilter();
			},
			
			resetFilter() {
				// 重置当前激活的筛选类型
				switch (this.activeIndex) {
					case 0:
						this.selectedService = null;
						break;
					case 1:
						this.selectedDistance = null;
						break;
					case 2:
						this.selectedPrice = null;
						this.customMin = '';
						this.customMax = '';
						break;
					case 3:
						this.selectedSort = null;
						break;
				}
			},
			
			confirmFilter() {
				// 对于需要确认的筛选类型（附近和自定义价格），点击完成时生效
				if (this.activeIndex === 1 || this.activeIndex === 2) {
					this.emitFilterChange();
				}
				this.closeFilter();
			},
			
			closeFilter() {
				this.showDropdown = false;
				
				// 等待动画完成后重置状态
				setTimeout(() => {
					this.isAnimating = false;
					this.activeIndex = -1;
				}, 300);
			},
			
			emitFilterChange() {
				const filterData = {
					serviceType: this.selectedService,
					distance: this.selectedDistance,
					sortType: this.selectedSort,
					minPrice: null,
					maxPrice: null
				};
				
				// 处理价格筛选
				if (this.selectedPrice === 'custom') {
					if (this.customMin || this.customMax) {
						filterData.minPrice = this.customMin ? parseFloat(this.customMin) : null;
						filterData.maxPrice = this.customMax ? parseFloat(this.customMax) : null;
					}
				} else if (this.selectedPrice) {
					// 解析预设的价格区间
					const match = this.selectedPrice.match(/(\d+)-(\d+)/);
					if (match) {
						filterData.minPrice = parseFloat(match[1]);
						filterData.maxPrice = parseFloat(match[2]);
					}
				}
				
				console.log('发送筛选数据:', filterData);
				this.$emit('filter-change', filterData);
			}
		}
	};
</script>

<style lang="less" scoped>

.filter-container {
	width: 100%;
	background: #fff;
	position: relative;
	z-index: 1000;
}

.filter-bar {
	display: flex;
	justify-content: space-around;
	align-items: center;
	height: 80rpx;
	background: #fff;
  border-top: hsla(0, 0%, 95%, 0.795)  solid 1px;
	
	.filter-item {
		display: flex;
		align-items: center;
		font-size: 28rpx;
		color: #666;
		padding: 0 10rpx;
		transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
		
		.filter-text {
			margin-right: 8rpx;
		}
		
		.arrow-icon {
			width: 13rpx;
			height: 8rpx;
			transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
		}
		
		&.active,
		&.has-value {
			color: #333333;
			font-weight: 500;
		}
		
		&:active {
			opacity: 0.7;
		}
	}
}

/* 遮罩层 */
.filter-mask {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	z-index: 999;
	opacity: 0;
	transition: opacity 0.3s cubic-bezier(0.4, 0, 0.2, 1);
	pointer-events: none;
	
	&.mask-show {
		opacity: 1;
		pointer-events: auto;
	}
	
	&.mask-hide {
		opacity: 0;
		pointer-events: none;
	}
}

/* 筛选面板 - 在筛选栏正下方平滑下拉出现 */
.filter-panel {
	position: fixed;
	left: 0;
	right: 0;
	background: #fff;
	z-index: 1001;
	border-radius: 0 0 20rpx 20rpx;
	transform-origin: top center;
	transform: scaleY(0);
	opacity: 0;
	max-height: 60vh;
	overflow-y: auto;
	transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);  // 弹窗下来的速度
	
	&.panel-show {
		transform: scaleY(1);
		opacity: 1;
	}
	
	&.panel-hide {
		transform: scaleY(0);
		opacity: 0;
	}
}

/* 筛选内容区域 */
.filter-content {
	padding: 10rpx 50rpx 20rpx 50rpx;
	opacity: 0;
	transform: translateY(-10px);
	transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) 0.2s;  // 弹窗内容出现的速度
	
	&.content-active {
		opacity: 1;
		transform: translateY(0);
	}
	
	/* 服务类型和排序的选项列表样式 */
	.option-list {
		.option-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 24rpx 0;
			border-bottom: 1rpx solid #f5f5f5;
			font-size: 28rpx;
			color: #333;
			transition: all 0.3s ease;
			
			&:last-child {
				border-bottom: none;
			}
			
			&.active {
				color: #E8101E;
			}
			
			.check-icon {
				width: 25rpx;
				height: 20rpx;
				margin-right: 490rpx;
				transition: all 0.2s ease;
      }
		}
	}
	
	/* 附近和价格的按钮样式 */
	.option-buttons {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
		
		.option-button {
			flex: 0 0 calc(25% - 16rpx);
			height: 60rpx;
      // padding: 0 5rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			background: #f5f5f5;
			border-radius: 10rpx;
			font-size: 24rpx;
      font-weight: 500;
			color: #666;
			transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);  // 选项变红动画时间
			
			
			
			.button-text {
        font-weight: 500;
				font-size: 24rpx;
			}
			&.active {
				background: #FFECF0;
				color: #E8101E;
			}
		}
		
		/* 距离筛选的特殊样式 */
		&.distance-buttons {
			margin-bottom: 40rpx;
		}
		
		/* 价格筛选的特殊样式 */
		&.price-buttons {
			margin-bottom: 30rpx;
			
			/* 自定义价格容器 */
			.custom-price-container {
				flex: 0 0 calc(25% - 14rpx);
				height: 60rpx;
				background: #f5f5f5;
				border-radius: 10rpx;
				position: relative;
				transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
				overflow: hidden;
				cursor: pointer;
				
				&.expanded {
					flex: 0 0 calc(50% - 15rpx); /* 展开时宽度加倍 */
					// background: #FFECF0;
				}
				
				&.active {
					// background: #FFECF0;
				}
				
				.custom-price-inner {
					position: absolute;
					top: 0;
					left: 0;
					width: 200%; /* 内部宽度是容器的2倍，用于动画 */
					height: 100%;
					display: flex;
					transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
				}
				
				.custom-button-content {
					flex: 0 0 50%; /* 占50%宽度 */
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 24rpx;
					color: #666;
					height: 100%;
					
					.custom-price-container.active & {
						color: #E8101E;
					}
				}
				
				.custom-input-content {
					flex: 0 0 50%; /* 占50%宽度 */
					display: flex;
					align-items: center;
					justify-content: space-between;
					opacity: 0;
					transition: opacity 0.15s ease 0.15s;
					
					.price-input {
						flex: 1;
						height: 50rpx;
						padding: 0 10rpx;
						background: transparent;
						border: none;
						font-size: 24rpx;
						color: #333;
						text-align: center;
						
						&::placeholder {
							color: #999;
							font-size: 24rpx;
						}
					}
					
					.separator {
						color: #9999998f;
						font-size: 26rpx;
					}
				}
				
				&.expanded .custom-price-inner {
					transform: translateX(-50%); /* 向左移动50%，显示输入框部分 */
				}
				
				&.expanded .custom-input-content {
					opacity: 1;
				}
			}
		}
	}
}

/* 操作按钮区域 */
.action-buttons {
	display: flex;
	justify-content: space-between;
	gap: 20rpx;
	margin: 20rpx 0;
	opacity: 0;
	transform: translateY(10px);
	transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) 0.2s;
	
	.filter-content.content-active & {
		opacity: 1;
		transform: translateY(0);
	}
	
	.btn {
		flex: 1;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 28rpx;
		border-radius: 10rpx;
		transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

    &::after {
			border: 0 !important;
		}
		
		&.reset {
			background: #f5f5f5;
			color: #666;
			
			&:active {
				background: #e8e8e8;
			}
		}
		
		&.confirm {
			background: #FF3344;
			color: #fff;
			
			&:active {
				background: #e62b3b;
			}
		}
	}
}
</style>