<script setup lang="ts">
import { useRequest } from "vue-request";
import { myRequest } from "@/requests/request.ts";
import { userinfo } from "@/store/store.ts";
import { ref, watch } from "vue";
import MenuEdit from "@/pages/sys-menu/menu-edit.vue";
import { ElMessage } from "element-plus";
import { formatError } from "@/utils/utils.ts";
import YlActionDiv from "@/components/yl-action-div.vue";
import { updateMenu } from "@/utils/menu.ts";
// 空菜单信息
const blackMenu: sysMenuList = {
  route_only: false,
  menu_id: "",
  name: "",
  path: "",
  icon: "bi-list-ul",
  white_list: "",
  user_type: "admin",
};
const tableData = ref<sysMenuList[]>(); //菜单表格数据
const page = ref(1); // 分页当前页数
const pageSize = ref(10); // 分页当前页面行数
const dialog = ref({
  visible: false,
  title: "",
}); // 弹窗标题
const dialogData = ref<sysMenuList>(blackMenu); // 弹窗菜单数据
const expandList = ref<string[]>([]);
// 获取菜单列表
const {
  data: menus,
  loading: loading1,
  run,
} = useRequest<{ data: sysMenuList[] }>(
  () => myRequest(`/admin/menus`, userinfo.token),
  {
    refreshDeps: () => userinfo.token,
    ready: () => Boolean(userinfo.token),
  },
);
// 删除菜单
const { runAsync: deleteMenu } = useRequest(
  (id: string) =>
    myRequest(`/admin/menus?menu_id=${id}`, userinfo.token, {}, "delete"),
  { manual: true },
);
// 刷新菜单数据
const update = () => {
  run();
  dialog.value.visible = false;
  updateMenu();
};
//删除菜单方法
const deleteMenuItem = (id: string) => {
  deleteMenu(id)
    .then((res) => {
      if (res.code === 200) {
        run();
        ElMessage.success("删除成功");
      }
    })
    .catch((res) => ElMessage.error(formatError(res)));
};
// 菜单根据id转换为二级菜单
const getId = (data: sysMenuList) => {
  for (let i = 1; i <= 99; i++) {
    const id = data.menu_id + (i < 10 ? "0" + i : i);
    if (data.children?.filter((e) => e.menu_id === id).length === 0) {
      return id;
    }
  }
  return "";
};
// 根据菜单信息转换菜单为二级菜单数据
watch(menus, () => {
  tableData.value = menus?.value?.data
    .filter((item) => item.menu_id.length === 3)
    .map((e) => ({
      ...e,
      children: menus?.value?.data.filter(
        (i) => i.menu_id.startsWith(e.menu_id) && i.menu_id !== e.menu_id,
      ),
    }));
});
</script>

<template>
  <yl-action-div class-name="flex between">
    <div>
      <el-button @click="() => run()"
        ><el-icon><i class="bi-arrow-clockwise" /></el-icon
        ><span> 刷新</span></el-button
      >
      <el-button
        type="primary"
        @click="
          () => {
            dialog.visible = true;
            dialog.title = '添加菜单';
            dialogData = { ...blackMenu };
          }
        "
        >添加菜单</el-button
      >
    </div>
    <div>
      <el-button
        v-if="expandList.length === 0"
        @click="
          tableData ? (expandList = tableData?.map((e) => e.menu_id)) : []
        "
        >全部展开</el-button
      ><el-button v-else @click="expandList = []">全部折叠</el-button>
    </div>
  </yl-action-div>
  <el-table
    v-loading="loading1"
    :data="
      tableData?.filter(
        (_: object, i: number) =>
          i >= (page - 1) * pageSize && i < page * pageSize,
      )
    "
    :expand-row-keys="expandList"
    @expand-change="
      (row: sysMenuList, ex: boolean) => {
        if (ex) {
          expandList.push(row.menu_id);
        } else {
          expandList = expandList.filter((e) => e !== row.menu_id);
        }
      }
    "
    row-key="menu_id"
    stripe
  >
    <el-table-column prop="menu_id" label="ID" align="center" />
    <el-table-column prop="name" label="名称" align="center" />
    <el-table-column prop="icon" label="图标" align="center">
      <template #default="scope">
        <el-icon size="20"><i :class="scope.row.icon"></i></el-icon>
      </template>
    </el-table-column>
    <el-table-column prop="path" label="地址" align="center" />
    <el-table-column prop="route_only" label="仅路由模式" align="center">
      <template #default="scope">
        <el-switch v-model="scope.row.route_only" disabled
      /></template>
    </el-table-column>
    <el-table-column prop="user_type" label="用户权限" align="center" />
    <el-table-column prop="white_list" label="白名单" align="center" />
    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-button
          link
          v-if="scope.row.menu_id.length === 3"
          @click="
            () => {
              dialog.title = '添加菜单';
              dialog.visible = true;
              dialogData = {
                ...blackMenu,
                menu_id: getId(scope.row),
                icon: scope.row.icon,
              };
            }
          "
          >新增</el-button
        >
        <el-button
          link
          @click="
            () => {
              dialog.title = '修改菜单';
              dialog.visible = true;
              dialogData = { ...scope.row };
            }
          "
          >编辑</el-button
        >
        <el-popconfirm
          title="确认删除菜单？"
          @confirm="() => deleteMenuItem(scope.row.menu_id)"
        >
          <template #reference
            ><el-button type="danger" size="small">删除</el-button></template
          >
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <div class="flex around pagination">
    <el-pagination
      layout="sizes, prev, pager, next"
      :total="tableData ? tableData.length : 0"
      v-model:current-page="page"
      v-model:page-size="pageSize"
      hide-on-single-page
    />
  </div>
  <menu-edit
    :dialog="dialog"
    :data="dialogData"
    :run="update"
    :first-list="menus?.data.filter((e) => e.menu_id !== '000')"
  ></menu-edit>
</template>

<style scoped>
.pagination {
  padding: 1rem;
}
</style>
