<!-- 前台头部 -->
<template>
    <el-header class="header-wrapper">
        <div class="header-container">
            <div class="header-left">
                <div class="logo-box">
                    <img class="logo" src="@/assets/img/login/logo-gyl.png" alt="" />
                    <div class="logo_title">供应商管理平台</div>
                </div>
                <div class="menu-container">
                    <!-- <el-tooltip placement="bottom" trigger="hover" popper-class="menu-popover">
                        <template v-slot:content>
                            <span>跳转到工作台</span>
                        </template>
                        <div class="sys-home" @click="goHome">
                            <svg-icon
                                icon-style="icon header-icon"
                                icon-class="home"
                                title="首页"
                            />
                        </div>
                    </el-tooltip> -->
                    <!-- <div class="line"></div>
                    <el-tooltip placement="right" trigger="hover" popper-class="menu-popover">
                        <template v-slot:content>
                            <span>{{ menuCardShow ? '收起菜单' : '展开菜单' }}</span>
                        </template>
                        <div
                            :class="['current-group', { expansion: menuCardShow }]"
                            @click="toggleMenuCard"
                        >
                            <svg-icon
                                icon-style="icon header-icon"
                                :icon-class="
                                    currentMenuGroup.menuIcon ? currentMenuGroup.menuIcon : ''
                                "
                                :title="currentMenuGroup.name"
                            />
                            <span class="current-home-name">{{ currentMenuGroup.name }}</span>
                        </div>
                    </el-tooltip>
                    <div :class="['all-menu', menuCardShow ? 'all-menu-show' : '']">
                        <div
                            class="all-menu-content"
                            tabindex="-1"
                            @blur="allMenuBlur"
                            ref="allNavContentRef"
                        >
                            <div
                                :class="[
                                    'menu-btn',
                                    item.alias === currentMenuGroupAlias ? 'menu-btn-active' : ''
                                ]"
                                v-for="item in userMenuList"
                                :key="item.alias"
                                @click="menuClick(item)"
                            >
                                <svgIcon
                                    icon-style="icon header-icon"
                                    :icon-class="item.menuIcon ? item.menuIcon : ''"
                                />
                                <span> {{ item.name }}</span>
                            </div>
                        </div>
                    </div> -->
                </div>
            </div>
            <div class="header-right">
                <div class="bell-box" @click="handleOpenMsgCenter">
                    <el-badge
                        class="item"
                        type="danger"
                        :value="msgNum"
                        :show-zero="false"
                        :offset="[-2, 6]"
                    >
                        <el-tooltip class="box-item" effect="dark" placement="top">
                            <template #content>
                                <div class="theme-text">消息中心</div>
                            </template>
                            <!-- <img src="@/assets/img/layout/bell.png" alt="" /> -->
                            <el-icon class="no-inherit">
                                <bell />
                            </el-icon>
                        </el-tooltip>
                    </el-badge>
                </div>
                <UserAvator class="avatar" />
                <el-popover
                    popper-class="header-popper"
                    width="300"
                    placement="bottom"
                    trigger="click"
                >
                    <template v-slot:reference>
                        <div class="user-box">
                            <div class="welcome">
                                你好，{{
                                    userStore.getUserDetail &&
                                    userStore.getUserDetail.user &&
                                    userStore.getUserDetail.user.fullname
                                }}
                                <el-icon><CaretBottom /></el-icon>
                            </div>
                            <div class="department">{{ companyDepartment }}</div>
                        </div>
                    </template>
                    <div class="user-box-header flex">
                        <UserAvator class="avatar" style="margin-right: 15px" :size="30" />
                        <div>
                            <h3
                                v-if="
                                    userStore.getUserDetail &&
                                    userStore.getUserDetail.user &&
                                    userStore.getUserDetail.user.fullname
                                "
                                style="margin: 5px 0"
                            >
                                {{
                                    userStore.getUserDetail &&
                                    userStore.getUserDetail.user &&
                                    userStore.getUserDetail.user.fullname
                                }}
                            </h3>
                        </div>
                    </div>
                    <div class="user-link">
                        <div class="user-link-item" @click="openPersonalCenter">
                            <el-icon class="link-icon"><Avatar /></el-icon>
                            个人中心
                        </div>
                        <div class="user-link-item" @click="openResetPwdDialog">
                            <el-icon class="link-icon"><Tools /></el-icon>
                            修改密码
                        </div>
                        <div class="user-link-item" v-if="userType !== 2" @click="handleSysPlat">
                            <el-icon class="link-icon"><Platform /></el-icon>
                            管理系统
                        </div>
                        <div class="user-link-item">
                            <el-icon class="link-icon"><StarFilled /></el-icon>
                            {{ themeStore.isLightTheme ? '浅色主题' : '深色主题' }}
                            <el-switch
                                v-model="theme"
                                active-value="white"
                                size="small"
                                inactive-value="blue"
                                style="margin-left: 10px"
                                :disabled="themeStore.isThemeChanging"
                                @change="setThemeColor"
                            />
                        </div>
                        <!-- <div class="user-link-item" @click="logout">
                            <el-icon class="link-icon"><CircleCloseFilled /></el-icon>
                            退出登录
                        </div> -->
                    </div>
                    <div class="flex user-box-logout" @click="logout">
                        <el-button class="user-box-logout-button" type="" link>
                            退出系统
                        </el-button>
                    </div>
                </el-popover>
            </div>
        </div>
        <MessageDrawer v-model:is-show="showMsgDrawer" @refresh="getMsgNum"></MessageDrawer>

        <!-- 全局主题切换Loading遮罩 -->
        <div v-if="themeStore.isThemeChanging" class="theme-switching-overlay">
            <div class="theme-switching-content">
                <div class="theme-switching-spinner"></div>
                <div class="theme-switching-text">主题切换中...</div>
            </div>
        </div>
    </el-header>
</template>

<script lang="ts" setup>
import { computed, ref, nextTick, onMounted } from 'vue'
import { formatOrgName, selectPriorityOrg } from '@/utils/userInfo'
import UserAvator from '@/components/UserAvator/index.vue'
import { useUserStore } from '@/stores/user'
import { useMenuStore } from '@/stores/menu'
import { useThemeStore } from '@/stores/theme'
import { useRouter } from 'vue-router'
import { getFisrtModulePath } from '@/utils/menu'
import { getToken } from '@/utils/cookie'
import { getMsgbadge } from '@/api/system/message'
import MessageDrawer from '@/components/Message/MessageDrawer.vue'
/**
 * 获取菜单信息
 */
const themeStore = useThemeStore()
const theme = computed({
    get: () => (themeStore.currentTheme === 'theme-white' ? 'white' : 'blue'),
    set: (value) => {
        // 这里需要更新theme值以保持switch组件状态同步
        // 实际的主题切换由setThemeColor方法处理
    }
})

const msgNum = ref(0) // 新消息数量

const showMsgDrawer = ref(false) // 显示消息中心弹窗

const menuStore = useMenuStore()

const userMenuList = menuStore.getNormalMenuData

const currentMenuGroup = computed(() => menuStore.getCurrentMenuGroup)

const currentMenuGroupAlias = computed(() => menuStore.currentMenuGroupAlias)

const menuCardShow = ref(false)

const allNavContentRef = ref<HTMLElement | null>(null)
// 切换菜单显示
const toggleMenuCard = () => {
    if (menuCardShow.value) {
        menuCardShow.value = false
    } else {
        menuCardShow.value = true
        nextTick(() => {
            allNavContentRef.value && allNavContentRef.value.focus()
        })
    }
}

// 菜单弹出层失焦时间
const allMenuBlur = () => {
    nextTick(() => {
        menuCardShow.value = false
    })
}

onMounted(() => {
    getMsgNum()
    // 初始化主题
    themeStore.initTheme()
})

// 获取消息数量
const getMsgNum = async () => {
    try {
        const { value = 0, state } = (await getMsgbadge()) as any
        if (state) {
            msgNum.value = value
        }
    } catch (error) {
        console.error('获取消息数量失败:', error)
    }
}

const handleOpenMsgCenter = () => {
    showMsgDrawer.value = true
}

const router = useRouter()

const goHome = () => {
    router.push('/platLayout/home')
}

const menuClick = (item: any) => {
    menuStore.setCurrentMenuGroup(item)
    menuStore.setCurrentMenuGroupAlias(item.alias)
    toggleMenuCard()
    const firstBzRouter = getFisrtModulePath([item], '/platLayout')
    const hasHomePage = item.tabsStyle && JSON.parse(item.tabsStyle).tabType === 'card' // 利用菜单标签风格字段：选项卡样式
    if (hasHomePage) {
        router.push(item.routerPath)
    } else {
        router.push(firstBzRouter)
    }
}

/**
 * 获取用户信息
 */
const userStore = useUserStore()

const userDetail = computed(() => userStore.getUserDetail)

// 用户类型
const userType = computed(() => {
    const userDetail = userStore.getUserDetail
    const { userType = '' } = userDetail?.user || {}
    return userType
})

// 用户所属公司部门
const companyDepartment = computed(() => {
    const userDetail = userStore.getUserDetail
    const orgList = userDetail?.org || []
    // 处理空数据情况
    if (!Array.isArray(orgList) || orgList.length === 0) {
        return ''
    }
    // 选择优先显示的部门
    const selectedOrg = selectPriorityOrg(orgList)
    // 优先返回orgPathName
    if (selectedOrg?.orgPathName) {
        return selectedOrg.orgPathName
    }
    return formatOrgName(selectedOrg)
})

/**
 *  跳转操作
 */

const openPersonalCenter = () => {
    router.push('/platLayout/personalInfo')
}

const openResetPwdDialog = () => {
    router.push('/platLayout/resetPwd')
}

const handleSysPlat = () => {
    const token = getToken()
    const { MANAGE_PLAT_URL = '' } = (window as any).config
    const url = MANAGE_PLAT_URL + '/mvue/getAuth?token=' + token
    window.open(url, '_blank')
}

const logout = () => {
    userStore.userLogout()

    router.push('/login')
}

// 设置主题颜色
const setThemeColor = async () => {
    // 直接根据当前switch状态切换主题
    const newTheme = themeStore.currentTheme === 'theme-white' ? 'theme-blue' : 'theme-white'
    await themeStore.setTheme(newTheme)
}
</script>

<style lang="scss" scoped>
.header-wrapper {
    padding: 0;
}
.header-container {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    z-index: 999;
    padding-left: 16px;
    box-sizing: border-box;
    // background:
    //     url('@/assets/img/layout/header-bg.png') no-repeat 0 0,
    //     linear-gradient(180deg, var(--theme-header-bg) 0%, var(--theme-header-bg) 100%);
    // background-size: 100% 100%;
    background: var(--theme-header-container-bg);
    > * {
        font-family:
            Microsoft YaHei,
            serif;
    }

    .header-left {
        flex: 1;
        display: flex;
        align-items: center;
        column-gap: 60px;
        height: 100%;
        position: relative;

        .logo-box {
            height: 100%;
            box-sizing: border-box;
            display: flex;
            align-items: center;

            .logo {
                width: 140px;
                margin-right: 20px;
                margin-top: -5px;
            }

            .logo_title {
                cursor: pointer;
                display: flex;
                flex-direction: column;
                margin-top: 2px;
                margin-right: 100px;
                font-weight: bold;
                font-size: 24px;
            }
        }
        .menu-container {
            display: flex;
            align-items: center;
            // gap: 10px;
            height: 100%;
        }
        .line {
            width: 1px;
            height: 16px;
            background-color: #fff;
            opacity: 0.5;
        }
        .header-icon {
            font-size: 28px;
            color: var(--theme-text-primary);
        }
        .sys-home {
            cursor: pointer;
            padding: 0 20px;
            cursor: pointer;
        }
        .current-group {
            display: flex;
            align-items: center;
            padding: 0 20px;
            gap: 8px;
            cursor: pointer;
        }
        .current-group.expansion {
            background-color: var(--theme-system-module-1);
            height: 100%;
        }
        .current-home-name {
            color: var(--theme-text-primary);
        }
        .all-menu {
            position: absolute;
            left: 480px;
            bottom: 0;
            width: 536px;
            height: 0;
            z-index: 2004;
            transition:
                height 0.2s,
                bottom 0.2s,
                opacity 0.1s;
            opacity: 0;
            pointer-events: none;
            overflow: hidden;
            background: var(--theme-system-module-1);
            border-radius: 0 0 16px 16px;
            box-shadow: 0 4px 10px 0 var(--theme-box-color-3);

            &.all-menu-show {
                bottom: -312px;
                height: 312px;
                opacity: 1;
                pointer-events: auto;
            }

            .all-menu-content {
                width: 100%;
                height: 100%;
                padding: 24px;
                box-sizing: border-box;
                display: flex;
                flex-wrap: wrap;
                column-gap: 8px;
                row-gap: 8px;

                &:focus {
                    outline: none;
                }

                .menu-btn {
                    width: calc((100% - 24px) / 4);
                    height: 130px;
                    background: linear-gradient(
                        360deg,
                        var(--theme-box-color-5) 0%,
                        var(--theme-box-color-4) 100%
                    );
                    border-radius: 8px;
                    display: flex;
                    flex-direction: column;
                    row-gap: 16px;
                    align-items: center;
                    justify-content: center;
                    cursor: pointer;
                    transition: all 1s;
                    box-sizing: border-box;

                    @mixin hover-active {
                        background: linear-gradient(
                            360deg,
                            var(--theme-box-color-1) 0%,
                            var(--theme-box-color-3) 100%
                        );

                        span,
                        svg {
                            color: $system-hover-active-text;
                        }
                    }

                    &:hover {
                        @include hover-active;
                    }

                    &.menu-btn-active {
                        @include hover-active;
                    }

                    span {
                        display: inline-block;
                        height: 24px;
                        line-height: 24px;
                        font-size: 18px;
                        font-family:
                            Microsoft YaHei,
                            serif;
                        font-weight: 400;
                        color: var(--theme-text-primary);
                        transition: all 0.3s;
                        user-select: none;
                    }

                    svg {
                        font-size: 42px;
                        color: var(--theme-text-primary);
                        transition: all 0.3s;
                    }
                }
            }
        }
    }

    .header-right {
        margin-right: 16px;
        display: flex;
        align-items: center;

        .bell-box {
            padding: 5px;
            cursor: pointer;
            user-select: none;
        }

        .avatar {
            margin: 0 20px;
        }

        .user-box-header {
            padding: 10px;

            h3 {
                font-weight: bold;
                margin: 2px 0;
            }
        }

        .input {
            width: 340px;
            height: 40px;
            border-radius: 4px;
            margin: 19px 36px;
            margin-left: 24px;

            :deep(.el-input input),
            :deep(.el-input-group__append) {
                background-color: #f1f1f1;
                border: none;

                .el-icon-search {
                    font-size: 18px;
                }
            }

            :deep(.el-input-group) {
                height: 100%;
            }

            :deep(.el-input) {
                input {
                    font-size: 16px;
                    font-weight: normal;
                    font-stretch: normal;
                    line-height: 19px;
                    letter-spacing: 0;
                    height: 100%;
                }

                input::-webkit-input-placeholder {
                    // 针对 谷歌 内核
                    font-family:
                        Microsoft YaHei,
                        serif;
                    font-size: 16px;
                    font-weight: normal;
                    font-stretch: normal;
                    line-height: 19px;
                    letter-spacing: 0;
                    color: #c4c4c4;
                }

                input:-moz-placeholder {
                    // 火狐
                    font-family:
                        Microsoft YaHei,
                        serif;
                    font-size: 16px;
                    font-weight: normal;
                    font-stretch: normal;
                    line-height: 19px;
                    letter-spacing: 0;
                    color: #c4c4c4;
                }

                input:-ms-input-placeholder {
                    // 微软ie
                    font-family:
                        Microsoft YaHei,
                        serif;
                    font-size: 16px;
                    font-weight: normal;
                    font-stretch: normal;
                    line-height: 19px;
                    letter-spacing: 0;
                    color: #c4c4c4;
                }
            }
        }

        .user-box {
            display: flex;
            flex-direction: column;
            margin-right: 10px;
            row-gap: 2px;
            cursor: pointer;

            .welcome {
                display: flex;
                align-items: center;
                font-size: 14px;
                font-family:
                    Microsoft YaHei,
                    Microsoft YaHei,
                    serif;
                color: var(--theme-text-inverse);
                font-weight: 700;

                i {
                    color: var(--theme-text-inverse);
                    font-size: 14px;
                    margin-left: 8px;
                }
            }

            .department {
                font-size: 12px;
                font-family:
                    Microsoft YaHei,
                    Microsoft YaHei,
                    serif;
                font-weight: 400;
                color: var(--theme-text-primary);
            }
        }
    }
}
</style>

<style lang="scss">
.no-inherit {
    font-size: 24px;
    margin-top: 10px;
    color: var(--theme-text-primary);
}
.header-popper {
    width: 220px !important;
    border-radius: 10px;
    padding: 8px 12px 16px !important;
    vertical-align: middle;

    * {
        font-size: 14px;
    }
    .user-link {
        padding: 10px 0;
        .user-link-item {
            padding: 4px 2px;
            display: flex;
            align-items: center;
            gap: 6px;
            margin: 4px 0;
            cursor: pointer;
        }
        .user-link-item:hover {
            color: $system-hover-active-text;
            background-color: var(--theme-box-color-3);
        }
        .link-icon {
            font-size: 14px;
        }
        .user-link-item:hover {
            .link-icon {
                color: $system-hover-active-text !important;
            }
        }
    }

    .user-box-logout {
        justify-content: center;
    }
}
.user-box-logout-button {
    color: var(--theme-text-primary) !important;

    &:hover {
        color: var(--theme-primary) !important;
    }
}

/* 全局主题切换Loading遮罩 */
.theme-switching-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: var(--theme-loading-mask-bg);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;
    backdrop-filter: blur(5px);
}

.theme-switching-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16px;
    padding: 24px;
    background-color: var(--theme-system-module-1);
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.theme-switching-spinner {
    width: 40px;
    height: 40px;
    border: 3px solid var(--theme-border-tertiary);
    border-top: 3px solid var(--theme-primary);
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

.theme-switching-text {
    font-size: 14px;
    color: var(--theme-text-primary);
    font-weight: 500;
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }
    100% {
        transform: rotate(360deg);
    }
}
</style>
