<template>
  <div class="manager-container">
    <div class="manager-header">
      <div class="manager-header-left">
        <img style="border-radius: 50%" src="@/assets/imgs/logo.png" alt="" />
        <div class="title">管理系统</div>
      </div>
      <div class="manager-header-center">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item to="/manager/home">首页</el-breadcrumb-item>
          <el-breadcrumb-item>{{
            router.currentRoute.value.meta.name
          }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="manager-header-right">
        <el-dropdown style="cursor: pointer">
          <div style="padding-right: 20px; display: flex; align-items: center">
            <img
              v-if="data.user.avatar"
              :src="data.user?.avatar"
              alt=""
              style="
                width: 40px;
                height: 40px;
                display: block;
                border-radius: 50%;
              "
            />
            <img
              v-else
              src="@/assets/imgs/avatar.png"
              alt=""
              style="
                width: 40px;
                height: 40px;
                display: block;
                border-radius: 50%;
              "
            />
            <span style="margin-left: 5px">{{ data.user?.name }}</span>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click.native="goToPerson"
                >个人资料</el-dropdown-item
              >
              <el-dropdown-item @click.native="router.push('/manager/password')"
                >修改密码</el-dropdown-item
              >
              <el-dropdown-item @click.native="logout"
                >退出登录</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <!-- 添加通知图标 -->
        <div class="notification-wrapper">
          <el-badge :value="data.notifications.length" :hidden="data.notifications.length === 0" class="notification-badge">
            <el-icon class="notification-icon" @click="data.notificationVisible = !data.notificationVisible">
              <Bell />
            </el-icon>
          </el-badge>

          <el-popover
            placement="bottom"
            :width="300"
            trigger="click"
            v-model:visible="data.notificationVisible"
          >
            <template #default>
              <div class="notification-list">
                <div v-if="data.notifications.length === 0" class="no-notification">
                  暂无通知
                </div>
                <div v-else v-for="(item, index) in data.notifications" :key="index" class="notification-item">
                  <div class="notification-title">{{ item.title }}</div>
                  <div class="notification-content">{{ item.content }}</div>
                  <div class="notification-footer">
                    <el-button type="text" size="small" @click="removeNotification(index)">
                      忽略
                    </el-button>
                    <el-button v-if="item.title === '新消息提醒'" type="primary" size="small" link @click="goToChat(index)">
                      查看
                    </el-button>
                  </div>
                </div>
              </div>
            </template>
            <template #reference>
              <div v-if="false"></div> <!-- 空引用，使用图标作为触发器 -->
            </template>
          </el-popover>
        </div>
      </div>
    </div>

    <div style="display: flex">
      <div class="manager-main-left">
        <el-menu
          class="left-menu"
          :default-active="$route.path"
          router
        >
          <el-menu-item index="/manager/home">
            <el-icon><home-filled /></el-icon><span>系统首页</span>
          </el-menu-item>

          <!-- 管理员菜单 -->
          <template v-if="data.user.role === 'admin'">

            <el-sub-menu index="user">
              <template #title>
                <el-icon><UserFilled /></el-icon><span>用户信息</span>
              </template>
              <el-menu-item index="/manager/admin">管理员</el-menu-item>
              <el-menu-item index="/manager/patient">患者</el-menu-item>
              <el-menu-item index="/manager/doctor">医生</el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="health">
              <template #title>
                <el-icon><Location /></el-icon><span>健康管理</span>
              </template>
              <el-menu-item index="/manager/symptomRecord">症状记录</el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="resource">
              <template #title>
                <el-icon><Reading /></el-icon>
                <span>心理资源管理</span>
              </template>
              <el-menu-item index="/manager/resourceCategory">资源分类管理</el-menu-item>
              <el-menu-item index="/manager/treatmentResource">心理资源管理</el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="4">
              <template #title>
                <el-icon><Histogram /></el-icon>
                <span>症状统计</span>
              </template>
              <el-menu-item index="/manager/symptomStatistics">症状数据分析</el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="report-admin">
              <template #title>
                <el-icon><Document /></el-icon>
                <span>评估报告</span>
              </template>
              <el-menu-item index="/manager/assessmentReports">报告管理</el-menu-item>
              <el-menu-item index="/manager/generateReport">生成报告</el-menu-item>
            </el-sub-menu>
          </template>

          <!-- 医生菜单 -->
          <template v-if="data.user.role === 'doctor'">
            <el-sub-menu index="patient">
              <template #title>
                <el-icon><UserFilled /></el-icon><span>患者管理</span>
              </template>
              <el-menu-item index="/manager/patient">患者列表</el-menu-item>
              <el-menu-item index="/manager/symptomRecord">症状记录</el-menu-item>
              <el-menu-item index="/manager/aiChat">智能问答</el-menu-item>
            </el-sub-menu>

            <!-- 修改心理资源管理菜单，增加我的资源入口 -->
            <el-sub-menu index="resource-doctor">
              <template #title>
                <el-icon><Reading /></el-icon>
                <span>心理资源管理</span>
              </template>
              <el-menu-item index="/manager/treatmentResource">心理资源</el-menu-item>
              <el-menu-item index="/manager/myResources">我的资源</el-menu-item>
            </el-sub-menu>

            <!-- 添加症状统计菜单 -->
            <el-sub-menu index="statistics-doctor">
              <template #title>
                <el-icon><Histogram /></el-icon>
                <span>症状统计</span>
              </template>
              <el-menu-item index="/manager/symptomStatistics">症状数据分析</el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="report-doctor">
              <template #title>
                <el-icon><Document /></el-icon>
                <span>评估报告</span>
              </template>
              <el-menu-item index="/manager/patientReports">患者报告</el-menu-item>
              <el-menu-item index="/manager/generateReport">生成报告</el-menu-item>
            </el-sub-menu>
          </template>

          <!-- 患者菜单 -->
          <template v-if="data.user.role === 'patient'">
<!--            <el-sub-menu index="doctor">-->
<!--              <template #title>-->
<!--                <el-icon><UserFilled /></el-icon><span>医生管理</span>-->
<!--              </template>-->
<!--              <el-menu-item index="/manager/doctor">医生列表</el-menu-item>-->
<!--            </el-sub-menu>-->

            <el-sub-menu index="health">
              <template #title>
                <el-icon><Location /></el-icon><span>健康管理</span>
              </template>
              <el-menu-item index="/manager/symptomRecord">症状记录</el-menu-item>
            </el-sub-menu>

            <!-- 修改心理资源菜单，移除资源分类 -->
            <el-sub-menu index="resource-patient">
              <template #title>
                <el-icon><Reading /></el-icon>
                <span>心理资源中心</span>
              </template>
              <el-menu-item index="/manager/treatmentResource">心理资源</el-menu-item>
              <el-menu-item index="/manager/resourceRecommendation">个性化推荐</el-menu-item>
              <el-menu-item index="/manager/aiChat">智能问答</el-menu-item>
            </el-sub-menu>

            <!-- 添加症状统计菜单 -->
            <el-sub-menu index="statistics-patient">
              <template #title>
                <el-icon><Histogram /></el-icon>
                <span>症状统计</span>
              </template>
              <el-menu-item index="/manager/symptomStatistics">我的数据分析</el-menu-item>
            </el-sub-menu>

            <el-menu-item index="/manager/myReports">
              <el-icon><Document /></el-icon>
              <span>我的评估报告</span>
            </el-menu-item>
          </template>

          <!-- 系统管理菜单对所有用户可见 -->
          <el-sub-menu index="sys">
            <template #title>
              <el-icon><Setting /></el-icon><span>系统管理</span>
            </template>
            <!-- 消息聊天 - 医生和患者可见 -->
            <el-menu-item v-if="data.user.role === 'doctor' || data.user.role === 'patient'" index="/manager/chat">
              聊天室
            </el-menu-item>
            <!-- 公告管理 - 仅管理员可见 -->
            <el-menu-item v-if="data.user.role === 'admin'" index="/manager/announcement">公告管理</el-menu-item>
            <!-- 公告列表 - 所有用户可见 -->
            <el-menu-item index="/manager/announcementList">公告列表</el-menu-item>
            <el-menu-item index="/manager/password">修改密码</el-menu-item>
            <el-menu-item @click="logout">退出登录</el-menu-item>
          </el-sub-menu>
        </el-menu>
      </div>

      <div class="manager-main-right">
        <router-view @updateUser="updateUser" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { HomeFilled, UserFilled, Bell, Location, Tickets, Reading, OfficeBuilding, Files, Histogram, Document, ChatDotRound } from "@element-plus/icons-vue";
import { reactive, onMounted } from "vue";
import router from "@/router";

const data = reactive({
  user: JSON.parse(localStorage.getItem("xm-user") || "{}"),
  notifications: [],
  notificationVisible: false,
});
const goToPerson = () => {
  if (data.user.role === "admin") {
    router.push("/manager/pAdmin");
  } else if (data.user.role === "patient") {
    router.push("/manager/pPatient");
  } else if (data.user.role === "doctor") {
    router.push("/manager/pDoctor");
  }
};
const logout = () => {
  localStorage.removeItem("xm-user");
  router.push("/login");
};

const updateUser = () => {
  data.user = JSON.parse(localStorage.getItem("xm-user") || "{}"); // 重新获取下用户的最新信息
};

// 移除通知
const removeNotification = (index) => {
  data.notifications.splice(index, 1);
};

// 添加通知
const addNotification = (notification) => {
  data.notifications.push(notification);
};

// 在script部分添加goToChat方法
const goToChat = (index) => {
  router.push('/manager/chat');
  // 移除通知
  removeNotification(index);
  data.notificationVisible = false;
};

// 监听WebSocket消息
onMounted(() => {
  if (data.user.role === "dispatcher") {
    const ws = new WebSocket("ws://localhost:9090/ws/notification");
    ws.onmessage = (event) => {
      const notification = JSON.parse(event.data);
      if (notification.role === "dispatcher") {
        addNotification(notification);
      }
    };
  }

  if (data.user.id && data.user.role && (data.user.role === 'doctor' || data.user.role === 'patient')) {
    const chatWs = new WebSocket(`ws://${window.location.host}/ws/chat/${data.user.id}/${data.user.role}`);

    chatWs.onopen = () => {
      console.log('聊天通知WebSocket连接已建立');
    };

    chatWs.onmessage = (event) => {
      try {
        const message = JSON.parse(event.data);

        const isInChatPage = router.currentRoute.value.path === '/manager/chat';

        if (!isInChatPage) {
          const notification = {
            title: '新消息提醒',
            content: `${message.senderName || '有人'}发来一条新消息: ${message.content.substring(0, 20)}${message.content.length > 20 ? '...' : ''}`
          };
          addNotification(notification);
        }
      } catch (error) {
        console.error('处理聊天WebSocket消息错误', error);
      }
    };

    chatWs.onclose = () => {
      console.log('聊天通知WebSocket连接已关闭');
    };
  }
});
</script>

<style scoped>
@import "@/assets/css/manager.css";

.notification-badge {
  margin-right: 20px;
}

.notification-icon {
  font-size: 20px;
  cursor: pointer;
  color: #606266;
}

.notification-wrapper {
  position: relative;
  display: inline-block;
  margin-left: auto;
}

.notification-list {
  max-height: 400px;
  overflow-y: auto;
}

.notification-item {
  padding: 12px;
  border-bottom: 1px solid #eee;
}

.notification-item:last-child {
  border-bottom: none;
}

.notification-title {
  font-weight: bold;
  margin-bottom: 8px;
  color: #f56c6c;
}

.notification-content {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.notification-footer {
  text-align: right;
}

.no-notification {
  text-align: center;
  padding: 20px;
  color: #909399;
}
</style>
