<template>
	<view class="search-center-page">
		<!-- 顶部搜索栏（带“取消”） -->
		<view class="search-header">
			<view class="header-row">
				<view class="search-wrap">
					<image class="search-icon" src="/static/icons/search.svg" mode="aspectFit" />
					<input
						class="search-input"
						v-model="keyword"
						placeholder="搜索"
						confirm-type="search"
						@confirm="onConfirm"
					/>
				</view>
				<view class="cancel" @click="onCancel">取消</view>
			</view>
		</view>

		<!-- 分类 chips（点击后滚动到对应区块） -->
		<scroll-view class="chips-scroll" scroll-x :show-scrollbar="false">
			<view class="chips-row">
				<view
					v-for="c in chips"
					:key="c.key"
					class="chip"
					:class="{ active: c.key === activeKey }"
					@click="onChipClick(c.key)"
				>
					{{ c.label }}
				</view>
			</view>
		</scroll-view>

		<scroll-view
			class="results-scroll"
			scroll-y
			:scroll-into-view="scrollIntoView"
			scroll-with-animation
		>
			<view class="empty-state" v-if="!keyword.trim()">
				<text class="empty-text">请输入关键词开始搜索</text>
			</view>

			<!-- 联络人 -->
			<view id="sec-contacts" class="section" v-if="keyword.trim()">
				<view class="section-header">
					<text class="section-title">联络人</text>
					<view class="section-arrow">></view>
				</view>
				<view class="section-body">
					<view v-if="contacts.length" class="list">
						<view
							v-for="u in contacts"
							:key="String(u.id)"
							class="row-item"
							@click="openContact(u)"
						>
							<UserAvatar
								:name="u.name"
								:id="String(u.id)"
								:src="''"
								:size="64"
								unit="rpx"
							/>
							<view class="row-main">
								<text class="row-title">{{ u.name }}</text>
								<text class="row-sub">{{ u.english_name || '' }}</text>
							</view>
						</view>
					</view>
					<view v-else class="empty-sub">暂无匹配联系人</view>
				</view>
				<view class="more-row" @click="onMore('contacts')">
					<text class="more-text">在联系人中搜索更多</text>
					<text class="more-arrow">></text>
				</view>
			</view>

			<!-- 应用 -->
			<view id="sec-apps" class="section" v-if="keyword.trim()">
				<view class="section-header">
					<text class="section-title">应用</text>
					<view class="section-arrow">></view>
				</view>
				<view class="section-body">
					<view v-if="apps.length" class="list">
						<view
							v-for="a in apps"
							:key="String(a.id)"
							class="row-item"
							@click="openApp(a)"
						>
							<SystemAvatar :name="a.name" :size="64" unit="rpx" />
							<view class="row-main">
								<text class="row-title">{{ a.name }}</text>
								<text class="row-sub">{{ a.categoryName || '' }}</text>
							</view>
						</view>
					</view>
					<view v-else class="empty-sub">暂无匹配应用</view>
				</view>
				<view class="more-row" @click="onMore('apps')">
					<text class="more-text">在应用中搜索更多</text>
					<text class="more-arrow">></text>
				</view>
			</view>

			<!-- 消息（当前仅占位，若后续有接口可替换） -->
			<view id="sec-messages" class="section" v-if="keyword.trim()">
				<view class="section-header">
					<text class="section-title">消息</text>
					<view class="section-arrow">></view>
				</view>
				<view class="section-body">
					<view class="empty-sub">暂无可展示的消息搜索内容</view>
				</view>
				<view class="more-row" @click="onMore('messages')">
					<text class="more-text">在消息中搜索更多</text>
					<text class="more-arrow">></text>
				</view>
			</view>

			<view class="bottom-spacer" />
		</scroll-view>

		<!-- 加载提示（只在搜索中显示） -->
		<view class="loading-mask" v-if="loading">
			<text class="loading-text">搜索中...</text>
		</view>
	</view>
</template>

<script>
import UserAvatar from '../../components/UserAvatar.vue'
import SystemAvatar from '../../components/SystemAvatar.vue'
import { getToken, getLaunchpadApps, searchUsers, ssoLogin } from '../../utils/api'

export default {
	components: { UserAvatar, SystemAvatar },
	data() {
		return {
			keyword: '',
			activeKey: 'contacts',
			scrollIntoView: '',
			loading: false,
			contacts: [],
			apps: [],
			chips: [
				{ key: 'messages', label: '消息' },
				{ key: 'contacts', label: '联系人' },
				{ key: 'apps', label: '应用' }
			]
		}
	},
	onLoad(options) {
		try {
			const kw = options && options.keyword ? options.keyword : ''
			if (/%[0-9A-Fa-f]{2}/.test(String(kw))) this.keyword = decodeURIComponent(String(kw))
			else this.keyword = String(kw || '')
		} catch (e) {}
		// 如果从外部带了关键字，直接触发一次搜索
		if (this.keyword.trim()) {
			this.doSearch()
		}
	},
	methods: {
		onCancel() {
			uni.navigateBack()
		},
		onConfirm() {
			this.doSearch()
		},
		onChipClick(key) {
			this.activeKey = key
			// scroll-into-view 需要存在于 scroll-view 内的子节点 id
			this.scrollIntoView = 'sec-' + key
		},
		async doSearch() {
			const q = String(this.keyword || '').trim()
			if (!q) {
				this.contacts = []
				this.apps = []
				return
			}
			this.loading = true
			try {
				const token = getToken()
				if (!token) {
					this.contacts = []
					this.apps = []
					uni.showToast({ title: '请先登录', icon: 'none' })
					return
				}

				// 1) 联络人
				let contacts = []
				try {
					const res = await searchUsers(token, q, 20)
					if (Array.isArray(res)) contacts = res
					else if (res && Array.isArray(res.items)) contacts = res.items
				} catch (e) {
					contacts = []
				}
				this.contacts = contacts

				// 2) 应用：复用应用中心的列表接口，然后本地模糊过滤
				let apps = []
				try {
					const res = await getLaunchpadApps()
					const items = res && Array.isArray(res.items) ? res.items : []
					const filtered = items.filter((it) => {
						const name = String(it.app_name || '')
						return name.includes(q)
					})
					// 和 app-center 页结构尽量保持一致（只用到 name/categoryName/id）
					apps = filtered.slice(0, 8).map((it) => ({
						id: it.app_id ?? it.id,
						name: it.app_name || '应用',
						categoryName: it.category_name || '分类'
					}))
				} catch (e) {
					apps = []
				}
				this.apps = apps
			} finally {
				this.loading = false
			}
		},
		openContact(u) {
			const id = String(u?.id ?? '').trim()
			if (!id) return
			uni.navigateTo({
				url:
					'/pages/contact-detail/index?contactId=' +
					encodeURIComponent(id) +
					'&contactName=' +
					encodeURIComponent(u?.name || '') +
					'&contactEnglishName=' +
					encodeURIComponent(u?.english_name || '')
			})
		},
		async openApp(app) {
			if (!app || !app.id) return
			uni.showLoading({ title: '打开中...' })
			try {
				const res = await ssoLogin(app.id)
				const redirectUrl = res && (res.redirect_url || res.redirectUrl)
				if (!redirectUrl) {
					uni.showToast({ title: '打开失败', icon: 'none' })
					return
				}
				const pageUrl =
					'/pages/webview/index?url=' +
					encodeURIComponent(redirectUrl) +
					'&title=' +
					encodeURIComponent(app.name || '应用')
				uni.navigateTo({ url: pageUrl })
			} catch (e) {
				uni.showToast({ title: '打开失败', icon: 'none' })
			} finally {
				uni.hideLoading()
			}
		},
		onMore(key) {
			// 当前项目尚未实现分模块“更多搜索”的详情页，这里先保持交互反馈
			const map = {
				contacts: '联系人',
				apps: '应用',
				messages: '消息'
			}
			uni.showToast({ title: `打开${map[key] || '更多'}搜索`, icon: 'none' })
		}
	}
}
</script>

<style scoped>
.search-center-page {
	height: 100vh;
	background: #f5f5f7;
	display: flex;
	flex-direction: column;
	position: relative;
}

.search-header {
	background: #fff;
	border-bottom: 1rpx solid #eee;
	padding: 0 24rpx 20rpx 24rpx;
	/* 顶部安全区：与消息/通讯录页面 custom-header 对齐，避免刘海屏点击不到 */
	padding-top: 88rpx;
	padding-top: max(88rpx, calc(24rpx + constant(safe-area-inset-top)));
	padding-top: max(88rpx, calc(24rpx + env(safe-area-inset-top)));
}

.header-row {
	display: flex;
	align-items: center;
	gap: 16rpx;
}

.search-wrap {
	flex: 1;
	min-width: 0;
	display: flex;
	align-items: center;
	gap: 12rpx;
	padding: 14rpx 18rpx;
	border-radius: 999rpx;
	background: #f0f0f0;
}

.search-icon {
	width: 28rpx;
	height: 28rpx;
	opacity: 0.75;
}

.search-input {
	flex: 1;
	min-width: 0;
	font-size: 28rpx;
	height: 44rpx;
	line-height: 44rpx;
	padding: 0;
}

.cancel {
	color: #259653;
	font-size: 28rpx;
	font-weight: 600;
	padding: 10rpx 8rpx;
	white-space: nowrap;
}

.chips-scroll {
	background: #fff;
	border-bottom: 1rpx solid #eee;
}

.chips-row {
	display: flex;
	align-items: center;
	gap: 16rpx;
	padding: 18rpx 24rpx;
}

.chip {
	padding: 10rpx 20rpx;
	border-radius: 999rpx;
	background: #f3f4f6;
	color: #111827;
	font-size: 26rpx;
	white-space: nowrap;
}

.chip.active {
	background: rgba(37, 150, 83, 0.12);
	color: #259653;
	font-weight: 700;
}

.results-scroll {
	flex: 1;
	min-height: 0;
	height: 0;
	padding: 20rpx 24rpx 0;
	box-sizing: border-box;
}

.empty-state {
	padding: 120rpx 10rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}
.empty-text {
	color: #9ca3af;
	font-size: 28rpx;
}

.section {
	margin-bottom: 22rpx;
	background: #fff;
	border-radius: 24rpx;
	padding: 18rpx 18rpx 14rpx;
	box-shadow: 0 2rpx 10rpx rgba(17, 24, 39, 0.04);
}

.section-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 6rpx 10rpx;
}

.section-title {
	font-size: 30rpx;
	font-weight: 800;
	color: #111827;
}
.section-arrow {
	color: #9ca3af;
	font-size: 32rpx;
	font-weight: 600;
}

.section-body {
	padding: 6rpx 6rpx 0;
}

.list {
	display: flex;
	flex-direction: column;
	gap: 14rpx;
}

.row-item {
	display: flex;
	align-items: center;
	gap: 18rpx;
	padding: 14rpx 12rpx;
	border-radius: 18rpx;
}

.row-main {
	flex: 1;
	min-width: 0;
}

.row-title {
	display: block;
	font-size: 30rpx;
	font-weight: 700;
	color: #111827;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.row-sub {
	display: block;
	margin-top: 6rpx;
	font-size: 24rpx;
	color: #6b7280;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.empty-sub {
	padding: 22rpx 6rpx 28rpx;
	color: #9ca3af;
	font-size: 26rpx;
}

.more-row {
	margin-top: 12rpx;
	padding: 16rpx 10rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	border-top: 1rpx solid #f3f4f6;
}

.more-text {
	font-size: 26rpx;
	color: #6b7280;
}

.more-arrow {
	font-size: 30rpx;
	color: #9ca3af;
	font-weight: 600;
}

.badge {
	min-width: 42rpx;
	height: 36rpx;
	padding: 0 12rpx;
	border-radius: 18rpx;
	background: #f5222d;
	color: #fff;
	font-size: 22rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-weight: 700;
}

.loading-mask {
	position: absolute;
	left: 0;
	right: 0;
	top: 0;
	bottom: 0;
	background: rgba(255, 255, 255, 0.65);
	display: flex;
	align-items: flex-start;
	justify-content: center;
	padding-top: 240rpx;
	z-index: 10;
}
.loading-text {
	background: rgba(255, 255, 255, 0.95);
	padding: 18rpx 28rpx;
	border-radius: 20rpx;
	font-size: 28rpx;
	color: #111827;
	font-weight: 700;
}

.bottom-spacer {
	height: 60rpx;
}
</style>

