<template>
  <FlexRow width="100%" align="center">
    <CascaderField
      v-if="ChinaCityData.data.value"
      ref="fieldRef"
      :modelValue="modelValue"
      @update:modelValue="$emit('update:modelValue', $event)"
      textKey="name"
      :valueKey="stringValue ? 'name' : 'code'"
      childrenKey="children"
      :data="(ChinaCityData.data.value as CascaderItem[]) || []"
      v-bind="$attrs"
      :placeholder="readonly ? '未填写' : ($attrs.placeholder as string || '请选择省市区')" 
    />
    <Button v-if="!disabled && !readonly" type="primary" size="mini" icon="map" @click="selectCityFromMap">地图选择</Button>
  </FlexRow>
</template>

<script setup lang="ts">
import { ref, type PropType } from 'vue';
import { useDataLoader } from '@/components/composeabe/DataLoader';
import type { CascaderItem } from '@/components/form/Cascader.vue';
import Button from '@/components/basic/Button.vue';
import CascaderField from '@/components/form/CascaderField.vue';
import FlexRow from '@/components/layout/FlexRow.vue';

const props = defineProps({
  modelValue: {
    type: Array as PropType<string[]>,
    default: () => [],
  },
  /**
   * 是否禁用
   */
  disabled: {
    type: Boolean,
    default: false,
  },
  readonly: {
    type: Boolean,
    default: false,
  },
  loadCityData: {
    type: Function as PropType<() => Promise<CascaderItem[]>>,
    default: () => Promise.resolve([]),
  },
  loadDistrictInfo: {
    type: Function as PropType<(latlon: [number,number]) => Promise<{
      province: string,
      city: string,
      district: string,
      township: string,
      towncode: string,
      adcode: string,
    }>>,
    default: null,
  },
  /**
   * 是否返回字符串值，否则返回选中城市code
   */
  stringValue: {
    type: Boolean,
    default: true,
  },
})
const emit = defineEmits(['update:modelValue', 'selectedTownship'])
const ChinaCityData = useDataLoader(() => props.loadCityData(), {
  immediate: true,
});

const fieldRef = ref();

function selectCityFromMap() {
  uni.chooseLocation({
    success: (res) => {
      props.loadDistrictInfo([res.latitude, res.longitude]).then((info) => {
        console.log(info);
        emit('update:modelValue', props.stringValue ? 
          [info.province, info.city, info.district] : 
          [info.adcode ])
        emit('selectedTownship', props.stringValue ? info.township : info.towncode, info.towncode)
        setTimeout(() => fieldRef.value?.confirm(), 200);
      })
    }
  })
}

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