<template>
  <FlexRow width="100%" align="center">
    <input 
      :value="modelValue"
      :placeholder="readonly ? '未填写' : '输入地址或者选择地图地址'"
      @input="handleInput"
    />
    <Button v-if="!disabled && !readonly" type="primary" size="mini" icon="map" @click="selectFromMap">地图选择</Button>
    <view v-else></view>
  </FlexRow>
</template>

<script setup lang="ts">
import { type PropType } from 'vue';
import Button from '@/components/basic/Button.vue';
import FlexRow from '@/components/layout/FlexRow.vue';

const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
  /**
   * 是否禁用
   */
  disabled: {
    type: Boolean,
    default: false,
  },
  /**
   * 是否只读
   */
  readonly: {
    type: Boolean,
    default: false,
  },
  loadFormattedAddress: {
    type: Function as PropType<(latlon: [number,number]) => Promise<string>>,
    default: null,
  },
});
const emit = defineEmits(['update:modelValue']);

function handleInput(e: any) {
  emit('update:modelValue', e.detail.value);
}
function selectFromMap() {
  uni.chooseLocation({
    success: (res) => {
      props.loadFormattedAddress([res.latitude, res.longitude]).then((info) => {
        console.log(info);
        emit('update:modelValue', info)
      })
    }
  })
}

defineOptions({
  options: {
    virtualHost: true,
  }
})
</script>
