<template>
  <div>
    <el-cascader
      ref="areaCascaderRef"
      v-model="localArea"
      :options="options"
      clearable
      style="width: 100%"
      :placeholder="placeholder"
      @change="handleChange"
      :disabled="handDisabled"
    />
  </div>

</template>

<script>
import { fetchProvinceTree } from '@/api/system/province'

export default {
  name: 'AreaCascader',
  props: {
    provinceId: String,
    cityId: String,
    districtId: String,
    placeholder: {
      type: String,
      default: '请选择所属省市区'
    },
    level: {
      type: Number,
      default: 0
    },
    handDisabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      options: []
    }
  },
  computed: {
    localArea: {
      get() {
        if(this.level === 2){
          return [this.provinceId, this.cityId] || []
        }else {
          return [this.provinceId, this.cityId, this.districtId] || []
        }

      },
      set(val) {
        this.$emit('update:provinceId', val[0])
        this.$emit('update:cityId', val[1])
        this.$emit('update:districtId', val[2])
      }
    }
  },
  created() {
    this.getProvinceData()
  },
  mounted() {
    console.log(this.handDisabled)
  },
  methods: {
    sortTreeData(tree) {
      let obj = {}
      return tree.map((item, i) => {
        const level = Number(item.level)
        obj = {
          ...item,
          label: level === 1 ? item.province : level === 2 ? item.city : item.district,
          value: level === 1 ? item.provinceId : level === 2 ? item.cityId : item.districtId
        }
        if (item.childrenList && item.childrenList.length > 0) {
          obj.children = this.sortTreeData(item.childrenList)
        }
        return Object.assign({}, item, obj)
      })
    },
    getProvinceData() {
      fetchProvinceTree().then(({ data }) => {
        let result = this.sortTreeData(data)
        if (this.level > 0) {
          result.forEach(item => {
            if (this.level < 2) {
              item.children = null
            } else (
              item.children.forEach(item => {
                if (this.level < 3) {
                  item.children = null
                }
              })
            )
          })
        }
        this.options = result
        this.$emit('areaOptions', this.options)
      })

    },
    handleChange(val) {
      const node = this.$refs.areaCascaderRef.getCheckedNodes()
      let areaStr = ''
      if (node && node.length > 0) {
        const formatLabel = (arr) => arr.map(item => {
          if (item.parent) {
            return `${item.label},${formatLabel([item.parent])}`
          } else {
            return item.label
          }
        })
        areaStr = formatLabel(node)[0].split(',').reverse().join('/')
      }
      this.$emit('change', areaStr)
    }
  }
}
</script>
<style scoped lang="scss">

</style>
