<template>
  <div class="m-4 mr-0 overflow-hidden bg-white">
    <div class="button-list">
      <a-button type="primary" @click="emit('add')">添加</a-button>
      <a-button type="primary" @click="editLayer()">编辑</a-button>
      <a-button type="primary" danger @click="delLayer()">删除</a-button>
    </div>
    <BasicTree
      ref="asyncExpandTreeRef"
      title="图层列表"
      toolbar
      search
      treeWrapperClassName="h-[calc(100%-35px)] overflow-auto"
      :renderIcon="createIcon"
      :clickRowToExpand="false"
      :checkable="true"
      @check="handleCheck"
      :treeData="treeData"
      :fieldNames="{ key: 'id', title: 'applicationName', children: 'child' }"
      :defaultExpandAll="true"
      @select="handleSelect"
    />
  </div>
</template>
<script lang="ts" setup>
  import { onMounted, ref, h, nextTick, unref } from 'vue';
  import { BasicTree, TreeItem, TreeActionItem, TreeActionType } from '@/components/Tree';
  import { getMenuList, deleteMenu, getAllModuleDetail } from '@/api/demo/system';
  import { getApplicationList, deleteApplication } from '@/api/application/index';
  import { FormOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons-vue';
  import { router } from '@/router';
  import { useMessage } from '@/hooks/web/useMessage';
  import { deleteLayer } from '@/api/sys/layerManagement';

  const { createMessage, createConfirm } = useMessage();
  const emit = defineEmits(['select', 'edit', 'add', 'remove']);

  defineOptions({ name: 'DeptTree' });
  const treeData = ref<TreeItem[]>([]);
  let selectItem = ref();
  const asyncExpandTreeRef = ref<Nullable<TreeActionType>>(null);
  async function fetch() {
    treeData.value = (await getApplicationList()) as unknown as TreeItem[];
    setTimeout(() => {
      treeData.value.forEach((item, index) => {
        let moduleDetail = allModuleDetail.value?.find((detail) => {
          return detail.id == item.id;
        });
      });
    }, 500);
    // 展开全部
    nextTick(() => {
      unref(asyncExpandTreeRef)?.expandAll(true);
    });
  }

  function handleSelect(keys) {
    const item = treeFindById(treeData.value, keys[0]);
    emit('select', item);
    selectItem.value = item;
  }
  function handleCheck(checkedKeys, e) {
    console.log('onChecked', checkedKeys, e);
  }
  /**
   * 根据id值或某个属性的值从树结构中查询数据
   * @param {Array} treeArray 树结构数据
   * @param {String|Number|Boolean|null} id 对比的id的值
   * @param {String} childrenKey 子集的key名, 默认 children
   * @returns 返回存在的数据，不存在返回null
   */
  function treeFindById(treeArray, id, childrenKey = 'child') {
    for (let node of treeArray) {
      // id值对比
      if (node.id === id) {
        return node;
      }

      if (node[childrenKey] && node[childrenKey].length > 0) {
        const foundElement = treeFindById(node[childrenKey], id);
        if (foundElement) {
          return foundElement;
        }
      }
    }

    return null;
  }

  const delLayer = () => {
    createConfirm({
      iconType: 'warning',
      title: '删除',
      content: '确认要删除吗?',
      onOk: async () => {
        var query = {
          id: selectItem.value.id,
        };
        const data = await deleteApplication(query);
        if (data) {
          fetch();
          emit('remove');
          createMessage.success('删除成功');
        } else {
          createMessage.info('删除失败');
        }
      },
    });
  };
  const editLayer = () => {
    if (!selectItem.value) {
      return createMessage.warning('请选择要编辑的数据');
    }
    emit('edit', selectItem);
  };
  function createIcon({ level }) {
    if (level === 1) {
      return 'ion:git-compare-outline';
    }
    if (level === 2) {
      return 'ion:home';
    }
    if (level === 3) {
      return 'ion:airplane';
    }
    return '';
  }

  const allModuleDetail = ref();
  async function funGetAllModuleDetail() {
    allModuleDetail.value = await getAllModuleDetail();
  }

  onMounted(() => {
    funGetAllModuleDetail();
    fetch();
  });
  defineExpose({
    fetch,
    treeData,
  });
</script>
<style lang="less" scoped>
  .button-list {
    padding-top: 10px;
    button {
      margin-left: 10px;
    }
  }
</style>
