<script setup lang="ts">
import { ref } from "vue";
import { httpList } from "/@/api/system/menuOperator";
import { ElTree } from "element-plus";
import type { IMenuTree } from "../types";

const defaultProps = {
  label: "menu_name",
  children: "child",
  isLeaf: "isLeaf"
};

const emit = defineEmits(["treeSelectChange", "initTableData"]);

const treeData = ref<Array<IMenuTree>>([]);
const treeRef = ref<InstanceType<typeof ElTree>>(null);
const defaultExpandedKeys = ref<Array<string>>([]);
const defaultCheckedKeys = ref<Array<string>>([]);

async function requestMenu(params: Record<string, string>) {
  return new Promise(resolve => {
    httpList({
      ...params,
      size:100
    })
      .then(result => {
        const { code, data } = result;
        if (code === 1 && data.list.length !== 0) {
          const list = data.list.map(item => ({
            ...item,
            isLeaf: Number(item.is_menu) === 0
          }));
          resolve(list);
        } else {
          resolve([]);
        }
      })
      .catch(() => {
        resolve([]);
      });
  });
}

async function initMenuList() {
  const f = await requestMenu({});
  const fId = f[0].id;
  defaultExpandedKeys.value = [fId];
  const list = await requestMenu({ pid: fId });
  setTimeout(() => {
    const node = list[0];
    treeRef.value.setCurrentKey(node.id);
    emit("treeSelectChange", node);
  }, 500);
}

async function load(row, resolve) {
  const { id } = row.data;
  const list = await requestMenu({ pid: id });
  resolve(list);
}

//选择节点
function handleSelect(node) {
  if (Number(node.is_menu) === 1) return;
  emit("treeSelectChange", node);
}

initMenuList();
</script>

<template>
  <div
    class="max-w-280px w-[280px] h-full min-h-780px bg-white p-2 mt-5px mr-10px"
  >
    <div class="flex justify-between mb-1 font-bold">
      <h1>菜单列表</h1>
    </div>
    <el-tree
      ref="treeRef"
      accordion
      node-key="id"
      highlight-current
      :props="defaultProps"
      :data="treeData"
      :lazy="true"
      :load="load"
      :default-expanded-keys="defaultExpandedKeys"
      :default-checked-keys="defaultCheckedKeys"
      @node-click="handleSelect"
    />
  </div>
</template>
