<template>
  <div class="m-4 mr-0 overflow-hidden bg-white">
    <BasicTree
      ref="asyncExpandTreeRef"
      title="流程分类"
      toolbar
      search
      treeWrapperClassName="h-[calc(100%-35px)] overflow-auto"
      :actionList="actionList"
      :renderIcon="createIcon"
      :clickRowToExpand="false"
      :treeData="treeData"
      :fieldNames="{ key: 'itemDetailId', title: 'itemName' }"
      :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, createVNode } from 'vue';
  import { BasicTree, TreeItem, TreeActionItem, TreeActionType } from '@/components/Tree';
  import { getLoad, del } from '@/api/sys/sysDataItemDetail';
  import {
    PlusOutlined,
    FormOutlined,
    DeleteOutlined,
    ExclamationCircleOutlined,
  } from '@ant-design/icons-vue';
  import { Modal } from 'ant-design-vue';
  import { BasicModal, useModal } from '@/components/Modal';
  import { router } from '@/router';
  import { useMessage } from '@/hooks/web/useMessage';

  const { createMessage } = useMessage();
  const [register] = useModal();
  defineOptions({ name: 'DeptTree' });

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

  const treeData = ref<TreeItem[]>([]);
  let selectItemId = ref('');
  const asyncExpandTreeRef = ref<Nullable<TreeActionType>>(null);
  const treeLoading = ref(false);
  async function handleSubmit() {
    var query = {
      id: selectItemId.value,
    };
    const data = await del(query);
    if (data) {
      emit('success');
      return createMessage.success('删除成功');
    } else {
      return createMessage.error('删除失败');
    }
  }

  async function fetch() {
    treeLoading.value = true;
    treeData.value = (await getLoad({ code: 'FlowSort' })) as unknown as TreeItem[];
    // 展开全部
    nextTick(() => {
      treeLoading.value = false;
      unref(asyncExpandTreeRef)?.expandAll(true);
    });
  }

  function handleSelect(keys) {
    var itemDetailId = keys[0];
    var itemName;
    treeData.value.forEach((element) => {
      if (itemDetailId == element.itemDetailId) {
        itemName = element.itemName;
      }
    });
    emit('select', itemName);
  }
  const btnList: any = router.currentRoute.value.meta.elements;
  const actionList: TreeActionItem[] = [];
  btnList.forEach((element) => {
    if (element.domId == 'btnAdd') {
      actionList.push({
        render: (node) => {
          return h(PlusOutlined, {
            class: 'ml-2',
            onClick: () => {
              emit('add', node);
            },
          });
        },
      });
    } else if (element.domId == 'btnEdit') {
      actionList.push({
        render: (node) => {
          let data = {};
          treeData.value.forEach((element) => {
            if (element.itemDetailId == node.itemDetailId) {
              data = element;
            }
          });
          return h(FormOutlined, {
            class: 'ml-2',
            onClick: () => {
              emit('edit', data);
            },
          });
        },
      });
    } else if (element.domId == 'btnDelete') {
      actionList.push({
        render: (node) => {
          return h(DeleteOutlined, {
            class: 'ml-2',
            onClick: () => {
              selectItemId.value = node.itemDetailId;
              Modal.confirm({
                title: '删除?',
                icon: createVNode(ExclamationCircleOutlined),
                content: '你确定要删除当前流程分类吗',
                okText: '确定',
                okType: 'danger',
                cancelText: '取消',
                onOk() {
                  console.log('OK');
                  handleSubmit();
                },
                onCancel() {
                  console.log('Cancel');
                },
              });
            },
          });
        },
      });
    }
  });

  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>
