

<template>
  <FlexCol 
    :padding="[0,'space.md']" 
    backgroundColor="white" 
    radius="radius.md"
  >
    <NavBar title="选择城市" />
    <SearchBar 
      v-model="searchValue"
      leftIcon=""
      searchIcon="search"
      searchState="show"
      placeholder="搜索城市" 
      @search="cities.reload()"
      @clear="cities.reload()"
    />
    <IndexList 
      v-if="cities.content.value"
      :data="cities.content.value"
      :groupDataBy="(item) => item.first_letter"
      :sortGroup="arr => arr.sort()"
      :innerStyle="{
        height: '70vh',
      }"
      dataDisplayProp="name"
      @itemClick="handleCityClick"
    />
  </FlexCol>
</template>

<script setup lang="ts">
import MapApi, { type CityItem } from '@/api/map/MapApi';
import { useSimpleDataLoader } from '@/components/composeabe/loader/SimpleDataLoader';
import SearchBar from '@/components/form/SearchBar.vue';
import FlexCol from '@/components/layout/FlexCol.vue';
import { ref } from 'vue';
import NavBar from '@/components/nav/NavBar.vue';
import IndexList from '@/components/list/IndexList.vue';

const searchValue = ref('');
const cities = useSimpleDataLoader(async () => {
  return (await MapApi.loadCityData(true))
    .flatMap(item => {
      return (item.children || []).map(child => ({
        ...child,
        parentName: item.name,
      }));
    })
    .filter(item => !searchValue.value || item.name.includes(searchValue.value));
})

const emit = defineEmits(['selectCity']);

const handleCityClick = (item: CityItem) => {
  console.log(item);
  emit('selectCity', item);
}
</script>