<template>
  <el-dialog
    title="请选择部门"
    v-model="dialogVisible"
    @closed="closeDialog"
    destroy-on-close
  >
    <el-alert
      :title="`当前选中节点：` + currentNode.department_name"
      type="success"
    />
    <el-tree
      ref="treeRef"
      :data="treeData"
      default-expand-all
      node-key="id"
      highlight-current
      accordion
      @node-click="handleNodeClick"
    >
    </el-tree>
    <template #footer>
      <el-button type="primary" @click="handleCommitClick">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive, ref, watch } from 'vue';
import { getUserDepartmentTree } from '~/service/user';

const loading = ref(false);
const treeRef = ref();
const treeData = ref([]);

const currentNode = reactive({
  department_guid: '',
  department_name: ''
});

const props = defineProps({
  modelValue: Boolean,
  done: Function
});

getUserDepartmentTree().then(({ code, data }) => {
  if (code === 0) {
    treeData.value = data;
  }
});

const emits = defineEmits(['update:modelValue']);

const dialogVisible = ref(props.modelValue);

watch(
  () => props.modelValue,
  (v) => {
    dialogVisible.value = v;
  }
);

const closeDialog = () => {
  dialogVisible.value = false;
  emits('update:modelValue', false);
};

const handleNodeClick = (value) => {
  currentNode.department_guid = value.id;
  currentNode.department_name = value.label;
};

const handleCommitClick = async () => {
  props.done(currentNode);
  closeDialog();
};
</script>
