<template>
	<view class="filter-section">
		<!-- 课程类型筛选 -->
		<picker 
			mode="selector" 
			:range="courseTypeOptions" 
			range-key="label"
			:value="courseTypeIndex"
			@change="onCourseTypeChange"
		>
			<view class="filter-item">
				<uni-icons type="apps" size="18" color="#5E6F8D" class="filter-icon" />
				<text class="filter-text">{{ courseTypeOptions[courseTypeIndex]?.label || '全部类型' }}</text>
				<uni-icons type="right" size="20" color="#A0AEC0" class="filter-arrow" />
			</view>
		</picker>
		
		<!-- 时间区间筛选 -->
		<view class="filter-item" @click="handleTimePick">
			<uni-icons type="calendar" size="18" color="#5E6F8D" class="filter-icon" />
			<text class="filter-text">{{ timeRangeText || '选择时间' }}</text>
			<uni-icons type="right" size="20" color="#A0AEC0" class="filter-arrow" />
		</view>
		
		<!-- 排序方式 -->
		<picker 
			mode="selector" 
			:range="sortOptions" 
			range-key="label"
			:value="sortIndex"
			@change="onSortChange"
		>
			<view class="filter-item">
				<uni-icons type="list" size="18" color="#5E6F8D" class="filter-icon" />
				<text class="filter-text">{{ sortOptions[sortIndex].label }}</text>
				<uni-icons type="right" size="20" color="#A0AEC0" class="filter-arrow" />
			</view>
		</picker>
	</view>
</template>

<script setup>
import { ref, watch, computed } from 'vue'

const props = defineProps({
	timeRangeText: {
		type: String,
		default: ''
	},
	sortOptions: {
		type: Array,
		default: () => [
			{ label: '默认排序', value: 'default', priceSort: null, remainingMost: false },
			{ label: '价格从低到高', value: 'priceAsc', priceSort: 'asc', remainingMost: false },
			{ label: '价格从高到低', value: 'priceDesc', priceSort: 'desc', remainingMost: false },
			{ label: '剩余名额最多', value: 'remainingMost', priceSort: null, remainingMost: true }
		]
	},
	sortIndex: {
		type: Number,
		default: 0
	},
	courseTypes: {
		type: Array,
		default: () => []
	},
	currentCourseTypeId: {
		type: [Number, String, null],
		default: null,
		validator: (val) => val === null || val === '' || !isNaN(Number(val))
	}
})

const emit = defineEmits(['update:sortIndex', 'timePick', 'courseTypeChange'])

const localSortIndex = ref(props.sortIndex)

const courseTypeOptions = computed(() => {
	return [{ id: null, label: '全部类型' }, ...props.courseTypes]
})

const courseTypeIndex = computed(() => {
	if (props.currentCourseTypeId === null || props.currentCourseTypeId === '') return 0
	const currentId = Number(props.currentCourseTypeId)
	const index = courseTypeOptions.value.findIndex(item => Number(item.id) === currentId)
	return index >= 0 ? index : 0
})

watch(() => props.sortIndex, (val) => {
	localSortIndex.value = val
})

const onSortChange = (e) => {
	localSortIndex.value = e.detail.value
	const sortOption = props.sortOptions[localSortIndex.value]
	
	console.log('[FilterSection] 排序方式变更:', { 
		index: localSortIndex.value, 
		value: sortOption 
	})
	
	if (sortOption.priceSort && sortOption.remainingMost) {
		console.warn('[FilterSection] 排序参数冲突警告: priceSort和remainingMost不能同时设置')
	}
	
	emit('update:sortIndex', localSortIndex.value)
}

const onCourseTypeChange = (e) => {
	const index = e.detail.value
	const selectedType = courseTypeOptions.value[index]
	// 确保返回数字类型而非字符串
	const typeId = selectedType.id !== null ? Number(selectedType.id) : null
	console.log('[FilterSection] 课程类型变更:', { 
		index, 
		id: typeId, 
		label: selectedType.label 
	})
	emit('courseTypeChange', typeId)
}

const handleTimePick = () => {
	console.log('[FilterSection] 触发时间选择器')
	emit('timePick')
}

const getFilterParams = () => {
	const sortOption = props.sortOptions[localSortIndex.value]
	const selectedType = courseTypeOptions.value[courseTypeIndex.value]
	
	const params = {
		sortType: sortOption.value,
		priceSort: sortOption.priceSort,
		remainingMost: sortOption.remainingMost,
		courseTypeId: selectedType.id !== null ? Number(selectedType.id) : null,
		courseTypeName: selectedType.label,
		timeRangeText: props.timeRangeText
	}
	console.log('[FilterSection] 获取筛选参数:', params)
	return params
}

const getSortType = () => {
	return props.sortOptions[localSortIndex.value].value
}

const comparePrice = (a, b, ascending = true) => {
	const getEffectivePrice = (item) => {
		if (item.storedValueAmount > 0 && item.pointCardAmount > 0) {
			return Math.min(item.storedValueAmount, item.pointCardAmount * 50)
		} else if (item.storedValueAmount > 0) {
			return item.storedValueAmount
		} else if (item.pointCardAmount > 0) {
			return item.pointCardAmount * 50
		}
		return 0
	}
	
	const priceA = getEffectivePrice(a)
	const priceB = getEffectivePrice(b)
	
	return ascending ? priceA - priceB : priceB - priceA
}

const compareByPaymentType = (a, b, sortType) => {
	const getPaymentType = (item) => {
		const hasPointCard = item.pointCardAmount > 0
		const hasStoredValue = item.storedValueAmount > 0
		
		if (hasPointCard && !hasStoredValue) return 1
		if (!hasPointCard && hasStoredValue) return 2
		if (hasPointCard && hasStoredValue) return 3
		return 0
	}
	
	const typeA = getPaymentType(a)
	const typeB = getPaymentType(b)
	
	switch (sortType) {
		case 'pointCardOnly':
			if (typeA === 1 && typeB !== 1) return -1
			if (typeA !== 1 && typeB === 1) return 1
			return 0
		case 'storedValueOnly':
			if (typeA === 2 && typeB !== 2) return -1
			if (typeA !== 2 && typeB === 2) return 1
			return 0
		case 'bothPayment':
			if (typeA === 3 && typeB !== 3) return -1
			if (typeA !== 3 && typeB === 3) return 1
			return 0
		default:
			return 0
	}
}

const sortCourses = (courses) => {
	const sortType = getSortType()
	if (!courses || !Array.isArray(courses)) return []
	
	const sorted = [...courses]
	
	switch (sortType) {
		case 'priceAsc':
			sorted.sort((a, b) => comparePrice(a, b, true))
			break
		case 'priceDesc':
			sorted.sort((a, b) => comparePrice(a, b, false))
			break
		case 'spotsDesc':
			sorted.sort((a, b) => (b.maxMembers - b.currentMembers) - (a.maxMembers - a.currentMembers))
			break
		case 'pointCardOnly':
		case 'storedValueOnly':
		case 'bothPayment':
			sorted.sort((a, b) => compareByPaymentType(a, b, sortType))
			break
		default:
			sorted.sort((a, b) => new Date(a.startTime) - new Date(b.startTime))
	}
	
	return sorted
}

defineExpose({
	getFilterParams,
	getSortType,
	sortCourses
})
</script>

<style lang="scss" scoped>
.filter-section {
	display: flex;
	flex-wrap: wrap;
	gap: 16rpx;

	.filter-item {
		flex: 1;
		min-width: calc(33.33% - 12rpx);
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 8rpx;
		padding: 18rpx 16rpx;
		background: #F5F7FA;
		border-radius: 16rpx;
		font-size: 24rpx;
		color: #5E6F8D;
		
		.filter-icon {
			display: flex;
			align-items: center;
		}
		
		.filter-arrow {
			margin-left: auto;
			display: flex;
			align-items: center;
		}
		
		.filter-text {
			max-width: 100rpx;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}
	}
}
</style>