<template>
	<view>
		<uni-data-checkbox v-model="selectedValuesArray" :localdata="dictItems" :multiple="true" data-key="value"
			data-value="label"></uni-data-checkbox>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		watch
	} from 'vue';
	import {
		getDictItemsApi
	} from '@/api/api.js';

	// 定义 props 和 emits
	const props = defineProps({
		dictCode: {
			type: String,
			required: true
		},
		modelValue: {
			type: String,
			default: ''
		}
	});

	const emits = defineEmits(['update:modelValue', 'change']);

	// 定义数据
	const dictItems = ref([]);
	const selectedValuesArray = ref(props.modelValue ? props.modelValue.split(',') : []);

	// 加载字典数据
	const loadDictItems = async () => {
		try {
			const response = await getDictItemsApi(props.dictCode);
			dictItems.value = response.result; // 假设响应数据的格式为 { data: [...] }
		} catch (error) {
			console.error('加载字典数据失败:', error);
		}
	};

	// 监听选中值的变化并通知父组件
	watch(selectedValuesArray, (newValue) => {
		console.log('selectedValuesArray 变化:', newValue);
		const selectedValuesString = newValue.join(',');
		emits('update:modelValue', selectedValuesString);
		emits('change', selectedValuesString);
	}, {
		deep: true
	});

	// 监听 props.modelValue 的变化
	watch(() => props.modelValue, (newValue) => {
		console.log('props.modelValue 变化:', newValue);
		selectedValuesArray.value = newValue ? newValue.split(',') : [];
	}, {
		immediate: true
	});

	onMounted(() => {
		loadDictItems();
	});
</script>

<style scoped>
	/* 可以添加组件的样式 */
</style>