<template>
	<u-popup v-model="visible" mode="bottom" height="80%">
		<view class="project-select">
			<view class="project-select-btns">
				<u-button size="mini" type="info" @click="handleCancel">取消</u-button>
				<text></text>
				<u-button size="mini" type="primary" @click="handleConfirm">确定</u-button>
			</view>
			<view class="project-select-filter">
				<u-search placeholder="请输入项目名称" height="60" v-model="searchKey" :show-action="false"
					@change="handleSearchKey"></u-search>
			</view>
			<scroll-view scroll-y="true" class="project-select-inner">
				<view class="project-select-inner-wrap">
					<view class="li" v-for="(item,idx) in props.list" :key="idx"
						:class="selectObj[props.valueKey] == item[props.valueKey]?'active':''" @click="handerChangList(item)">{{item[props.labelKey]}}
					</view>
				</view>
			</scroll-view>
		</view>
	</u-popup>
</template>

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

	const props = defineProps({
		modelValue: {
			type: Boolean,
			default: false
		},
		searchKey: {
			type: String,
			default: ''
		},
		list: {
			type: Array,
			default: () => []
		},
		labelKey: {
			type: String,
			default: 'label'
		},
		valueKey: {
			type: String,
			default: 'value'
		},
		selectId: {
			type: String,
			default: ''
		}
	})

	const emit = defineEmits(['update:modelValue', 'cancel', 'confirm', 'searchChange'])

	const visible = ref(false)
	const searchKey = ref("")

	const selectObj = ref(null)

	watch(() => props.modelValue, (val) => {
		visible.value = val
		if(val){
			const selectedItem = props.list.find(item => item[props.valueKey] === props.selectId)
			if (selectedItem) {
				selectObj.value = selectedItem
			} else {
				selectObj.value = {}
			}
		}
	})

	watch(visible, (val) => {
		emit('update:modelValue', val)
	})
	const handerChangList = (item)=>{
		selectObj.value = item 
	}
	// 点击取消
	const handleCancel = () => {
		emit('update:modelValue', false)
	}
	// 点击确认
	const handleConfirm = () => {
		emit("confirm", selectObj.value)
	}
	// 搜索
	const handleSearchKey = (val) => {
		emit('searchChange', val)
	}
</script>