<script setup lang="ts">
import { provide, onMounted, ref } from 'vue'
import { ElTree } from 'element-plus'
import { post } from "@/utils/request";

const departmentData = ref<any[]>([])
const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()

const defaultProps = {
  children: 'children',
  label: 'label',
  value: 'id'
}

function getDepartmentData() {
  post(`/department/listAllMemb`, { keyword: '' }).then(res => {
    departmentData.value = setUserToDept(res.data || [])
  })
}

function setUserToDept(list: any): any[] {
  let newList = JSON.parse(JSON.stringify(list))
  for (let item of newList) {
    if (item.children != null) {
      item.children = setUserToDept(item.children);
    }

    if (item.userList != null) {
      if (item.children == null) {
        item.children = [];
      }
      item.userList.forEach((element: any) => {
        var obj = { id: element.id, label: element.name, parentId: element.departmentId, isUser: 1 };
        item.children.push(obj);
      });
    }
  }
  return newList;
}

onMounted(() => {
  getDepartmentData()
})

function getSelectData() {
  return treeRef.value!.getCheckedNodes()
}

// 向外暴露方法
defineExpose({
  getSelectData,
});
</script>

<template>
  <div class="w-full h-[60vh] flex flex-col">
    <!-- <el-input v-model="filterText" placeholder="请输入" class="mb-4" /> -->
    <div class="flex-1 overflow-auto">
      <el-tree ref="treeRef" :data="departmentData" :props="defaultProps" :check-on-click-node="true" :expand-on-click-node="false" :highlight-current="true" node-key="id" :show-checkbox="true" :check-strictly="true">
        <template #default="{ node, data }">
          <template v-if="node.data.isUser">
            <div class="flex items-center">
              <span class="pr-2"><el-icon color="#e6a23c"><Avatar /></el-icon></span>
              <TextTranslation translationTypes="userName" :translationValue="node.label"></TextTranslation>
            </div>
          </template>
          <template v-if="!node.data.isUser">
            <div class="flex items-center">
              <span class="pr-2"><el-icon color="#075985"><Grid /></el-icon></span>
              <TextTranslation translationTypes="departmentName" :translationValue="node.label"></TextTranslation>
            </div>
          </template>
        </template>
      </el-tree>
    </div>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-tree-node) {
  padding-top: 8px;
  font-size: 14px;
}
</style>
