<template>
  <van-popup v-model="visible" position="bottom">
    <van-area
      title="地区"
      v-model="value"
      :area-list="areaList"
      :loading="loading"
      @cancel="handleCancel"
      @confirm="handleConfirm"
    />
  </van-popup>
</template>

<script>
export default {
  name: 'AreaPicker',
  props: {
    value: [String, Array],
    show: Boolean
  },
  data() {
    return {
      loading: false,
      list: []
    }
  },
  computed: {
    visible: {
      get() {
        return this.show
      },
      set(val) {
        this.$emit('update:show', val)
      }
    },
    areaList() {
      return this.list.reduce(
        (acc, x) => {
          const { province_list, city_list, county_list } = acc

          province_list[x.adcode] = x.name
          x.districts.forEach((y) => {
            city_list[y.adcode] = y.name

            y.districts.forEach((z) => {
              county_list[z.adcode] = z.name
            })
          })

          return { province_list, city_list, county_list }
        },
        {
          province_list: {},
          city_list: {},
          county_list: {}
        }
      )
    }
  },
  mounted() {
    this.getAreaData()
  },
  methods: {
    handleConfirm(v) {
      this.$emit('change', v)
    },
    getAreaData() {
      const list = localStorage.getItem('areas')
      if (list) {
        this.list = JSON.parse(list)
        return
      }

      this.loading = true

      // 如果不存在
      fetch(
        'https://restapi.amap.com/v3/config/district?keywords=中国&subdistrict=3&key=194d2c8d01a9084e3b0bbb62d2d5fad0'
      )
        .then((res) => res.json())
        .then((res) => {
          console.log('🚀 ~ file: index.vue ~ line 84 ~ .then ~ res', res)
          this.list = res.districts[0].districts
          localStorage.setItem('area', this.list)
          this.loading = false
        })
    },
    handleCancel() {
      this.$emit('cancel', true)
    }
  }
}
</script>
