import { ref, computed, watch } from 'vue'
import { getGroupCoursePage, getTypeLabels, searchGroupCourse } from '@/api/groupCourse.js'

export function useGroupCourseList() {
	const pageNum = ref(0)
	const pageSize = ref(10)
	const total = ref(0)
	const totalPages = ref(0)
	const loading = ref(false)
	const hasMore = ref(true)

	const courseList = ref([])

	const searchKeyword = ref('')
	const hotKeywords = ref(['燃脂', '瑜伽', '单车', '普拉提', '高强度'])

	const courseType = ref(null)
	const courseTypes = ref([])

	const sortOptions = ref([
		{ 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 }
	])
	const sortIndex = ref(0)

	const timePeriodOptions = ref([
		{ label: '全部', value: 'all' },
		{ label: '早上 (6-12 点)', value: 'morning', startHour: 6, endHour: 12 },
		{ label: '下午 (12-18 点)', value: 'afternoon', startHour: 12, endHour: 18 },
		{ label: '晚上 (18-24 点)', value: 'evening', startHour: 18, endHour: 24 }
	])
	const timePeriodIndex = ref(0)

	const showTimePicker = ref(false)
	const startDate = ref('')
	const endDate = ref('')
	const timeRangeText = ref('')

	const filteredCourseList = computed(() => {
		let result = [...courseList.value]

		if (searchKeyword.value) {
			result = result.filter(course =>
				course.courseName.includes(searchKeyword.value)
			)
		}

		if (startDate.value || endDate.value) {
			result = result.filter(course => {
				const courseDate = course.startTime.split('T')[0]
				if (startDate.value && courseDate < startDate.value) return false
				if (endDate.value && courseDate > endDate.value) return false
				return true
			})
		}

		const timePeriod = timePeriodOptions.value[timePeriodIndex.value]
		if (timePeriod.value !== 'all') {
			result = result.filter(course => {
				const courseHour = new Date(course.startTime).getHours()
				return courseHour >= timePeriod.startHour && courseHour < timePeriod.endHour
			})
		}

		const sortType = sortOptions.value[sortIndex.value]
		if (sortType.value !== 'id' || sortType.order !== 'asc') {
			result.sort((a, b) => {
				const valA = a[sortType.value] || 0
				const valB = b[sortType.value] || 0
				return sortType.order === 'asc' ? valA - valB : valB - valA
			})
		}

		return result
	})

	// 监听排序方式变化，重新获取数据
	watch(sortIndex, () => {
		console.log('[useGroupCourseList] 排序方式变化，触发重新查询')
		pageNum.value = 0
		fetchCourseList()
	})

	const getAllSearchParams = (searchBarRef, filterSectionRef, timePeriodRef, timeRangePickerRef) => {
		const searchParams = searchBarRef?.getSearchParams?.() || { keyword: searchKeyword.value }
		const filterParams = filterSectionRef?.getFilterParams?.() || { sortType: sortOptions.value[sortIndex.value].value }
		const timePeriodParams = timePeriodRef?.getTimePeriodParams?.() || { index: timePeriodIndex.value, value: timePeriodOptions.value[timePeriodIndex.value].value }
		const timeRangeParams = timeRangePickerRef?.getTimeRangeParams?.() || { startDate: startDate.value, endDate: endDate.value, timeRangeText: timeRangeText.value }

		const allParams = {
			search: searchParams,
			filter: filterParams,
			timePeriod: timePeriodParams,
			timeRange: timeRangeParams
		}

		console.log('[useGroupCourseList] 获取所有搜索参数:', allParams)
		return allParams
	}

	const handleSearch = (params) => {
		console.log('[useGroupCourseList] 搜索触发:', params)
		searchKeyword.value = params.keyword || ''
		pageNum.value = 0
		fetchCourseList()
	}

	const onTimePeriodChange = (option) => {
		console.log('[useGroupCourseList] 时间段选择:', option)
		pageNum.value = 0
		fetchCourseList()
	}

	const onTimeRangeConfirm = (params) => {
		console.log('[useGroupCourseList] 时间范围确认:', params)
		startDate.value = params.startDate || ''
		endDate.value = params.endDate || ''
		timeRangeText.value = params.timeRangeText
	}

	const onCourseTypeChange = (typeId) => {
		console.log('[useGroupCourseList] 课程类型选择:', typeId)
		courseType.value = typeId
		pageNum.value = 0
		fetchCourseList()
	}

	const clearCourseType = () => {
		courseType.value = null
		pageNum.value = 0
		fetchCourseList()
	}

	const handleBooking = (course) => {
		console.log('[useGroupCourseList] 预约课程:', course)
		uni.showToast({
			title: `预约课程：${course.courseName}`,
			icon: 'success'
		})
	}

	const goDetail = (courseId) => {
		console.log('[useGroupCourseList] 跳转到课程详情:', courseId)
		uni.navigateTo({
			url: `/pages/groupCourse/detail?id=${courseId}`
		})
	}

	const buildSearchParams = () => {
		const sortOption = sortOptions.value[sortIndex.value]
		const timePeriod = timePeriodOptions.value[timePeriodIndex.value]
		
		const params = {
			page: pageNum.value,
			size: pageSize.value
		}

		if (searchKeyword.value) {
			params.courseName = searchKeyword.value
		}

		if (courseType.value) {
			params.courseType = courseType.value
		}

		if (startDate.value) {
			params.startDate = startDate.value
		}

		if (endDate.value) {
			params.endDate = endDate.value
		}

		if (timePeriod.value && timePeriod.value !== 'all') {
			params.timePeriod = timePeriod.value
		}

		if (sortOption.priceSort) {
			params.priceSort = sortOption.priceSort
		}

		if (sortOption.remainingMost) {
			params.remainingMost = sortOption.remainingMost
		}

		return params
	}

	const hasActiveFilters = () => {
		return searchKeyword.value || 
			courseType.value || 
			startDate.value || 
			endDate.value || 
			timePeriodOptions.value[timePeriodIndex.value].value !== 'all' ||
			sortIndex.value !== 0
	}

	const fetchCourseList = async (isLoadMore = false) => {
		if (loading.value) return

		loading.value = true

		try {
			const currentPage = isLoadMore ? pageNum.value + 1 : pageNum.value
			pageNum.value = currentPage

			const searchParams = buildSearchParams()
			searchParams.page = currentPage

			console.log('[useGroupCourseList] 请求参数:', JSON.stringify(searchParams, null, 2))

			const result = await searchGroupCourse(searchParams)

			console.log('[useGroupCourseList] 响应结果:', JSON.stringify(result, null, 2))

			if (result && result.data && result.data.content) {
				const { content: list, totalElements: totalCount, currentPage: respPage, totalPages: pages } = result.data

				if (isLoadMore) {
					courseList.value = [...courseList.value, ...list]
				} else {
					courseList.value = list
				}

				total.value = totalCount
				totalPages.value = pages
				hasMore.value = currentPage < pages - 1

				console.log('[useGroupCourseList] 团课列表获取成功:', {
					total: total.value,
					currentPage: pageNum.value,
					totalPages: totalPages.value,
					hasMore: hasMore.value
				})
			} else {
				console.error('[useGroupCourseList] 获取团课列表失败:', {
					result: result,
					message: result?.message || '未知错误',
					code: result?.code,
					success: result?.success
				})
			}
		} catch (error) {
			console.error('[useGroupCourseList] 获取团课列表异常 - 错误详情:', {
				error: error,
				message: error?.message || '无错误信息',
				code: error?.code,
				statusCode: error?.statusCode,
				response: error?.response,
				stack: error?.stack
			})
			uni.showToast({
				title: `获取课程列表失败: ${error?.message || '网络错误'}`,
				icon: 'none'
			})
		} finally {
			loading.value = false
		}
	}

	const loadMore = () => {
		if (!hasMore.value || loading.value) return
		fetchCourseList(true)
	}

	const onScrollToLower = () => {
		loadMore()
	}

	return {
		pageNum,
		pageSize,
		total,
		totalPages,
		loading,
		hasMore,
		courseList,
		searchKeyword,
		hotKeywords,
		courseType,
		courseTypes,
		sortOptions,
		sortIndex,
		timePeriodOptions,
		timePeriodIndex,
		showTimePicker,
		startDate,
		endDate,
		timeRangeText,
		filteredCourseList,

		getAllSearchParams,
		handleSearch,
		onTimePeriodChange,
		onTimeRangeConfirm,
		onCourseTypeChange,
		clearCourseType,
		handleBooking,
		goDetail,
		fetchCourseList,
		buildSearchParams,
		hasActiveFilters,
		loadMore,
		onScrollToLower
	}
}