<template>
  <div>
    <Cascader
      v-model="value"
      :data="casData"
      :load-data="_loadData"
      placeholder="请选择省、市、区"
      :clearable="true"
      @on-change="_casChange"
      change-on-select
    />
  </div>
</template>
<script>
/**
 * 省、市、县 级联选择
 */
import { sysProvince, sysCity, sysArea } from '../../api'
export default {
  props: ['data', 'value', 'name'],
  data() {
    return {
      casData: []
    }
  },
  mounted() {
    this._getProvince()
  },
  methods: {
    _getProvince: async function() {
      const result = await sysProvince.getProvince()
      const casData = []
      for (let i = 0; i < result.length; i++) {
        casData.push({
          label: result[i].label,
          id: result[i].value,
          value: result[i].code,
          code: result[i].code,
          children: [],
          loading: false
        })
      }
      this.casData = casData
    },
    _loadData(item, callback) {
      const val = item.__value
      item.loading = true
      if (val.indexOf(',') === -1) {
        // 不存在逗号
        this._getCity(item.id).then(data => {
          item.children = data
          item.loading = false
          callback()
        })
      } else {
        this._getArea(item.id).then(data => {
          item.children = data
          item.loading = false
          callback()
        })
      }
    },
    _getArea: async function(value) {
      const result = await sysArea.getArea(value)
      const areaData = []
      for (let i = 0; i < result.length; i++) {
        areaData.push({
          label: result[i].label,
          id: result[i].value,
          value: result[i].code,
          code: result[i].code
        })
      }
      return areaData
    },
    _getCity: async function(value) {
      const result = await sysCity.getCity(value)
      const cityData = []
      for (let i = 0; i < result.length; i++) {
        cityData.push({
          label: result[i].label,
          id: result[i].value,
          value: result[i].code,
          code: result[i].code,
          children: [],
          loading: false
        })
      }
      return cityData
    },
    _casChange(id, selectedData) {
      const tempData = {
        id: id, // 返回的id值（只是用于查询省市区下面的子集数据）
        selectedData: selectedData
      }
      console.log('dddd===', tempData)
      this.$emit('on-result-change', this.name, tempData)
    }
  }
}
</script>
