<template>
  <view class="flex flex-col" style="height: 100vh">
    <view class="flex-shrink-0 p-4">
      <up-input
        v-model="searchKeyword"
        placeholder="搜索"
        :customStyle="{
          padding: '0 16rpx',
          height: '80rpx',
          backgroundColor: '#f4f4f4'
        }"
        border="surround"
        clearable
        @input="onSearch"
      ></up-input>
    </view>

    <view class="flex-1" style="overflow: hidden">
      <up-index-list :index-list="indexList" :sticky="true">
        <up-index-item
          v-for="(item, index) in countryList"
          :key="index"
          v-show="getFilteredGroup(item).length > 0"
        >
          <up-index-anchor :text="indexList[index]"></up-index-anchor>
          <view
            v-for="country in getFilteredGroup(item)"
            :key="country.id"
            class="px-4 py-2.5 border-b border-gray-2"
            @click="handleCountryClick(country)"
          >
            {{ country.name }}
          </view>
        </up-index-item>
        <view style="padding-bottom: calc(300rpx + env(safe-area-inset-bottom))"></view>
      </up-index-list>
    </view>
  </view>
</template>

<script setup>
  import { ref, onMounted, getCurrentInstance } from 'vue'
  import { getCountryListRequest } from '@/api/system'

  const instance = getCurrentInstance().proxy
  const eventChannel = instance.getOpenerEventChannel()

  const indexList = ref(['★', ...Array.from({ length: 26 }, (_, i) => String.fromCharCode(65 + i))])

  const countryList = ref(new Array(27).fill().map(() => []))
  const searchKeyword = ref('')

  const getFilteredGroup = group => {
    if (!searchKeyword.value) return group
    const keyword = searchKeyword.value.toLowerCase()
    return group.filter(country => country.name.toLowerCase().includes(keyword))
  }

  const onSearch = () => {}

  const getCountryList = async () => {
    uni.showLoading({ title: '加载中...' })
    try {
      const { code, data, message } = await getCountryListRequest()
      if (code === 0) {
        const newGroups = data
          .filter(item => !indexList.value.includes(item.group))
          .map(item => item.group)
          .filter((group, index, arr) => arr.indexOf(group) === index)

        indexList.value = [...indexList.value, ...newGroups]
        countryList.value = new Array(indexList.value.length).fill().map(() => [])

        if (data.length > 0) countryList.value[0].push(data[0])

        data.forEach(item => {
          const groupIndex = indexList.value.indexOf(item.group)
          if (groupIndex !== -1) countryList.value[groupIndex].push(item)
        })
      } else {
        uni.showToast({ title: message, icon: 'none' })
      }
    } catch (e) {
      console.error(e)
      uni.showToast({ title: '获取国家列表失败', icon: 'none' })
    } finally {
      uni.hideLoading()
    }
  }

  onMounted(() => getCountryList())

  const handleCountryClick = country => {
    eventChannel.emit('country', country)
    uni.navigateBack()
  }
</script>
