<template>
	<view class="all-services-page">
		<nav-bar title="全部分类" :showBack="false"></nav-bar>
		<!-- 顶部搜索栏（暂时注释）
		<view class="header-search">
			<view class="search-input-wrap">
				<uni-icons type="search" size="14" color="#999"></uni-icons>
				<input class="search-input" v-model="searchValue" placeholder="搜索服务内容"
					placeholder-class="placeholder-style" />
			</view>
		</view>
		-->

		<!-- 主体分类区域 -->
		<view class="main-content">
			<!-- 左侧侧边栏 -->
			<scroll-view scroll-y class="sidebar">
				<view v-for="(item, index) in allData" :key="index"
					:class="['sidebar-item', { active: activeSidebar === index }]" @click="activeSidebar = index">
					<text>{{ item.title }}</text>
				</view>
			</scroll-view>

			<!-- 右侧服务列表 -->
			<scroll-view scroll-y class="content-view">
				<view class="category-section" v-for="(cat, index) in currentCategories" :key="index">
					<view class="service-grid">
						<view class="service-cell" v-for="(service, sIndex) in cat.items" :key="sIndex"
							@click="onServiceClick(service)">
							<view class="icon-wrapper">
								<image :src="service.icon" class="service-icon" mode="aspectFill"></image>
							</view>
							<text class="service-name">{{ service.name }}</text>
						</view>
					</view>
				</view>

			</scroll-view>
		</view>

		<custom-tabbar></custom-tabbar>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import navBar from '@/components/nav-bar/index.vue'
import customTabbar from '@/components/custom-tabbar/index.vue'
import { listAll as getClassifications } from '@/api/service/classification'
import { listAll as getServices } from '@/api/service/list'
import { listMyServices } from '@/api/system/store'

const searchValue = ref('')
const activeSidebar = ref(0)
const allData = ref([])
/** 当前用户可用的服务ID列表 */
const myServiceIds = ref([])

/** 前端搜索 + 权限过滤 */
const filteredData = computed(() => {
	let data = allData.value

	// 先按权限过滤：只展示用户有权限的服务类型
	if (myServiceIds.value.length > 0) {
		const idSet = new Set(myServiceIds.value)
		data = data.map(group => ({
			...group,
			categories: group.categories.map(cat => ({
				...cat,
				items: cat.items.filter(s => idSet.has(s.id))
			})).filter(cat => cat.items.length > 0)
		})).filter(group => group.categories.some(cat => cat.items.length > 0))
	}

	// 再按搜索关键词过滤
	const keyword = searchValue.value.trim().toLowerCase()
	if (!keyword) return data
	return data.map(group => ({
		...group,
		categories: group.categories.map(cat => ({
			...cat,
			items: cat.items.filter(s => s.name.toLowerCase().includes(keyword))
		})).filter(cat => cat.items.length > 0)
	})).filter(group => group.categories.some(cat => cat.items.length > 0))
})

const currentCategories = computed(() => {
	if (filteredData.value.length === 0 || !filteredData.value[activeSidebar.value]) return []
	return filteredData.value[activeSidebar.value].categories
})

/** 获取当前用户可下单的服务ID列表 */
const fetchMyServiceIds = async () => {
	try {
		const res = await listMyServices()
		// 兼容多种响应格式，确保取到数组并保持字符串类型
		const ids = res?.data ?? res?.rows ?? res ?? []
		myServiceIds.value = Array.isArray(ids) ? ids.map(String) : []
		console.log('我的可用服务ID:', myServiceIds.value)
	} catch (error) {
		console.error('获取可用服务列表失败，将展示全部服务', error)
		myServiceIds.value = []
	}
}

const loadData = async () => {
	try {
		const [classifications, services] = await Promise.all([
			getClassifications(),
			getServices()
		])

		console.log('分类数据:', classifications)
		console.log('服务数据:', services)

		allData.value = classifications.map(classification => {
			const categoryServices = services.filter(
				service => service.classificationId === classification.id
			)

			console.log(`分类 ${classification.name} 的服务:`, categoryServices)

			return {
				title: classification.name,
				categories: [{
					items: categoryServices.map(service => ({
						...service,
						name: service.name,
						icon: service.iconUrl,
						type: service.id
					}))
				}]
			}
		})

		console.log('最终数据结构:', allData.value)
	} catch (error) {
		console.error('加载服务数据失败:', error)
		uni.showToast({ title: '加载失败', icon: 'none' })
	}
}

onMounted(() => {
	loadData()
	fetchMyServiceIds()
})

const onServiceClick = (service) => {
	if (service.id) {
		uni.setStorageSync('currentService', service)
		uni.navigateTo({ url: `/pages/service/detail/index?serviceId=${service.id}` })
	} else {
		uni.showToast({ title: service.name + ' 功能即将上线', icon: 'none' })
	}
}
</script>

<style lang="scss" scoped>
.all-services-page {
	height: 100vh;
	display: flex;
	flex-direction: column;
	background-color: #fff;
}

.header-search {
	padding: 16rpx 32rpx;
	background-color: #fff;
	border-bottom: 2rpx solid #EEEEEE;
}

.search-input-wrap {
	flex: 1;
	display: flex;
	align-items: center;
	background: #f5f5f5;
	border-radius: 32rpx;
	padding: 12rpx 20rpx;
	gap: 12rpx;
}

.search-input {
	flex: 1;
	font-size: 26rpx;
}

.placeholder-style {
	color: #999;
	font-size: 26rpx;
}

.main-content {
	flex: 1;
	display: flex;
	overflow: hidden;
}

.sidebar {
	width: 200rpx;
	background-color: #f7f8fa;
}

.sidebar-item {
	padding: 28rpx 0;
	text-align: center;
	font-size: 26rpx;
	color: #666;
	position: relative;
}

.sidebar-item.active {
	background-color: #fff;
	color: #333;
	font-weight: bold;
}

.sidebar-item.active::before {
	content: '';
	position: absolute;
	left: 0;
	top: 50%;
	transform: translateY(-50%);
	width: 6rpx;
	height: 40rpx;
	background-color: #f7ca3e;
	border-radius: 0 6rpx 6rpx 0;
}

.content-view {
	flex: 1;
	padding: 32rpx;
}

.category-section {
	margin-bottom: 48rpx;
}

.service-grid {
	display: flex;
	flex-wrap: wrap;
}

.service-cell {
	width: 33.33%;
	display: flex;
	flex-direction: column;
	align-items: center;
	margin-bottom: 32rpx;
}

.icon-wrapper {
	width: 96rpx;
	height: 96rpx;
	background-color: #fff;
	border-radius: 24rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
	margin-bottom: 16rpx;
}

.service-icon {
	width: 100%;
	height: 100%;
}

.service-name {
	font-size: 24rpx;
	color: #666;
	text-align: center;
}
</style>
