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

        :class="{ 'yn-theme': !isYunNanProject, 'is-no-layout': !isNullES(isLayout) && isLayout === 'no' }"
    >
        <el-header class="hc-layout-header">
            <!-- <div class="hc-layout-header-logo" :style="`width: ${isCollapse ? '0px' : '200px'};`" @click="logoClick">
                <img v-show="!isCollapse" id="logo-name" :src="appLogoName" alt="">
            </div> -->
            <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 Priject 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 @send="cascaderSend" @change="cascaderChange" />
                <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">
                                    <component :is="Component" :msg-count="msgCount" />
                                </keep-alive>
                            </transition>
                        </router-view>
                    </div>
                </div>
            </el-main>
        </el-container>
        <hc-reminder v-model="isReminderShow" :text="isReminderText" />
    </el-container>
</template>

<script setup>
import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getArrValue, getObjValue, isNullES, useClick } from 'js-fast-way'
import { HcSocket } from '~src/plugins/HcSocket'
import { HcAnnouncement } from 'hc-vue3-ui'
import { useAppStore } from '~src/store'
import { initButtons } from '~sto/app'
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 { isAppLoading } = useProject()

//子组件
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'

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

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

const projectId = ref(store.getProjectId)
// 判断是否为云南项目
const isYunNanProject = ref(projectId.value === '1904814720589430785')


// 添加watch来更新isYunNanProject
watch(() => projectId.value, (newProjectId) => {
    isYunNanProject.value = newProjectId === '1904814720589430785'
})
//渲染完成
onMounted(() => {
    const layout = useRoutes?.query?.layout, layout2 = store.isLayout
    isLayout.value = layout ?? layout2
    annRefs.value = []
    initButtons()
})

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

//监听项目信息变化
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
}

//顶部菜单导航被点击
const topMenuChange = (data) => {
    if (!isYunNanProject.value && !isNullES(data)) {
        menuBarData.value = data
        isAsideMenu.value = true
    }
}
// 修改菜单数据的监听逻辑
watch(() => store.getMenus, (val) => {
    if (isYunNanProject.value) {
        let newVal = getArrValue(val)
        let newArr = []
        for (let index = 0; index < newVal.length; index++) {
            const element = newVal[index]
            if (element.parentId === '0' && ( element.code !== 'tasks' && element.code !== 'patrol-menu' && element.code !== 'tentative-menu' )) {
                let arr2 = element.children
                if (arr2) {
                    for (let index = 0; index < arr2.length; index++) {
                    const element2 = arr2[index]
                    newArr.push(element2)
                }
                }
               
             
            } else if (element.code === 'patrol-menu') {
                newArr.push(element)
            } else if (element.code === 'tasks') {
                // 先跳过 tasks，最后再添加
                newArr.push(element)
            }

            // 最后添加 tasks
           

            
        }
      
       let obj1 = newArr[newArr.length - 1]
       let obj2 = newArr[newArr.length - 2]
       newArr[newArr.length - 1] = obj2
       newArr[newArr.length - 2] = obj1
        menuBarData.value = newArr
        // menuBarData.value = getArrValue(val)
    }
}, { immediate: true })
//菜单被点击
const menuBarChange = ({ code }) => {
    menuBarKey.value = code
    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 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 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 isReminderShow = ref(false)
const isReminderText = ref('')
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: 'home-index' })
}

//关闭普通公告
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()
})

// / 动态加载样式
const loadStyles = () => {
  const styleElement = document.createElement('style')
  styleElement.type = 'text/css'
  const styleContent = isYunNanProject.value
    ? import('./test-yn/index-yn.scss')
    : import('./index.scss')
  styleElement.textContent = styleContent
  document.head.appendChild(styleElement)
  return styleElement
}
let currentStyle = null

// 监听项目类型变化，动态切换样式
watch(() => isYunNanProject.value, () => {
  if (currentStyle) {
    document.head.removeChild(currentStyle)
  }
  currentStyle = loadStyles()
}, { immediate: true })
</script>

