<template>
	<picker mode="selector" :range="displayRange" :disabled="disableChange"  @change="change($event)">
		<common-cell :name="name" :required="required">
			<view class="form-content__wrapper">
				<view class="flex-main-content truncate" :class="value ? '' : 'form__placeholder'">
					{{ value || placeholder }}
				</view>
				<uni-icons class="form-arrow" type="arrowright"></uni-icons>
			</view>
		</common-cell>
	</picker>
</template>
<script setup>
import { computed } from 'vue';

import commonCell from '../common-cell.vue';

const emits = defineEmits(['change']);
const props = defineProps({
	form: {
		type: Object,
		default: () => ({})
	},
	name: {
		default: ''
	},
	range: {
		type: Array,
		default: () => []
	},
	required: {
		type: Boolean,
		default: false
	},
	disableChange: {
		type: Boolean,
		default: false
	},
	title: {
		default: ''
	}
})

const placeholder = computed(() => `请输入${props.name || ''}`)
const displayRange = computed(() => {
	// 如果range是对象数组，提取label作为显示文本
	if (Array.isArray(props.range) && props.range.length > 0 && typeof props.range[0] === 'object') {
		return props.range.map(item => item.label);
	}
	return props.range;
})
const value = computed(() => {
	if (!props.form) return '';
	const currentValue = props.form[props.title];
	if (currentValue === undefined || currentValue === null || currentValue === '') return '';
	// 如果range是对象数组，找到对应的label显示
	if (Array.isArray(props.range) && props.range.length > 0 && typeof props.range[0] === 'object') {
		const option = props.range.find(item => item.value === currentValue);
		return option ? option.label : currentValue;
	}
	return currentValue;
})

function change(e) {
	const selectedValue = props.range[e.detail.value];
	emits('change', {
		title: props.title,
		value: selectedValue
	})
}
</script>
<style>
@import '../cell-style.css';
</style>
