<template>
  <div class="navbar">
    <hamburger
      id="hamburger-container"
      :is-active="appStore.sidebar.opened"
      class="hamburger-container"
      @toggleClick="toggleSideBar"
    />
    <breadcrumb
      id="breadcrumb-container"
      class="breadcrumb-container"
      v-if="!settingsStore.topNav"
    />
    <top-nav
      id="topmenu-container"
      class="topmenu-container"
      v-if="settingsStore.topNav"
    />

    <div class="right-menu">
      <template v-if="appStore.device !== 'mobile'">
        <!-- <el-button
          @click="oldSystem"
          style="margin-top: 8px"
          type="primary"
          round
          >旧系统入口</el-button
        >

        <header-search id="header-search" class="right-menu-item" /> -->
        <span style="margin-right: 10px; font-weight: 700; font-size: 17px"
          >当前用户：{{ userLogin }}</span
        >
        <screenfull id="screenfull" class="right-menu-item hover-effect" />
        <!-- 铃铛 -->
        <!-- 闪动 -->
        <!-- :class="{ 'badge-custom': noticeCount > 0 }" -->
        <!-- v-if="noticeCount != 0" 为0是否显示 -->
        <el-popover placement="top-start" width="330" trigger="hover">
          <template #reference>
            <el-badge
              v-if="noticeCount != 0"
              :value="noticeCount"
              class="right-menu-item hover-effect"
              :class="{ 'badge-custom': noticeCount > 0 }"
            >
              <el-icon style="margin-top: 12px; font-weight: 700" size="24"
                ><Bell
              /></el-icon>
            </el-badge>
            <el-icon
              v-else
              @click="toNoticePage"
              style="margin-top: 12px; font-weight: 500"
              size="24"
              ><Bell
            /></el-icon>
          </template>
          <div style="padding: 5px 10px">
            <div
              style="
                font-size: 17px;
                color: #606266;
                font-weight: 700;
                border-bottom: 1px solid #e4e7ed;
                padding-bottom: 15px;
              "
            >
              系统消息
            </div>

            <div
              v-if="unreadLength != 0"
              style="height: 400px; overflow: hidden"
            >
              <div
                v-for="item in unreadList"
                :key="item"
                style="
                  height: 70px;
                  padding: 5px 5px;
                  border-bottom: 1px solid #e4e7ed;
                  cursor: pointer;
                "
                class="bg"
              >
                <div @click="detailNotice(item)">
                  <div
                    style="
                      width: 200px;
                      display: inline-block;
                      margin-top: 4px;
                      padding-left: 10px;
                    "
                  >
                    <div
                      style="
                        font-size: 16px;
                        width: 200px;
                        display: inline-block;
                      "
                    >
                      <span
                        style="
                          width: 7px;
                          height: 7px;
                          border-radius: 50%;
                          background-color: #d90013;
                          display: inline-block;
                          margin-bottom: 5px;
                        "
                      ></span>
                      {{ item.noticeTitle }}
                    </div>
                    <div
                      style="
                        font-size: 14px;
                        display: inline-block;
                        margin-top: 8px;
                        width: 200px;
                        margin-left: 12px;
                      "
                    >
                      {{ item.createTime }}
                    </div>
                  </div>

                  <dict-tag
                    style="float: right; margin-top: 17px; margin-right: 5px"
                    :options="sys_notice_type"
                    :value="item.noticeType"
                  />
                </div>
              </div>
            </div>
            <el-empty v-else description="暂无未读消息" />
            <div style="border-top: 1px solid #e4e7ed; padding: 15px 0">
              <div @click="toNoticePage" style="float: right; cursor: pointer">
                查看更多<el-icon size="10"><ArrowRightBold /></el-icon>
              </div>
            </div>
          </div>
        </el-popover>

        <el-tooltip content="布局大小" effect="dark" placement="bottom">
          <size-select id="size-select" class="right-menu-item hover-effect" />
        </el-tooltip>
      </template>
      <div class="avatar-container">
        <el-dropdown
          @command="handleCommand"
          class="right-menu-item hover-effect"
          trigger="click"
        >
          <div class="avatar-wrapper">
            <img :src="userStore.avatar" class="user-avatar" />
            <el-icon><caret-bottom /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <router-link to="/user/profile">
                <el-dropdown-item>个人中心</el-dropdown-item>
              </router-link>
              <el-dropdown-item command="setLayout">
                <span>布局设置</span>
              </el-dropdown-item>
              <!-- <el-dropdown-item command="oldSystem">
                <span>旧系统入口</span>
              </el-dropdown-item> -->
              <el-dropdown-item divided command="logout">
                <span>退出登录</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <el-dialog v-model="openDialog" width="800" :before-close="handleClose">
      <div
        style="
          font-size: 20px;
          align-items: center;
          text-align: center;
          color: black;
          font-weight: 700;
        "
      >
        {{ form.noticeTitle }}
      </div>
      <div
        style="
          font-size: 15px;
          text-align: center;
          color: black;
          margin-top: 15px;
        "
      >
        发送人:{{ createBy }} &nbsp; &nbsp; &nbsp; &nbsp;发送时间:{{
          form.createTime
        }}
      </div>
      <div style="font-size: 16px; color: black; margin-top: 20px">
        {{ form.noticeContent }}
      </div>
      <template #footer>
        <div style="text-align: center" class="dialog-footer">
          <el-button @click="openDialog = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getInfo } from "@/api/login";
import { ElMessageBox } from "element-plus";
// import EventSource from "../../node_modules/eventsource/lib/eventsource.js";

import { getToken } from "@/utils/auth";
import Breadcrumb from "@/components/Breadcrumb";
import TopNav from "@/components/TopNav";
import Hamburger from "@/components/Hamburger";
import Screenfull from "@/components/Screenfull";
import SizeSelect from "@/components/SizeSelect";
import HeaderSearch from "@/components/HeaderSearch";
import useAppStore from "@/store/modules/app";
import useUserStore from "@/store/modules/user";
import useSettingsStore from "@/store/modules/settings";
import {
  listNotice,
  getNotice,
  getCurrUserUnReadNotice,
  closeSSE,
  currUserUnReadList,
} from "@/api/system/notice";
import { onMounted } from "vue";
import { EventSourcePolyfill } from "event-source-polyfill";
import { ElMessage } from "element-plus";
const { proxy } = getCurrentInstance();
const { sys_notice_type } = proxy.useDict("sys_notice_type");

// SSE
const appStore = useAppStore();
const userStore = useUserStore();
const settingsStore = useSettingsStore();
const noticeContent = ref("");
const userId = ref("");
const userLogin = ref("");
const form = ref(null);
const eventSource = ref(undefined);
const noticeCount = ref(0);
const intervalId = ref(null);
const unreadList = ref([]);
const unreadLength = ref(null);

const openDialog = ref(false);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
// SSE
// function getUserId() {
//   getInfo().then((res) => {
//     userId.value = res.user.userId;
//     sendMessage(userId.value).then((res) => {
//       console.log("sendMessageres", res);
//     });
//   });
// }
function getInfo1() {
  getInfo().then((res) => {
    console.log("res", res);
    userLogin.value = res.user.nickName;
  });
}
function detailNotice(row) {
  const noticeId = row.noticeId || ids.value;
  getNotice(noticeId).then((response) => {
    openDialog.value = true;
    form.value = response.data;
  });
  setTimeout(() => {
    getUnreadList();
    startData();
  }, 200);
}
// 第一次请求
function startData() {
  getCurrUserUnReadNotice().then((res) => {
    // console.log("getCurrUserUnReadNotice", res);
    noticeCount.value = res.data;
    noticeContent.value = "您有" + noticeCount.value + "条未读的信息"; //定制内容
  });
}

function getUnreadList() {
  currUserUnReadList().then((res) => {
    console.log("currUserUnReadList", res);
    unreadLength.value = res.total;
    unreadList.value = res.rows;
  });
}
//建立消息连接
function createSSE() {
  console.log("EventSource", window.EventSource);
  if (window.EventSource) {
    // getInfo().then((res) => {
    // userId.value = res.user.userId;
    // console.log("userId", userId.value);
    eventSource.value = new EventSourcePolyfill("/dev-api/sse/connect/", {
      // 设置重连时间
      heartbeatTimeout: 60 * 60 * 1000,
      // 添加token
      headers: {
        Authorization: `Bearer ${getToken()}`,
        // "Content-type": "text/event-stream",
      },
    });
    console.log("11111111");
    // 根据环境的不同，变更url
    console.log("eventSource.value", eventSource.value);
    // 建立连接后触发
    eventSource.value.onopen = (e) => {
      console.log("onopen", e);
      console.log("已建立SSE连接~");
    };
    // 接收服务器发送的消息
    eventSource.value.onmessage = (e) => {
      console.log("onmessage", e);

      getCurrUserUnReadNotice().then((res) => {
        console.log("getCurrUserUnReadNotice", res);
        noticeCount.value = res.data;
        noticeContent.value = "您有" + noticeCount.value + "条未读的信息"; //定制内容
        ElMessage({
          message: "您有一条新的消息",
          type: "success",
        });
      });
      currUserUnReadList().then((res) => {
        console.log("currUserUnReadListeventSource", res);
        unreadLength.value = res.total;

        unreadList.value = res.rows;
      });
    };
    eventSource.value.onerror = (e) => {
      console.log("onerrorEventSource", EventSource);
      if (e.readyState == EventSource.CLOSED) {
        console.log("SSE连接关闭");
      } else if (eventSource.value.readyState == EventSource.CONNECTING) {
        console.log("SSE正在重连");
        //重新设置token
        eventSource.value.headers = {
          Authorization: `Bearer ${getToken()}`,
        };
        // getCurrUserUnReadNotice().then((res) => {
        //   console.log("getCurrUserUnReadNotice", res);
        //   noticeCount.value = res.data;
        // });
      } else {
        console.log("error", e);
      }
    };
    // });
  } else {
    console.log("你的浏览器不支持SSE~");
  }
}
//关闭连接

// getInfo().then((res) => {
//   console.log("res", res);
//   userId.value = res.user.userId;
//   const eventSource = new EventSource(
//     baseUrl + "/system/notice/getCurrUserUnReadNotice?userId=" + userId.value
//   );
// });
// const eventSource = new EventSource(
//   baseUrl + "/system/notice/getCurrUserUnReadNotice"
// );
// eventSource.addEventListener("/proxy", (e) => {
//   console.log(e.data);
// });
function toNoticePage() {
  //前往通知公告管理页面
  // console.log("11111111111111");
  proxy.$router.push({ path: "/system/notice" });
}

function startPolling() {
  // 每隔一定时间执行轮询任务
  intervalId.value = setInterval(() => {
    poll();
  }, 30000); // 5秒钟轮询一次，根据需要调整间隔时间
}

function stopPolling() {
  // 清除定时器，停止轮询任务    ！！！！重要，防止内存泄露
  clearInterval(intervalId.value);
}

function poll() {
  // 在这里执行轮询的任务，可以是发送请求或执行其他操作
  listNotice().then((response) => {
    // console.log("image.png", response);
    noticeCount.value = response.total; //获取信息条数
    noticeContent.value = "您有" + noticeCount.value + "条未读的信息"; //定制内容
  });
}

function toggleSideBar() {
  appStore.toggleSideBar();
}

function handleCommand(command) {
  switch (command) {
    case "setLayout":
      setLayout();
      break;
    case "logout":
      logout();
      break;
    case "oldSystem":
      oldSystem();
      break;
    default:
      break;
  }
}
function oldSystem() {
  window.open(
    "http://192.168.3.217:8000/LiveFlowWeb/htm/nwmb/index.html",
    "_blank"
  );
}
function logout() {
  ElMessageBox.confirm("确定注销并退出系统吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      userStore.logOut().then(() => {
        location.href = "/index";
      });
    })
    .catch(() => {});
}

const emits = defineEmits(["setLayout"]);
function setLayout() {
  emits("setLayout");
}
onMounted(() => {
  // startPolling();
  // const headers = { Authorization: "Bearer " + getToken() };
  // const eventSource = new EventSource(
  //   baseUrl + "/system/notice/getCurrUserUnReadNotice",
  //   { headers }
  // );
  // eventSource.onmessage = function (event) {
  //   console.log("New message:", event.data);
  // };
  // eventSource.onerror = function (err) {
  //   console.error("EventSource failed:", err);
  // };
});
onBeforeUnmount(() => {
  // stopPolling();
  closeSSE().then((res) => {
    console.log("closeSSE", res);
  });
});
// beforeDestroy() {
// 	closeSSE().then((res) => {
// 		console.log(res);
// 	});
// }
createSSE();
startData();
getUnreadList();
getInfo1();
// poll();
</script>

<style lang="scss" scoped>
::v-deep .el-empty__image svg {
  color: var(--el-svg-monochrome-grey);
  fill: currentColor;
  width: 80%;
  height: 80%;
  vertical-align: top;
}
.bg:hover {
  background-color: #edf7ff;
}
.navbar {
  height: 50px;
  overflow: hidden;
  position: relative;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);

  .hamburger-container {
    line-height: 46px;
    height: 100%;
    float: left;
    cursor: pointer;
    transition: background 0.3s;
    -webkit-tap-highlight-color: transparent;

    &:hover {
      background: rgba(0, 0, 0, 0.025);
    }
  }

  .breadcrumb-container {
    float: left;
  }

  .topmenu-container {
    position: absolute;
    left: 50px;
  }

  .errLog-container {
    display: inline-block;
    vertical-align: top;
  }

  .right-menu {
    float: right;
    height: 100%;
    line-height: 50px;
    display: flex;

    &:focus {
      outline: none;
    }

    .right-menu-item {
      display: inline-block;
      padding: 0 8px;
      height: 100%;
      font-size: 18px;
      color: #5a5e66;
      vertical-align: text-bottom;

      &.hover-effect {
        cursor: pointer;
        transition: background 0.3s;

        &:hover {
          background: rgba(0, 0, 0, 0.025);
        }
      }
    }

    .avatar-container {
      margin-right: 40px;

      .avatar-wrapper {
        margin-top: 5px;
        position: relative;

        .user-avatar {
          cursor: pointer;
          width: 40px;
          height: 40px;
          border-radius: 10px;
        }

        i {
          cursor: pointer;
          position: absolute;
          right: -20px;
          top: 25px;
          font-size: 12px;
        }
      }
    }
    ::v-deep .el-badge__content {
      margin-top: 15px; /* 调整一下上下左右你喜欢的位置 */
      margin-right: 10px;
    }

    .badge-custom {
      animation: blink-animation 0.5s infinite alternate; /* 设置闪烁动画 */
    }

    @keyframes blink-animation {
      0% {
        opacity: 1;
      } /* 定义动画起始状态 */
      100% {
        opacity: 0.1;
      } /* 定义动画结束状态 */
    }
  }
}
</style>
