<template>
	<view class="u-p-b-24 u-m-b-24 border-bottom">
		<view class="title font-bold">{{title}}</view>
		<picker
		 @change="change" 
		:range-key="rangeKey" 
		:value="index" 
		:range="list">
			<view class="u-m-t-16 u-flex u-row-between ">
				<view class="color-333" v-if="selText">{{selText}}</view>
				<view class="color-999" v-else>请选择</view>
				<uni-icons type="right" color="#999" size="16"></uni-icons>
			</view>
		</picker>
	</view>
</template>

<script setup>
	import {
		computed,
		ref, watch
	} from 'vue';
	const props = defineProps({
		rangeValue:{
			type: [String, Number],
			default: ''
		},
		rangeKey:{
			type:String,
			default:'label'
		},
		list: {
			type: Array,
			default: () => []
		},
		title: {
			type: String,
			default: '标题'
		},
		modelValue: {
			type: [String, Number],
			default: ''
		}
	})
	function isObj(obj){
		return typeof obj ==='object'
	}
	function findIndex(){
		return props.list.findIndex(v=>{
			 if(isObj(v)){
				 return v[props.rangeValue]==props.modelValue
			 }else{
				 return v==props.modelValue
			 }
		})
	}
	function findValue(){
		const item=props.list[index.value]
		if(isObj(item)){
			return item[props.rangeValue]
		}else{
			return item
		}
	}
	const computedIndex=props.rangeValue? findIndex(): props.modelValue
	const index = ref(computedIndex)
	const emits = defineEmits(['update:modelValue'], )
	watch(()=>index.value,(newval)=>{
		const value=props.rangeValue?findValue() :newval
		console.log(value);
		emits('update:modelValue',value)
	})
	function change(e){
		index.value=e.detail.value
	}
	const selText=computed(()=>{
		const item=props.list[index.value]
		if(item&&isObj(item)){
			return item?item[props.rangeKey]:''
		}else{
			return item
		}
	})
</script>

<style>
</style>