<template>
    <el-container v-loading="isAppLoadings" class="hc-layout-box" :class="[!isNullES(isLayout) && isLayout === 'no' ? 'is-no-layout' : '']">
        <el-header class="hc-layout-header">
            <div 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 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 @load="topMenuLoad" @change="topMenuChange" />
            </div>
            <div class="header-content-bar">
                <HcCascader @send="cascaderSend" @change="cascaderChange" />
                <hc-upload-bar />
                <HelpInfoBar />
                <ConfigBar />
                <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>
    </el-container>
</template>

<script setup>
import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { 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'

//初始组合式
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('')

//渲染完成
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 (!isNullES(data)) {
        menuBarData.value = data
        isAsideMenu.value = 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)
    })
}

//长链接消息
const annRefs = ref([])
const annUpdateRef = 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.value = await HcAnnouncement({ type: 'update', data: data, time: 'xxx年xx月xx日 xx:xx:xx' })
    } else if (type === 'msgSystemMsg') {
        //内容为空时，代表公告已经取消，由于前面已经关闭，所以不再创建
        if (isNullES(data)) {
            closeAnnFun()
            return
        }
        await nextTick()
        //普通公告，追加公告
        const ref = await HcAnnouncement({ type: 'system', data: data })
        annRefs.value.push(ref)
    }
}

// 项目切换
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 (!annUpdateRef.value) {
        annUpdateRef.value?.close()
        annUpdateRef.value = null
    }
}

//页面卸载
onUnmounted(() => {
    if (!isNullES(socket)) socket.close()
    closeAnnFun()
    closeAnnUpdate()
})
</script>

<style lang="scss">
@import "./index.scss";
</style>
