<template>
    <el-container
        v-loading="isAppLoadings" class="hc-layout-box" 

        :class="{ 'yn-theme': !isYunNanProject, 'is-no-layout': !isNullES(isLayout) && isLayout === 'no' }"
    >
        <div v-if="appTheme === 'dark'" class="hc-app-bg-box">
            <img :src="appViewBg" alt="">
        </div>
        <el-header class="hc-layout-header">
            <div v-if="!isYunNanProject" class="hc-layout-header-logo" :style="`width: ${isCollapse ? '0px' : '200px'};`" @click="logoClick">
                <!-- <img id="logo-icon" :src="appLogoIcon" alt=""> -->
                <img v-show="!isCollapse" id="logo-name" :src="appLogoName" alt="">
            </div>
            <div v-else class="hc-layout-header-logo" @click="logoClick">
                <img id="logo-icon" :src="appLogoIcon" alt="">
                <!-- <img v-show="!isCollapse" id="logo-name" :src="appLogoName" alt=""> -->

                <div class="ml-2">
                    <div class="text-18px font-900">工程项目档案资料管理系统</div>
                    <div class="text-12px">Engineering Project File Manegement Platform</div>
                </div>
            </div>
            <div class="header-top-collapse-bar" @click="collapseChange">
                <HcIcon v-if="isCollapse" name="menu-unfold" />
                <HcIcon v-else name="menu-fold" />
            </div>
            <div class="header-top-menu-bar">
                <HcTopMenuBar v-if="!isYunNanProject" @load="topMenuLoad" @change="topMenuChange" />
            </div>
            <div class="header-content-bar">
                <HcCascader v-if="userRoleId !== website.role_id" @send="cascaderSend" @change="cascaderChange" />
                <div v-else class="hc-header-project-name-box" @click="userProjectClick">
                    <HcIcon name="arrow-right" class="project-icon" />
                    <div class="truncate">{{ projectInfoData?.projectName ?? '请先选择项目' }}</div>
                </div>
                <hc-upload-bar v-if="!isYunNanProject" />
                <HelpInfoBar v-if="!isYunNanProject" />
                <ConfigBar v-if="!isYunNanProject" />
                <UserInfoBar @load="userInfoLoad" />
            </div>
        </el-header>
        <el-container class="hc-layout-container">
            <el-aside v-if="isAsideMenu" class="hc-layout-aside" :class="[isCollapse ? 'is-collapse' : '']" :width="isCollapse ? '90px' : '200px'">
                <MenuBar :collapse="isCollapse" :cur="menuBarKey" :datas="menuBarData" :msg-count="msgCount" @change="menuBarChange" />
            </el-aside>
            <el-main class="hc-layout-main">
                <div class="hc-router-menu-bar">
                    <RouterMenu @load="routerMenuLoad" />
                </div>
                <div id="hc-main-box" class="hc-main-page">
                    <div class="hc-main-body">
                        <router-view v-if="reloadRouter" v-slot="{ Component }">
                            <transition name="fade-transform">
                                <keep-alive :max="10" exclude="HcDataV">
                                    <component :is="Component" :msg-count="msgCount" :msg-change="msgChange" />
                                </keep-alive>
                            </transition>
                        </router-view>
                    </div>
                </div>
            </el-main>
        </el-container>
        <hc-reminder v-model="isReminderShow" :text="isReminderText" />
    </el-container>
</template>

<script setup>
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import { getArrValue, getObjValue, isNullES, useClick } from 'js-fast-way'
import { HcSocket } from '~src/plugins/HcSocket'
import { useRoute, useRouter } from 'vue-router'
import { useAppStore } from '~src/store'
import { initButtons } from '~sto/app'
import { HcAnnouncement } from 'hc-vue3-ui'
import { useProject } from '~sto/useProject'
import website from '~src/config'
import appLogoIcon from '~src/assets/logo/yunnan.png'


//初始组合式
const router = useRouter()
const useRoutes = useRoute()
const store = useAppStore()

const reloadRouter = ref(false)
const userRoleId = ref(store.getRoleId)
const projectInfoData = ref(store.getProjectInfo)
const projectId = ref(store.getProjectId)
// 判断是否为云南项目
const isYunNanProject = ref(projectId.value === '1904814720589430785')


// 添加watch来更新isYunNanProject
watch(() => projectId.value, (newProjectId) => {
    isYunNanProject.value = newProjectId === '1904814720589430785'
})

//子组件
import HcTopMenuBar from './modules/HcTopMenu.vue'
import HcCascader from './modules/Cascader.vue'
import UserInfoBar from './modules/UserInfoBar.vue'
import HelpInfoBar from './modules/HelpInfoBar.vue'
import ConfigBar from './modules/ConfigBar.vue'
import RouterMenu from './modules/RouterMenu.vue'
import MenuBar from '~src/layout/modules/MenuBar.vue'
import appViewBg from '~src/assets/view/bg.png'

// logo
const appLogoName = ref(store.getLogoName)
const appTheme = ref(store.getTheme)

//菜单数据
const menuBarKey = ref('')
const menuBarData = ref([])
const isLayout = ref('')

//获取项目信息
const { isAppLoading } = useProject()
// 在 setup 中添加

//渲染完成
onMounted(async () => {
    const layout = useRoutes?.query?.layout, layout2 = store.isLayout
    isLayout.value = layout ?? layout2
    annRefs.value = []
    initButtons()
     // 确保初始化时加载样式
    currentStyle = await loadStyles()
})

//监听layout
watch(() => [useRoutes?.query?.layout, store.isLayout], ([layout, layout2]) => {
    isLayout.value = layout ?? layout2
}, { deep: true })

//监听
watch(() => store.getTheme, (theme) => {
    appTheme.value = theme
})

//监听项目信息变化
const isAppLoadings = ref(true)
watch(() => isAppLoading.value, (res) => {
    if (!website.localModel) {
        reloadRouter.value = res
        isAppLoadings.value = !res
    } else {
        if (res) {
            setTimeout(() => {
                isAppLoadings.value = false
            }, 1000)
        } else {
            isAppLoadings.value = true
        }
    }
}, { immediate:true })

//路由信息
const routerMenuLoad = ({ key }) => {
    menuBarKey.value = key
}

// 是否折叠
const isCollapse = ref(false)
const collapseChange = () => {
    const bool = !isCollapse.value
    isCollapse.value = bool
    store.setCollapse(bool)
}

//顶部菜单导航
const isAsideMenu = ref(true)
const topMenuLoad = () => {
    isAsideMenu.value = false
}

// 修改菜单数据的监听逻辑
watch(() => store.getMenus, (val) => {
    if (isYunNanProject.value) {
        const filterAndRenameMenus = (menus) => {
            return menus.map(menu => {
                // 创建新对象，而不是修改原对象
                const newMenu = { ...menu }
                
                // 过滤掉个人中心和系统设置
                if (newMenu.name === '个人中心' || newMenu.name === '系统设置') {
                    return null
                }
                
                // 重命名档案收集为文件管理
                if (newMenu.name === '档案收集') {
                    newMenu.name = '文件管理'
                }
                
                // 递归处理子菜单
                if (newMenu.children && newMenu.children.length > 0) {
                    newMenu.children = filterAndRenameMenus(newMenu.children)
                }
                
                return newMenu
            }).filter(Boolean) // 过滤掉null值
        }
        
        menuBarData.value = filterAndRenameMenus(getArrValue(val))
    }
}, { immediate: true })
//顶部菜单导航被点击// 修改顶部菜单切换方法
const topMenuChange = (data) => {
    if (!isYunNanProject.value && !isNullES(data)) {
        menuBarData.value = data
        isAsideMenu.value = true
    }
}
//菜单被点击
const menuBarChange = ({ code }) => {
    menuBarKey.value = code
    if (code === 'statistics-datav') {
        // 如果跳转到数据看板，记录当前路由作为来源路径
        const currentRoute = router.currentRoute.value
        router.push({ 
            name: code,
            query: {
                from: currentRoute.fullPath,
            },
        })
    } else {
        router.push({ name: code })
    }
}

//消息数量
const msgCount = ref({
    allCount: 0,
    taskCount: 0,
    messageCount: 0,
    messageCount_1: 0,
    messageCount_2: 0,
    messageCount_3: 0,
    messageCount_4: 0,
    messageCount_5: 0,
})
const msgChange = ref(0)

//用户信息
const userId = ref('')

const userInfoLoad = ({ user_id }) => {
    userId.value = user_id
}

//项目合同段的ID
let socket
const cascaderSend = async ({ projectId, contractId }) => {
    await useClick()
    if (isNullES(contractId)) {
        //本地模式
        if (website.localModel) {
            window.$message?.error('项目信息不存在,请联系管理员')
            reloadRouter.value = false
        }
        return
    }
    //本地模式
    if (website.localModel) {
        setTimeout(() => {
            reloadRouter.value = true
        }, 1000)
    } else {
        reloadRouter.value = true
    }
    //链接webSocket
    if (!isNullES(socket)) socket.close()
    socket = new HcSocket({ projectId, contractId, userId: userId.value }, (res) => {
        socketData(res?.data)
    })
}

//长链接消息
let annUpdateRef
const annRefs = ref([])
const isReminderShow = ref(false)
const isReminderText = ref('')
const socketData = async (res) => {
    console.log('socket:', res)
    const { type, data } = getObjValue(res)
    if (type === 'msgUpdateMsg') {
        closeAnnUpdate()
        //内容为空时，代表公告已经取消，由于前面已经关闭，所以不再创建
        if (isNullES(data)) return
        await nextTick()
        //系统更新公告，直接替换
        annUpdateRef = await HcAnnouncement({ type: 'update', data: data })
    } else if (type === 'msgSystemMsg') {
        //内容为空时，代表公告已经取消，由于前面已经关闭，所以不再创建
        if (isNullES(data)) {
            closeAnnFun()
            return
        }
        await nextTick()
        //普通公告，追加公告
        const ref = await HcAnnouncement({ type: 'system', data: data })
        annRefs.value.push(ref)
    } else if (type === 'msgLink') {
        if (store.isLogin) {
            socket.send('getMsg')
            store.setIsLogin(false)
        }
    } else if (type === 'msgCountDown') {
        //倒计时更新
        if (isNullES(data) || data <= 0) {
            closeReminder()
            return
        }
        isReminderText.value = `系统将在${data}秒后，进行更新`
        setReminderText(data - 1)
        isReminderShow.value = true
    }
}

//倒计时
let timeRef
let startTime
const setReminderText = (totalTime) => {
    startTime = performance.now()
    const step = () => {
        const elapsedTime = Math.floor((performance.now() - startTime) / 1000)
        const remainingTime = totalTime - elapsedTime
        if (remainingTime < 0) {
            closeReminder()
            return
        }
        isReminderText.value = `系统将在${remainingTime}秒后，进行更新`
        requestAnimationFrame(step)
    }
    requestAnimationFrame(step)
}


//关闭倒计时
const closeReminder = () => {
    isReminderShow.value = false
    if (!isNullES(timeRef)) {
        clearTimeout(timeRef)
        timeRef = null
    }
}

// 项目切换
const cascaderChange = () => {
    reloadRouter.value = false
}

//首页
const logoClick = () => {
    router.push({ name: 'statistics-datav' })
}

const userProjectClick = () => {
    router.push({ path: '/user/project' })
}

//关闭普通公告
const closeAnnFun = () => {
    const refs = annRefs.value
    for (let i = 0; i < refs.length; i++) {
        if (!isNullES(refs[i])) {
            refs[i]?.close()
        }
    }
    annRefs.value = []
}

//关闭系统更新公告
const closeAnnUpdate = () => {
    if (!isNullES(annUpdateRef)) {
        annUpdateRef.close()
        annUpdateRef = null
    }
}

//页面卸载
onUnmounted(() => {
    if (!isNullES(socket)) socket.close()
    closeAnnFun()
    closeAnnUpdate()
    return () => {
    if (currentStyle) {
      document.head.removeChild(currentStyle)
    }
  }
})

// 动态加载样式
const loadStyles = async () => {
  try {
    // 1. 首先移除所有已存在的样式
    const existingStyles = document.head.querySelectorAll('style[data-theme]')
    existingStyles.forEach(style => {
      document.head.removeChild(style)
    })

    // 2. 创建新的样式元素
    const styleElement = document.createElement('style')
    styleElement.type = 'text/css'
    // 添加标识，方便后续清理
    styleElement.setAttribute('data-theme', isYunNanProject.value ? 'yunnan' : 'default')

    // 3. 加载对应的样式模块
    const module = isYunNanProject.value 
      ? await import('./test-yn/index-yn.scss?inline')
      : await import('./index.scss?inline')
    
    styleElement.textContent = module.default
    document.head.appendChild(styleElement)
    currentStyle = styleElement

    // 4. 强制重新计算样式
    document.documentElement.style.display = 'none'
    document.documentElement.offsetHeight // 触发重排
    document.documentElement.style.display = ''

    return styleElement
  } catch (error) {
    console.error('加载样式失败:', error)
    return null
  }
}
let currentStyle = null



// 监听项目类型变化，动态切换样式
watch(() => isYunNanProject.value, async (newVal) => {
  await loadStyles()
  console.log('样式已更新:', newVal ? 'yunnan' : 'default')
}, { immediate: true })
// 添加watch来更新isYunNanProject
watch(() =>store.getProjectId, (newProjectId) => {
    isYunNanProject.value = newProjectId === '1904814720589430785'
    //重新加载菜单
    let val = store.getMenus
    if (!isYunNanProject.value) {
       
        return
    }
     const filterAndRenameMenus = (menus) => {
            return menus.map(menu => {
                // 创建新对象，而不是修改原对象
                const newMenu = { ...menu }
                
                // 过滤掉个人中心和系统设置
                if (newMenu.name === '个人中心' || newMenu.name === '系统设置') {
                    return null
                }
                
                // 重命名档案收集为文件管理
                if (newMenu.name === '档案收集') {
                    newMenu.name = '文件管理'
                }
                
                // 递归处理子菜单
                if (newMenu.children && newMenu.children.length > 0) {
                    newMenu.children = filterAndRenameMenus(newMenu.children)
                }
                
                return newMenu
            }).filter(Boolean) // 过滤掉null值
        }
        
        menuBarData.value = filterAndRenameMenus(getArrValue(val))
         isAsideMenu.value = true
       

})
// 组件卸载时清理样式
</script>


