<template>
	<click-input preIcon="location" :disabled="readonly" :placeholder="formProps.placeholder || '请选择位置'"
		@click="chooseAddress" :value="locationText" >
	</click-input>
</template>

<script setup>
	import { ref, computed } from 'vue'
	import ClickInput from '@/components/ClickInput.vue'

	const props = defineProps({
		formProps: {
			type: Object,
			default: () => {
				return {}
			}
		},
		readonly: Boolean,
		modelValue: Object
	})

	const _value = computed({
		get() {
			return props.modelValue
		},
		set(val) {
			emits('update:modelValue', val)
		}
	})
	
	const locationText = computed(() => {
		return _value.value instanceof String ? _value.value 
		: (_value.value ? `${_value.value.name} (${_value.value.address})`:null)
	})

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

	function chooseAddress() {
		if (props.readonly) {
			if (!_value.value || _value.value instanceof String){
				return
			}
			uni.openLocation({
				type: 'wgs84',
				latitude: _value.value.lat,
				longitude: _value.value.lng,
				fail: function(err) {
					uni.showToast({
						icon: 'none',
						title: '打开地图异常'
					})
				}
			});
		} else {
			uni.chooseLocation({
				type: 'wgs84',
				success: function(res) {
					console.log('选择位置', res);
					_value.value = {
						name: res.name,
						address: res.address,
						lat: res.latitude,
						lng: res.longitude
					}
				}
			})
		}

	}
</script>

<style>
</style>