<template>
  <div>
    <el-select v-model="formData.country" :disabled="readonly" :style="{width: inputWidth}">
      <el-option v-for="(item) in treeList" :key="item.id" :value="item.id" :label="$l(item, 'title')" />
    </el-select>
    <el-select v-model="formData.province" class="ml-10" :disabled="readonly" :style="{width: inputWidth}">
      <el-option v-for="(item) in provinceList" :key="item.id" :value="item.id" :label="$l(item, 'title')" />
    </el-select>
    <el-select v-model="formData.city" class="ml-10" :disabled="readonly" :style="{width: inputWidth}">
      <el-option v-for="(item) in cityList" :key="item.id" :value="item.id" :label="$l(item, 'title')" />
    </el-select>
  </div>
</template>
<script>
import { getListTree } from '@/api/data'

export default {
  props: {
    country: Number,
    city: Number,
    province: Number,
    readonly: Boolean,
    inputWidth: String
  },
  data() {
    return {
      formData: {
        country: undefined,
        province: undefined,
        city: undefined
      },
      treeList: []
      // provinceList: [],
      // cityList:[]
    }
  },
  computed: {
    provinceList() {
      if (!this.formData.country) return []
      const country = this.treeList.find(item => item.id == this.formData.country)
      return country && country.children || []
    },
    cityList() {
      if (!this.provinceList.length) return []
      const province = this.provinceList.find(item => item.id == this.formData.province)
      return province && province.children || []
    }
  },
  watch: {
    city(val) {
      this.$set(this.formData, 'city', val)
    },
    province(val) {
      this.$set(this.formData, 'province', val)
    },
    country(val) {
      this.$set(this.formData, 'country', val)
    },
    'formData.city'(city) {
      this.$emit('cityChange', city)
    },
    'formData.country'(country) {
      this.$emit('countryChange', country)
      this.formData.province = null
      this.formData.city = null
    },
    'formData.province'(province) {
      this.$emit('provinceChange', province)
      this.formData.city = null
    }
  },
  created() {
    getListTree({ treeType: 1 }).then(async response => {
      this.treeList = response.data

      this.formData.country = this.country
      await this.$nextTick()
      this.formData.province = this.province
      await this.$nextTick()
      this.formData.city = this.city
    })
  }
}
</script>
