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

<script>

import {getBaseTypeList} from "@/api/base/type";

export default {
  name: "ServerChoose",
  props:{
    value:{
      type: String,
      default: "",
      required:false
    }
  },
  data() {
    return {
      serverSelected: undefined,
      expandOnClickNode: true,
      serverList: [],
      treeProps:{
        label: "name",
        children: "children"
      }
    }
  },
  watch:{
    value(val){
      if (val){
        this.serverSelected = val
      }else {
        this.serverSelected = null
      }
    },
  },
  created() {
    this.listServer()
  },
  methods: {
    async listServer(){
      const res = await getBaseTypeList({type: "03"})
      this.serverList = 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.name)
      this.$emit("change")
      this.warehouseSelected = node.name
      this.$refs.selectTree.blur()
    }
  }
}
</script>

<style scoped lang="scss">

</style>
