<template>
	<view class="select-page">
		<view class="navbox">
			<view class="status_bar"></view>
			<uni-nav-bar
			left-icon="left"
			title="选择患者"
			@clickLeft="goBack"
			color="#8B2316"
			:border="false"
			backgroundColor="#eee"
		>
			<!-- <template #right>
				<view class="confirm-btn" :class="{ active: selectedIds.length > 0 }" @click="confirmSelect">
					<text class="confirm-text">确定({{ selectedIds.length }})</text>
				</view>
			</template> -->
		</uni-nav-bar>
		</view>

		<!-- 搜索框 -->
		<view class="search-bar">
			<view class="input-wrap">
				<input class="search-input" v-model.trim="keyword" placeholder="搜索患者的备注名、昵称或手机号" placeholder-class="ph" @input="$u.debounce(onSearch, 500)" />
			</view>
			<view class="search-btn" @click="onSearch">
				<uni-icons type="search" size="50rpx" color="#999" />
			</view>
		</view>

		<!-- 列表 -->
		<scroll-view class="list" scroll-y>
			<view class="item" @click="toggle(p.uuid)"  v-for="p in availablePatientList" :key="p.uuid">
				<image class="avatar" :src="getAvatarSrc(p)" mode="aspectFill" @error="handleAvatarError(p)" />
				<view class="name">{{  p.realName || p.nickname }}</view>
				<view class="check" >
					<view class="circle" :class="{ active: selectedIds.includes(p.uuid) }"></view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script setup>
	import { ref, computed,nextTick } from 'vue'
	import docUrl from '@/utils/docUrl.js'
	import { onShow,onLoad} from "@dcloudio/uni-app";
    import api from '@/api/api.js'
    import defaultImg from "@/static/default.png"
	const keyword = ref('')
	const selectedIds = ref([])
	const patientList = ref([])
	const selectedDetail = ref([])
	const availablePatientList = ref([])
	// 计算属性：显示所有患者，但标记已选中的状态
	// const availablePatientList = computed(() => {
	// 	return patientList.value
	// })
    const patientListByGBK = async () => {
		
		const res = await api.patientListByGBK();
		if(res.code == 1){
			patientList.value = res.data;
			availablePatientList.value = res.data;
			nextTick(() => {
				uni.hideLoading();
			});
			// if(res.data.length > 1000){
			// 	setTimeout(() => {
			// 		uni.hideLoading();
			// 	}, 5000);
			// }else{
			// 	uni.hideLoading();
			// }
		}
		
	};
	onLoad(() => {
		uni.showLoading({
			title: '加载中...',
			mask: true
		})
		// 读取已选中的成员ID
		try {
			const preSelected = uni.getStorageSync('preSelectedIds')
			if (Array.isArray(preSelected)) {
				selectedIds.value = [...preSelected]
				// 清理缓存
				uni.removeStorageSync('preSelectedIds')
			}
		} catch (e) {}
		patientListByGBK();
	})
    onShow(() => {
		
		// 根据已选中的ID更新selectedDetail
		updateSelectedDetail();
	});

	

	// 根据已选中的ID更新selectedDetail
	const updateSelectedDetail = () => {
		selectedDetail.value = selectedIds.value.map(id => {
			const p = patientList.value.find(x => x.uuid === id)
			return { uuid: id, realName: p?.realName || '', photo: p?.photo || '',nickname: p?.nickname || '' }
		})
	}

	const toggle = (id) => {
		const i = selectedIds.value.indexOf(id)
		if (i > -1) {
			return false;
			// 如果已选中，则取消选中
			selectedIds.value.splice(i, 1)
			const di = selectedDetail.value.findIndex(it => it.uuid === id)
			if (di > -1) selectedDetail.value.splice(di, 1)
		} else {
			// 如果未选中，则选中
			selectedIds.value.push(id)
			const p = patientList.value.find(x => x.uuid === id)
			selectedDetail.value.push({ uuid: id, realName: p?.realName || '', photo: p?.photo || '' })
			let payload = { uuid: id, realName: p?.realName || '', photo: p?.photo || '',nickname: p?.nickname || '' }
			const pages = getCurrentPages()
			const curr = pages[pages.length - 1]
			const ec = curr?.getOpenerEventChannel?.()
			ec?.emit && ec.emit('onPatientsSelected', payload)
			uni.navigateBack()
		}
	}

	const getAvatarSrc = (patient) => {
		if (patient?._avatarLoadError) return defaultImg
		return patient?.photo ? (docUrl + patient.photo) : defaultImg
	}

	const handleAvatarError = (patient) => {
		if (!patient) return
		patient._avatarLoadError = true
	}
	
	const onSearch = () => {
		if(keyword.value.replace(/\s/g, "")){
			availablePatientList.value = patientList.value.filter(p => p.realName.indexOf(keyword.value) !== -1 || (p.nickname && p.nickname.indexOf(keyword.value) !== -1) || p.mobile.indexOf(keyword.value) !== -1)
		}else{
			availablePatientList.value = patientList.value
		}
        //patientList.value = patientList.value.filter(p => p.realName.indexOf(keyword.value) !== -1 || (p.nickname && p.nickname.indexOf(keyword.value) !== -1) || p.mobile.indexOf(keyword.value) !== -1)
    }
	const goBack = () => uni.navigateBack()
	const confirmSelect = (id) => {
		const payload =patientList.value.find(x => x.uuid === id)
		// 通过事件通道回传
		try {
			const pages = getCurrentPages()
			const curr = pages[pages.length - 1]
			const ec = curr?.getOpenerEventChannel?.()
			ec?.emit && ec.emit('onPatientsSelected', payload)
		} catch (e) {}
		// 兜底：使用本地存储
		try { uni.setStorageSync('patientsSelectedPayload', payload) } catch (e) {}
		uni.navigateBack()
	}
</script>

<style lang="scss" scoped>
	.select-page{
		min-height: 100vh; background:#fefefe;overflow: hidden;
	}
	.confirm-text{ color:#fff; font-size: 28rpx;white-space: nowrap; }
	.confirm-btn{ background:#7f7f7f; padding: 10rpx 18rpx; border-radius: 26rpx; }
	.confirm-btn.active{ background:#8B2316; }
	.search-bar{
        border: 2rpx solid #eee;
		margin: 20rpx 30rpx;
		margin-top: calc(var(--status-bar-height) + 64px);
		 display:flex; align-items:center; gap: 16rpx;
		.input-wrap{ flex:1; background:#fff; border-radius: 12rpx; padding: 16rpx 20rpx; }
		.search-input{ font-size: 28rpx; color:#333; }
		.ph{ color:#bfbfbf; }
		.search-btn{ 
            display: flex;
            align-items: center;
            justify-content: center;
            width: 88rpx; height: 72rpx; background:#fff;
        }
	}
	.list{   border-radius: 12rpx; }
	.item{background:#fff; display:flex; align-items:center;padding: 24rpx 30rpx; border-bottom: 2rpx solid #eee; }
	.avatar{ width: 96rpx; height:96rpx; border-radius: 16rpx; background:#ffe; }
	.name{ flex:1; margin-left: 20rpx; font-size: 32rpx; color:#333; }
	.check{ padding-left: 12rpx; }
	.circle{ width: 40rpx; height: 40rpx; border-radius: 50%; border: 2rpx solid #cfcfcf; }
	.circle.active{ background:#8B2316; border-color:#8B2316; position: relative; }
	.circle.active::after{ content:''; position:absolute; left: 14rpx; top: 6rpx; width: 10rpx; height: 18rpx; border: 4rpx solid #fff; border-top: 0; border-left: 0; transform: rotate(45deg); }
</style>
