<template>
  <el-cascader
      :placeholder= 'placeholder'
      :options="options"
      :filterable = 'filterable'
      :disabled = "disabled"
      :value ="value"
      :expand-trigger = "expandTrigger"
      :size = "size"
      :show-all-levels = 'showAllLevels'
      @active-item-change = '$emit("active-item-change")'
      @change="updateValue"
    ></el-cascader>
</template>
<script>
  import address from './address.json'
  export default {
    props: {
      format: Boolean,
      showAllLevels: {
        type: Boolean,
        default: true
      },
      level: {
        default: 3
      },
      expandTrigger: String,
      value: [String, Array],
      size: String,
      disabled: Boolean,
      filterable: Boolean,
      placeholder: String
    },
    computed: {
      options () {
        if (this.level === 1) {
          return address.map((item) => {
            return {
              value: item.value,
              label: item.label
            }
          })
        }
        if (this.level === 2) {
          return address.map((item) => {
            return {
              value: item.value,
              label: item.label,
              children: item.children && item.children.length && item.children.map((innerItem) => {
                return {
                  value: innerItem.value,
                  label: innerItem.label
                }
              })
            }
          })
        }
        if (this.level !== 1 || this.level !== 2) {
          return address
        }
      },
      formatValue: {
        get () {
          return this.value.split('-')
        }
      }
    },
    methods: {
      updateValue (item) {
        if (this.format) {
          this.$emit('getLabel', this.formatItem(item))
        }
        this.$emit('input', item)
        this.$emit('change', item)
      },
      formatItem (arr) {
        var result = ''
        arr.reduce((before, now, index) => {
          let val = before.filter((item) => {
            return item.value === now
          })
          result += '-' + val[0].label
          return val[0].children
        }, address)
        return result.substring(1)
      }
    }
  }
</script>
