<template>

<div class="org-select">

  <el-cascader
    class="def"
    popper-class="def"
    :teleported="false"
    :options="orgTree"
    :props="defProps.props"
    v-model="realValue"
  />

</div>



</template>

<script lang='ts' setup>

import { getOrgainzations } from '@/api/system/organization'

const defProps = defineProps<{
  props: any
}>()

const selected = defineModel<any>()
const orgTree = ref([])

const realValue = computed({
  set (e) {
    selected.value = e ? e.slice(-1)[0] : null
  },
  get () {
    return selected.value
  }
})

const getTree = (arr, map, tree = []) => {

  if (!tree.length) {
    tree = arr.filter(item => !map[item.parentId])
  }

  tree.forEach(item => {
    item.children = arr.filter(xterm => xterm.parentId === item.id)
    if (item.children.length) {
      getTree(arr, map, item.children)
    }
  })

  return tree

}

onBeforeMount(() => {

  getOrgainzations().then(res => {

    orgTree.value = getTree(
      res,
      Object.fromEntries(res.map(item => {
        return [item.id, item]
      }))
    )
    
  })
})

</script>

<style scoped lang="scss">

.org-select {
  width: 100%;
}

</style>