<template>
  <div>
    <!-- {{valueName}} -->
    <el-cascader
      v-model="value"
      :options="options"
      @change="handleChange"
      :show-all-levels="false"
      :props="{ checkStrictly: true }"
      style="width:100%"
      :disabled="disabledCreated"
    ></el-cascader>
  </div>
</template>
<script>
import basicData from '@/api/basicData.js'
export default {
  props: {
    valueName: String,
    onlyId: String,
    disabledCreated: Boolean
  },
  data() {
    return {
      value: '',
      options: [],
      obj: '',
      val: this.valueName
    }
  },
  created() {
    this.getInfo()
  },
  watch: {
    valueName(val) {
      this.val = val
    }
  },
  methods: {
    getInfo() {
      basicData.getCompanyInfo('1258608622670319616').then(res => {
        this.options = this.deepClone(res)
        if(this.val){
          console.log(this.val)
          this.value = JSON.parse(this.val)
        }else {
          // console.log('2')
          this.value = this.options[0].id
          //默然赋值为第一条数据
          this.$emit('value', this.options[0])
        }       
      })
    },
    //深层拷贝
    deepClone(obj, id) {
      let objClone = Array.isArray(obj) ? [] : {}
      if (obj && typeof obj === 'object') {
        for (let key in obj) {
          if (obj.hasOwnProperty(key)) {
            //判断ojb子元素是否为对象，如果是，递归复制
            if (obj[key] && typeof obj[key] === 'object') {
              objClone[key] = this.deepClone(obj[key])
            } else {
              objClone.label = obj.name
              objClone.value = obj.id
              //如果不是，简单复制
              objClone[key] = obj[key]
            }
          }
        }
      }
      return objClone
    },
    getObj(options, id) {
      options.forEach(item => {
        if (item.id == id) {
          this.obj = item
        } else {
          if (item.children) {
            this.getObj(item.children, id)
          }
        }
      })
    },
    handleChange(value) {
      let val = ''
      if (value.length > 1) {
        val = value.slice(value.length - 1, value.length)
        val = val[0]
      } else {
        val = value[0]
      }
      this.getObj(this.options, val)
      this.obj.valueInfo = value
      this.obj.constructUnitPersonLiable = this.onlyId
      this.$emit('handleChanged', this.obj)
    }
  }
}
</script>