import { areaList } from '@vant/area-data'
// json to array
const json2Array = function (data: Record<string, string>) {
  return Object.keys(data).map(code => ({ code, label: data[code], value: data[code] }))
}

export function useArea(province?: string, city?: string, county?: string) {
  const provinceValue = ref(province || '')
  const cityValue = ref(city || '')
  const countyValue = ref(county || '')

  watch(provinceValue, () => {
    cityValue.value = ''
  })
  watch(cityValue, () => {
    countyValue.value = ''
  })

  const provinceList = ref(
    json2Array(areaList.province_list).sort((a, b) => {
      return a.label.localeCompare(b.label)
    })
  )
  const cityList = computed(() => {
    return json2Array(areaList.city_list)
      .filter(item => {
        const provinceValueCode =
          provinceList.value.find(province => province.label === provinceValue.value)?.code || ''
        return item.code.slice(0, 2) === provinceValueCode.slice(0, 2)
      })
      .sort((a, b) => {
        return a.label.localeCompare(b.label)
      })
  })
  const countyList = computed(() => {
    return json2Array(areaList.county_list)
      .filter(item => {
        const cityValueCode = cityList.value.find(city => city.label === cityValue.value)?.code || ''
        return item.code.slice(0, 4) === cityValueCode.slice(0, 4)
      })
      .sort((a, b) => {
        return a.label.localeCompare(b.label)
      })
  })

  const treeList = provinceList.value.map(item => {
    const children = json2Array(areaList.city_list)
      .filter(item2 => {
        return item2.code.slice(0, 2) === item.code.slice(0, 2)
      })
      .sort((a, b) => {
        return a.label.localeCompare(b.label)
      })
    return { ...item, children }
  })

  return { provinceValue, cityValue, countyValue, provinceList, cityList, countyList, treeList }
}
