<template>
	<view class="u-relative choose-haocai">
		<view class="input u-flex" @click="toggle">
			<up-input @change="filterHaocaiList" border="none" v-model="text" placeholder="请选择"></up-input>
			<up-icon :size="10" name="arrow-down-fill"></up-icon>
		</view>
		<view class="u-absolute" v-if="popShow">
			<scroll-view scroll-y="true" class="scroll">
				<view class="item" v-for="(item,index) in $haocaiList" :key="index" @click="haocaiClick(item,index)">
					{{item.conName}}
				</view>
				<view class="item no-wrap" @click="toggle" v-if="text&&!$haocaiList.length">没有该耗材</view>
			</scroll-view>

		</view>
	</view>
</template>

<script setup>
	import { reactive, ref, watch, onMounted } from 'vue';
	const props = defineProps({
		listMap: {
			type: Object,
			default: () => {}
		},
		list: {
			type: Array,
			default: () => []
		},
		modelValue: {
			type: [String, Number],
			default: ''
		},
		show: {
			type: Boolean,
			default: false
		},

	})
	let text = ref('')
	let popShow = ref(props.show)
	const emits = defineEmits(['update:show', 'update:modelValue','change'])
	onMounted(() => {
		setText()
	})

	watch(() => props.show, (newval) => {
		popShow.value = newval
	})
	watch(() => popShow.value, (newval) => {
		emits('update:show', newval)
	})
	let $haocaiList = ref(props.list)
	watch(() => props.list, (newval) => {
		$haocaiList.value = newval
		setText()
	})
	watch(() => props.modelValue, (newval) => {
		setText()
	})

	function setText() {
		const item = props.listMap[props.modelValue]
		text.value = item ? item.conName : ''
	}

	function toggle(e) {
		popShow.value = !popShow.value
	}

	/**
	 * 耗材选择监听
	 * @param {Object} e
	 */
	function filterHaocaiList(e) {
		if (e === '') {
			return $haocaiList.value = props.list
		}
		const arr = props.list.filter(v => v.conName.match(e))
		$haocaiList.value = arr
	}
	
	/**
	 * 耗材选择确认
	 * @param {Object} item
	 * @param {Object} index
	 */
	function haocaiClick(item, index) {
		if (item.id != props.modelValue) {
			emits('update:modelValue', item.id)
			emits('change', item)
		}
		popShow.value = false
	}

	
</script>

<style lang="scss" scoped>
	.choose-haocai {
		.input {
			width: 172rpx;
			padding: 10rpx 16rpx;
			height: 60rpx;
			box-sizing: border-box;
			background: #FFFFFF;
			border-radius: 8rpx 8rpx 8rpx 8rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			border: 2rpx solid #E5E5E5;
			overflow: hidden;
		}


		.u-absolute {
			top: calc(100% + 10rpx);
			border: 1px solid #E5E5E5;
			left: 0;
			background-color: #fff;
			z-index: 10;
			right: 0;
			border-radius: 8rpx;

			.scroll {
				$line-h: 60rpx;
				max-height: calc($line-h * 4);

				.item {
					line-height: $line-h;
					padding: 0 20rpx;
				}
			}

		}
	}
</style>