<template>
  <div class="m-4 mr-0 overflow-hidden bg-white">
    <BasicTree ref="asyncExpandTreeRef" title="职级组列表" toolbar search
      treeWrapperClassName="h-[calc(100%-35px)] overflow-auto" loadData :actionList="actionList"
      :renderIcon="createIcon" :clickRowToExpand="false" :treeData="treeData" :fieldNames="{ key: 'id', title: 'name' }"
      :defaultExpandAll="true" @select="handleSelect" />
    <BasicModal @register="register" title="删除" :helpMessage="['提示1', '提示2']" @ok="handleSubmit">
      确认要删除菜单吗？
    </BasicModal>
  </div>
</template>
<script lang="ts" setup>
  import { onMounted, ref, h, nextTick, unref } from 'vue';
  import { BasicTree, TreeItem, TreeActionItem } from '@/components/Tree';
  import { getPosGroupList, deleteMenu } from '@/api/demo/system';
  import { FormOutlined, DeleteOutlined } from '@ant-design/icons-vue';
  import { BasicModal, useModal } from '@/components/Modal';
  import { router } from '@/router';

  const [register, { closeModal, openModal }] = useModal();
  defineOptions({ name: 'DeptTree' });

  const emit = defineEmits(['select', 'edit']);

  const treeData = ref < TreeItem[] > ([]);
  let selectItemId = ref('')
  const asyncExpandTreeRef = ref < Nullable < TreeActionType >> (null);

  async function handleSubmit() {
    var query = [selectItemId.value]
    const data = await deleteMenu(query);
    closeModal();

  }

  async function fetch() {
    treeData.value = (await getPosGroupList()) as unknown as TreeItem[];
    // 展开全部
    nextTick(() => {
      unref(asyncExpandTreeRef)?.expandAll(true);
    });
  }

  function handleSelect(keys) {
    emit('select', keys[0]);
  }
  const btnList = router.currentRoute.value.meta.elements
  const actionList: TreeActionItem[] = []
  btnList.forEach(element => {
    if (element.domId == 'btnEdit') {
      actionList.push({
        render: (node) => {
          return h(FormOutlined, {
            class: 'ml-2',
            onClick: () => {
              emit('edit', node);
            },
          });
        },
      })
    } else if (element.domId == 'btnDelete') {
      actionList.push({
        render: (node) => {
          return h(DeleteOutlined, {
            class: 'ml-2',
            onClick: () => {
              selectItemId.value = node.id
              openModal(true, {
                isUpdate: false,
              });
            },
          });
        },
      })
    }
  });

  function createIcon({ level }) {
    if (level === 1) {
      return 'ion:git-compare-outline';
    }
    if (level === 2) {
      return 'ion:home';
    }
    if (level === 3) {
      return 'ion:airplane';
    }
    return '';
  }
  onMounted(() => {
    fetch();
  });
  defineExpose({
    fetch
  })
</script>