<template>
  <div>
    <el-select class="main-select-tree" clearable ref="selectTree" v-model="warehouseSelected" @blur="$emit('input-blur', $event)">
      <el-option v-for="warehouse in optionData(warehouseList)"
                 :key="warehouse.value"
                 :label="warehouse.label"
                 :value="warehouse.value" style="display: none"/>
      <el-tree class="main-select-el-tree" ref="selectedTree"
                                 :data="warehouseList"
                                 :props="treeProps"
                                 highlight-current
                                 @node-click="handleNodeClick"
                                 :expand-on-click-node="expandOnClickNode"
                                 default-expand-all />
    </el-select>
  </div>
</template>

<script>

import {getBaseWarehouseList} from "@/api/base/warehouse";

export default {
  name: "WarehouseChoose",
  props:{
    value:{
      type: [String, Object],
      default: "",
      required:false
    }
  },
  data() {
    return {
      warehouseSelected: undefined,
      expandOnClickNode: true,
      warehouseList: [],
      treeProps:{
        label: "name",
        children: "children"
      }
    }
  },
  watch:{
    value(val){
      if (val){
        this.warehouseSelected = val.name
      }else {
        this.warehouseSelected = null
      }
    },
  },
  created() {
    this.listWarehouse()
  },
  methods: {
    async listWarehouse(){
      const res = await getBaseWarehouseList()
      this.warehouseList = this.handleTree(res.data, 'id', 'parentId',"children","0")
    },
    optionData(array, result=[]){
      array.forEach(item => {
        result.push({label: item.name, value: item.id})
        if (item.children && item.children.length !== 0){
          this.optionData(item.children, result)
        }
      })
      return JSON.parse(JSON.stringify(result))
    },
    handleNodeClick(node){
      this.$emit("input", node)
      this.$emit("change")
      this.warehouseSelected = node.name
      this.$refs.selectTree.blur()
    }
  }
}
</script>

<style scoped lang="scss">

</style>
