<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-popover
                        popper-style="width: 336px; height: 360px; background: #FFFFFF; box-shadow: 0px 2px 8px 0px rgba(0,0,0,0.15);padding:0;"
                >
                    <template #reference>
                        <el-badge
                                :value="msgCount"
                                :max="99"
                                class="badge"
                                :class="msgCount > 0 ? 'flash' : ''"
                                :hidden="msgCount === '0'"
                        >
                            <i
                                    class="icon iconfont right-menu-item hover-effect"
                                    @click="messageDetail"
                                    style="font-size: 22px"
                            >&#xebe7;</i
                            >
                        </el-badge>
                    </template>
                    <template #default>
                        <el-tabs v-model="activeMsg" stretch="true" class="mag-tabs" @tab-click="handleClick">
                            <el-tab-pane label="消息提醒" name="first">
                                <!--                <message-list :msg-category="'third'"></message-list>-->
                                <div class="message-list">
                                    <div class="msg-item" v-for="(msg, index) in messages" :key="index" v-show="messages.length > 0">
                                        <div class="icon">
                                            <img src="@/assets/system/images/layout/msg/icon1.png" alt="" />
                                        </div>
                                        <div class="content">
                                            <div class="title">{{ msg.title }}</div>
                                            <div class="time">{{ msg.time }}</div>
                                        </div>
                                    </div>
                                    <el-empty v-show="messages.length == 0 || messages == null || messages == 'undefined'"
                                              :image-size="100"
                                              description="暂无消息"
                                              class="empty-block"/>
                                </div>
                            </el-tab-pane>
                            <el-tab-pane label="通知" name="second">
                                <!--                <message-list :msg-category="'first'"></message-list>-->
                                <div class="message-list">
                                    <div class="msg-item" v-for="(msg, index) in noticeList" :key="index" v-show="msg.entityType == 1">
                                        <div class="icon">
                                            <img src="@/assets/system/images/layout/msg/icon1.png" alt="" />
                                        </div>
                                        <div class="content">
                                            <div class="title">{{ msg.title }}</div>
                                            <div class="time">{{ msg.time }}</div>
                                        </div>
                                    </div>
                                </div>
                            </el-tab-pane>
                            <el-tab-pane label="公告" name="third">
                                <!--                <message-list :msg-category="'second'"></message-list>-->
                                <div class="message-list">
                                    <div class="msg-item" v-for="(msg, index) in noticeList" :key="index" v-show="msg.entityType == 2">
                                        <div class="icon" >
                                            <img src="@/assets/system/images/layout/msg/icon1.png" alt="" />
                                        </div>
                                        <div class="content">
                                            <div class="title">{{ msg.title }}</div>
                                            <div class="time">{{ msg.time }}</div>
                                        </div>
                                    </div>
                                </div>
                            </el-tab-pane>

                        </el-tabs>
                        <div class="msg-btns">
                            <div class="btn-item" @click="clearNotification">全部已读</div>
                            <div class="btn-item" @click="messageDetail">查看更多</div>
                        </div>
                    </template>
                </el-popover>
                <div class="right-menu-item hover-effect" style="padding-top: 4px;" @click="handleRefreshClick">
                    <el-icon size="22"><Refresh /></el-icon>
                </div>

                <header-search id="header-search" class="right-menu-item" />

                <screenfull id="screenfull" class="right-menu-item hover-effect" />

                <!-- <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" />
                        <span class="nickName">{{ userStore.nickName }}</span>
                    </div>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <router-link to="/user/profile">
                                <el-dropdown-item>个人中心</el-dropdown-item>
                            </router-link>
                            <el-dropdown-item command="setLayout" v-if="settingsStore.showSettings">
                                <span>布局设置</span>
                            </el-dropdown-item>
                            <el-dropdown-item divided command="logout">
                                <span>退出登录</span>
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </div>
        </div>
        <MessageList></MessageList>
    </div>
</template>

<script setup>
    import { ElMessageBox } from 'element-plus'
    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 RuoYiGit from '@/components/RuoYi/Git'
    import RuoYiDoc from '@/components/RuoYi/Doc'
    import useAppStore from '@/store/system/app'
    import useUserStore from '@/store/system/user'
    import useSettingsStore from '@/store/system/settings'
    import useTagsViewStore from '@/store/system/tagsView'
    import {getNum, listMessage, readAll} from "@/api/system/system/message/message"
    import {loginOut} from "@/api/system/sso-auth.js"
    // import MessageList from "@/views/system/system/message/components/messageList.vue";
    import {onMounted, ref,watch} from "vue";
    import moment from 'moment';
    import { listNotice } from "@/api/system/system/notice";

    // 认证模式
    const authType = import.meta.env.VITE_APP_AUTH_TYPE;

    const route = useRoute()
    const router = useRouter();
    const appStore = useAppStore()
    const userStore = useUserStore()
    const settingsStore = useSettingsStore()
    const { proxy } = getCurrentInstance();
    const visitedViews = computed(() => useTagsViewStore().visitedViews);

    // 默认选择的消息类型
    const activeMsg = ref('first')

    // 消息通知数量
    const msgCount = ref(0);
    const messages = ref([])
    const noticeList = ref([])
    const sessionValue = ref(null)
    getMessageNum(); // 第一次主要获取消息

    const wsUri = import.meta.env.VITE_APP_WEBSOCKET_API + '/websocket/message/' + userStore.userId
    // 建立socket连接
    const ws = new WebSocket(wsUri);

    const initWebSocket = () => {
        //查询通知公告
        listNotice().then(response=>{
            console.log('---------- response.rows-------------',response)
            response.rows.forEach(item=>{
                item.title = item.noticeTitle
                item.entityType = item.noticeType
                item.time = item.updateTime != undefined && item.updateTime != null
                    ? formatTimestamp(item.updateTime) : formatTimestamp(item.createTime)
            })
            noticeList.value = response.rows
            console.log('----------noticeList-------------',noticeList.value)
            // messages.value.push(messageData)

        })

        //查询未读消息通知
        listMessage({
            receiverId: userStore.userId,
            hasRead: 0,
            pageNum: 1,
            pageSize: 1000,
        }).then((response) => {
            response.data.rows.forEach(item=>{
                item.time = item.updateTime
                item.entityType = item.category
                // item.title = item.title
            })
            messages.value = [...response.data.rows,...messages.value]
            msgCount.value = messages.value ? messages.value.length : 0;
            console.log('------messages.value----',messages.value)
        });
        ws.onmessage = (event) => { // 服务端推送数据
            // console.log('===服务端推送数据=========>',event.data)
            const messageData = JSON.parse(event.data);
            console.log('===监测数据 messageData=========>',messageData)
            if(messageData){
                messageData.time = messageData.updateTime != undefined && messageData.updateTime != null
                    ? formatTimestamp(messageData.updateTime) : formatTimestamp(messageData.createTime)
                // messages.value.push(messageData)
                messages.value = [messageData, ...messages.value]
            }
            console.log('===存储的数据 messages=========>',messages.value)
            // 消息数量更新
            msgCount.value = messages.value ? messages.value.length : 0;
        };
    }

    onMounted(()=>{
        initWebSocket();
    })
    // 页面注销
    onBeforeUnmount(() => {
        console.log('------页面注销----')
        ws.close();// 关闭socket
    })

    // 格式化时间戳为 YYYY-MM-DD HH:mm:ss 格式
    function formatTimestamp(timestamp) {
        const date = new Date(timestamp);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }

    // 消息查询
    function getMessageNum() {
        getNum()
    }


    // tab-click 事件处理函数
    const handleClick = (tab) => {
        console.log('当前选中的 tab:', tab.props);  // tab 是一个对象，包含当前被点击的 tab 的信息
        const label = tab.props.label
        activeMsg.value = tab.props.name
    };

    function toggleSideBar() {
        appStore.toggleSideBar()
    }

    function handleCommand(command) {
        switch (command) {
            case "setLayout":
                setLayout();
                break;
            case "logout":
                logout();
                break;
            default:
                break;
        }
    }

    function logout() {
        ElMessageBox.confirm('确定注销并退出系统吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            userStore.logOut().then(() => {
                if (authType === 'sso') {
                    // 退出统一认证中心的登录状态
                    loginOut(userStore.userId).then(() => {
                        location.href = '/index';
                    });
                } else {
                    location.href = '/index';
                }
            });
        }).catch(() => { });
    }

    const emits = defineEmits(['setLayout'])
    function setLayout() {
        emits('setLayout');
    }

    function handleRefreshClick(){
        const activeView = visitedViews.value.find(view => view.path === route.path);
        proxy.$tab.refreshPage(activeView);
        if (route.meta.link) {
            useTagsViewStore().delIframeView(route);
        }
    }

    function messageDetail() {
        router.push({ path: '/bases/message'})
    }

    function clearNotification() {
        readAll().then(() => {
            messages.value = []
            msgCount.value = 0
            ElMessage.success("清空成功！");
        })

    }
</script>

<style lang='scss' scoped>
    .message-list {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 100%;
        height: 100%;
        box-sizing: border-box;
        overflow-y: auto;
        overflow-x: hidden;
    }
    .msg-item {
        display: flex;
        align-items: center;
        width: 100%;
        padding: 10px 16px;
        margin-bottom: 10px;
        background: #f9f9f9;
        border-radius: 4px;
    }

    .icon {
        width: 34px;
        height: 34px;
        margin-right: 12px;
        img {
            width: 100%;
            border-radius: 50%;
        }
    }

    .content {
        .title {
            font-size: 14px;
            font-weight: 500;
            color: rgba(0, 0, 0, 0.85);
            margin-bottom: 6px;
        }

        .time {
            font-size: 12px;
            color: rgba(0, 0, 0, 0.45);
        }
    }
    .navbar {
        height: 60px;
        overflow: hidden;
        position: relative;
        background: #fff;
        box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
        text-align: center;
        line-height: 60px;

        ::v-deep .size-icon--style {
            line-height: 60px;
        }

        .hamburger-container {
            line-height: 60px;
            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: 60px;
            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: 0 15px 0 0;

                .avatar-wrapper {
                    display: flex;
                    align-items: center;
                    margin-top: 10px;
                    position: relative;

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

                    .nickName {
                        font-size: 15px;
                        /*font-weight: bold;*/
                        // color: rgba(0, 0, 0, 0.65);
                        color: var(--themeColor);
                        display: inline-block;
                        margin-left: 10px;
                    }

                    i {
                        cursor: pointer;
                        position: absolute;
                        right: -20px;
                        top: 25px;
                        font-size: 12px;
                    }
                }
            }
        }

        .flash ::v-deep .el-badge__content.is-fixed {
            animation: twinkle 1s infinite;
            /*margin-top: 16px;*/
            margin-right: 6px;
        }

        /* 定义闪烁的动画 */
        @keyframes twinkle {
            0% {
                opacity: 1; /* 完全可见 */
            }
            50% {
                opacity: 0.3; /* 半透明 */
            }
            100% {
                opacity: 1; /* 完全可见 */
            }
        }

        .item {
            height: 60px;
            line-height: 60px;
            display: inline-block;
            cursor: pointer;
        }
        .badge :deep(.el-badge__content.is-fixed){
            top: 20px;
            transform: translateY(-50%) translateX(64%);
        }
    }

    .mag-tabs{
        height: calc(100% - 50px);
        ::v-deep .el-tabs__item{
            height:50px;
            line-height: 50px;
        }

        ::v-deep .el-tabs__header{
            margin-bottom: 6px;
        }

        ::v-deep  .el-tabs__content{
            height: calc(100% - 56px);
            .el-tab-pane{
                height: 100%;
            }
        }
    }

    .msg-btns{
        display: flex;
        height: 50px;
        line-height: 50px;
        border-top: 1px solid #e6e6e6;
        .btn-item{
            width: 50%;
            text-align: center;
            cursor: pointer;
            color: rgba(0,0,0,0.85);
            &:last-child{
                border-left: 1px solid #e6e6e6;
            }
        }
    }
</style>
