import { getArea } from '@/api/data'
const Area = {
  template: `
        <a-select
          :id="id"
          :placeholder="placeholder"
          allowClear
          :value="defaultVal"
          :showSearch="true"
          @change="handleChange"
          :filter-option="filterOption">
          <a-select-option v-for="item in list" :key="item[defValKey]" :value="item[defValKey]">{{ item.name }}</a-select-option>
        </a-select>
    `,
  props: {
    value: {
      type: String,
      defatut: ''
    },
    id: {
      type: String,
      default: ''
    },
    defValKey: {
      type: String,
      default: 'areaSn'
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    leve: {
      type: String,
      default: 'province'
    },
    parentId: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      defaultVal: this.value,
      list: []
    }
  },
  watch: {
    value (newValue, oldValue) {
      console.log(newValue)
      this.defaultVal = newValue
    },
    parentId (newValue, oldValue) {
      if (this.leve != 'province' && newValue) {
        this.getList(this.leve)
      }
    }
  },
  mounted () {
    if (this.leve == 'province') {
      this.getList(this.leve)
    }
  },
  methods: {
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    handleChange (value) {
      console.log(value)
      this.defaultVal = value
      const item = this.list.find(item => item[this.defValKey] == value)
      this.$emit('change', value, item)
      this.$emit('input', value)
    },
    //  省/市/区
    getList (leve) {
      let params
      if (leve == 'province') {
        params = { type: '2' }
      } else {
        params = { parentId: this.parentId, type: leve == 'city' ? '3' : '4' }
      }
      console.log(params)
      getArea(params).then(res => {
        if (res.status == 200) {
          if (leve == 'province') {
            this.list = res.data || []
          } else if (leve == 'city') {
            this.list = res.data || []
          } else if (leve == 'district') {
            this.list = res.data || []
          }
        } else {
          this.list = []
        }
      })
    },
    clearData () {
      this.list = []
    }
  }
}

export default Area
