<template>
  <el-select v-bind="$attrs" v-on="$listeners" clearable no-data-text="请先选择省份">
    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
  </el-select>
</template>

<script>
import { areaList } from '@vant/area-data'

const json2Array = function(data) {
  return Object.keys(data).map(code => ({ code, label: data[code], value: data[code] }))
}
export default {
  props: {
    parentValue: { type: String, default: '' },
    isCity: { type: Boolean, default: false }
  },
  computed: {
    options() {
      return this.parentValue || this.isCity ? this.cityList : this.provinceList
    },
    provinceList() {
      return json2Array(areaList.province_list).sort((a, b) => {
        return a.label.localeCompare(b.label)
      })
    },
    cityList() {
      return json2Array(areaList.city_list)
        .filter(item => {
          const provinceValueCode = this.provinceList.find(province => province.label === this.parentValue)?.code || ''
          return item.code.slice(0, 2) === provinceValueCode.slice(0, 2)
        })
        .sort((a, b) => {
          return a.label.localeCompare(b.label)
        })
    },
    treeList() {
      this.provinceList.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 }
      })
    }
  }
}
</script>
