<template>
  <div class="common-layout">
    <TopMenu
      @openMaxmin="openMaxmin"
      @goIndex="goIndex"
      :systemPath="systemPath"
      :hasRole="hasRole"
    ></TopMenu>
    <DefaultPage
      :showSearch="showSearch"
      :hightData="hightData"
      :allData="allData"
      :hightDataTotal="hightDataTotal"
      :allDataTotal="allDataTotal"
      @changeSearch="changeSearch"
      @openMaxmin="openMaxmin"
    ></DefaultPage>
    <div class="footer"></div>
  </div>
</template>

<script setup>
import { onMounted, ref, provide, onUnmounted } from "vue";
import bus from "@/utils/bus.js";
import TopMenu from "@/layout/components/TopMenu/TopMenu.vue";
import DefaultPage from "@/layout/components/DefaultPage/DefaultPage.vue";
import { layer } from "@layui/layer-vue";
import { ElMessage, ElLoading, ElMessageBox } from "element-plus";
import useUserStore from "@/store/modules/user";
import usePermissionStore from "@/store/modules/permission";
import { searchAll } from "@/api/search/search.js";
import { flieSearch } from "@/api/search/search.js";
const permissionStore = usePermissionStore();
const sidebarRouters = computed(() => permissionStore.sidebarRouters);
const roles = useUserStore().roles;
const permissionRoles = ["admin", "dept", "system", "audit"];
const super_admin = "admin";
const hasRole = ref(
  roles.some((role) => {
    return super_admin === role || permissionRoles.includes(role);
  })
);
const showSearch = ref(false); //是否显示搜索结果界面
const systemPath = ref({});
const searchText = ref(""); //搜索框的值
const hightData = ref([]); // 高级搜索数据
const allData = ref([]); // 全域搜索数据
const hightDataTotal = ref(); // 高级搜索数据总数
const allDataTotal = ref(); // 全域搜索数据总数

// 将标签信息保存到本地
const openMaxmin = (title, path) => {
  const item = {
    title: title,
    path: path,
  };
  // 判断是否存在标签列表，存在则添加，不存在则创建
  const storage = sessionStorage.getItem("tagList");
  if (storage) {
    //如果标签数量超过11个，提示超出最大限制
    if (JSON.parse(storage).length >= 10) {
      ElMessage({ message: "标签数量超出最大限制", type: "error" });
      return;
    }
    const oldStorage = JSON.parse(storage);
    // 判断是否存在相同的标签
    if (oldStorage.find((item) => item.path === path)) {
      ElMessage({ message: "该页面已经打开", type: "error" });
      return;
    }
    const thisId = layer.open({
      type: "iframe", //类型
      // move: true, //拖拽
      maxmin: true,
      moveOut:true,//可以拖出窗外
      shade:false,//不显示遮罩
      resize:true,//拉伸
      title: title,
      content: path,
      shadeClose: false, // 点击遮罩关闭
      area: ["80%", "80%"], //大小
      close: (id) => {
        // console.log(`关闭:${id}`);
        const oldData = JSON.parse(sessionStorage.getItem("tagList"));
        // 删除本地存储中该标签的数据
        const newStorage = oldData.filter((item) => item.id !== id);
        sessionStorage.setItem("tagList", JSON.stringify(newStorage));
      },
    });
    item.id = thisId;
    sessionStorage.setItem(
      "tagList",
      JSON.stringify([...JSON.parse(sessionStorage.getItem("tagList")), item])
    );
    // }
  } else {
    const thisId = layer.open({
      type: "iframe", //类型
      move: false, //不可拖拽
      maxmin: true,
      title: title,
      content: path,
      shadeClose: false, // 点击遮罩关闭
      area: ["80%", "80%"], //大小
      close: (id) => {
        // console.log(`关闭:${id}`);
        // 删除本地存储中该标签的数据
        const oldData = JSON.parse(sessionStorage.getItem("tagList"));
        const newStorage = oldData.filter((item) => item.id !== id);
        sessionStorage.setItem("tagList", JSON.stringify(newStorage));
      },
    });
    item.id = thisId;
    sessionStorage.setItem("tagList", JSON.stringify([item]));
  }
  if (!path.includes("fileEdit")) {
    setInterval(() => {
      const newTab = sessionStorage.getItem("newTab");
      if (!newTab) {
        return;
      }
      const tabData = JSON.parse(newTab);
      openTab(tabData.name, tabData.path);
      sessionStorage.removeItem("newTab");
    }, 200);
  }
};
const openTab = (title, path) => {
  const item = {
    title: title,
    path: path,
  };
  // 判断是否存在标签列表，存在则添加，不存在则创建
  const storage = sessionStorage.getItem("tagList");
  if (storage) {
    //如果标签数量超过11个，提示超出最大限制
    if (JSON.parse(storage).length >= 10) {
      ElMessage({ message: "标签数量超出最大限制", type: "error" });
      return;
    }
    const oldStorage = JSON.parse(storage);
    // 判断是否存在相同的标签
    if (oldStorage.find((item) => item.path === path)) {
      ElMessage({ message: "该页面已经打开", type: "error" });
      return;
    }
    const thisId = layer.open({
      type: "iframe", //类型
      // move: true, //拖拽
      maxmin: true,
      resize:true,//拉伸
      moveOut:true,//可以拖出窗外
      shade:false,//不显示遮罩
      title: title,
      content: path,
      shadeClose: false, // 点击遮罩关闭
      area: ["80%", "80%"], //大小
      close: (id) => {
        // console.log(`关闭:${id}`);
        const oldData = JSON.parse(sessionStorage.getItem("tagList"));
        // 删除本地存储中该标签的数据
        const newStorage = oldData.filter((item) => item.id !== id);
        sessionStorage.setItem("tagList", JSON.stringify(newStorage));
      },
    });
    item.id = thisId;
    sessionStorage.setItem(
      "tagList",
      JSON.stringify([...JSON.parse(sessionStorage.getItem("tagList")), item])
    );
    // }
  } else {
    const thisId = layer.open({
      type: "iframe", //类型
      move: false, //不可拖拽
      maxmin: true,
      title: title,
      content: path,
      shadeClose: false, // 点击遮罩关闭
      area: ["80%", "80%"], //大小
      close: (id) => {
        // console.log(`关闭:${id}`);
        // 删除本地存储中该标签的数据
        const oldData = JSON.parse(sessionStorage.getItem("tagList"));
        const newStorage = oldData.filter((item) => item.id !== id);
        sessionStorage.setItem("tagList", JSON.stringify(newStorage));
      },
    });
    item.id = thisId;
    sessionStorage.setItem("tagList", JSON.stringify([item]));
  }
};
// 点击logo回到主页
const goIndex = () => {
  showSearch.value = false
};

// 页面刷新后清除标签
onMounted(() => {
  // 判断是否页面刷新 刷新就清楚存储的标签
  switch (performance.navigation.type) {
    case 0:
      // console.log("首次加载出来了");
      break;
    case 1:
      sessionStorage.removeItem("tagList");
      break;
  }
  if (hasRole.value) {
    // console.log("sidebarRouters", sidebarRouters.value);
    const thisItem = sidebarRouters.value.find(
      (item) => item.redirect == "noRedirect"
    ); //拿到系统管理的第一个菜单 判断依据：第一个redirect == "noRedirect"的路由
    const path1 = thisItem.path; //一级路由
    const path2 = thisItem.children[0].path; //二级路由
    let path3;
    if (thisItem.children[0].children) {
      path3 = thisItem.children[0].children[0].path;
    }
    systemPath.value = {
      label: "系统管理",
      // path: "/biz/dirTemplate",
      path: `${path1}/${path2}${path3 ? "/" + path3 : ""}`,
    };
  }
  // 绑定事件总线
  bus.on("test", (data, num) => {
    console.log("data", data);
  });
});
onUnmounted(() => {
  bus.off("test");
  clearInterval();
});
const changeSearch = async (val, text) => {
  showSearch.value = val;
  searchText.value = text;
  if (val) {
    if (!searchText.value) {
      return;
    }
    const query = {
      keyword: searchText.value,
      page: 1,
      size: 999,
    };
    const allQuery = {
      keyword: searchText.value,
      isAsc: "asc",
      orderByColumn: "createTime",
      pageSize: 99999,
      pageNum: 1,
    };
    //高级搜索
    searchAll(query).then((res) => {
      // console.log("hightData", res);
      if (res.data) {
        hightData.value = res.data;
        hightDataTotal.value = res.total;
      }
    });

    // 全域搜索
    flieSearch(allQuery).then((res2) => {
      allData.value = res2.rows;
      allDataTotal.value = res2.total;
      // console.log("allData", res2);
    });
  }
};
</script>

<style lang="scss" scoped>
@import "@/assets/styles/mixin.scss";
@import "@/assets/styles/variables.module.scss";
.common-layout {
  width: 100vw;
  height: 100vh;
  background-image: url("@/assets/images/newIndex/bgi.png");
  background-repeat: no-repeat;
  background-size: cover;
}
.topMenu {
  width: 100%;
  height: 80px;
}
.main {
  width: 100%;
  height: calc(100vh - 160px);
}
.footer {
  width: 100%;
  height: 80px;
  // border: 1px solid #000;
  background-color: #b5d2ea;
}
</style>