<template>
    <el-container class="hc-layout-box">
        <div v-show="MenuBarKey === 'home-index'" class="hc-layout-bg-box">
            <img v-if="HomeTheme.bg" id="imagebox" :src="HomeTheme.bg" alt="" crossOrigin="anonymous">
        </div>
        <el-aside :class="[isCollapse?'collapse':'', MenuBarKey]" :width="isCollapse?'90px':'250px'"
                  class="hc-aside-box">
            <div class="hc-aside-logo-box" @click="logoClick">
                <img :src="getAssetsHomeFile(`${AppColor.name}.png`)" alt="" class="logo-img">
                <img v-if="!isCollapse" :src="MenuBarKey === 'home-index' ? NameWhite : NameDark" alt=""
                     class="logo-img-1 white">
                <img v-if="!isCollapse" :src="NameWhite" alt="" class="logo-img-1 dark">
            </div>
            <div class="hc-aside-menu-box">
                <el-scrollbar>
                    <MenuBar :collapse="isCollapse" :cur="MenuBarKey" :datas="MenuBarData" :msgCount="msgCount"
                             @change="MenuBarChange"/>
                </el-scrollbar>
            </div>
            <div class="hc-aside-bar-box">
                <div :class="isCollapse?'':'active'" @click="collapseChange(false)">
                    <HcIcon name="menu-unfold"/>
                </div>
                <div v-show="!isCollapse" :class="isCollapse?'active':''" @click="collapseChange(true)">
                    <HcIcon name="menu-fold"/>
                </div>
            </div>
        </el-aside>
        <el-container :class="MenuBarKey === 'home-index'?'home':''" class="hc-container-view">
            <el-header class="hc-header-view">
                <div id="hc-header-page-name" class="hc-header-page-name">
                    {{ RoutesTitle }}
                </div>
                <div class="hc-header-top-menu-bar">
                    <TopMenuBar/>
                </div>
                <div class="hc-header-content">
                    <div class="hc-header-cascader-box">
                        <div class="project-name-box">{{ projectInfo.projectAlias }} / {{ contractInfo.name }}</div>
                        <el-cascader ref="ElCascaderRef" v-model="projectValue" :options="projectContract"
                                     :props="projectProps" placeholder="请选择项目" @change="projectContractChange"/>
                    </div>
                    <HelpInfoBar></HelpInfoBar>
                    <ConfigBar></ConfigBar>
                    <UserInfoBar></UserInfoBar>
                </div>
            </el-header>
            <el-main id="hc-main-box" class="hc-main-box">
                <router-view v-if="reloadRouter" v-slot="{ Component }">
                    <transition name="fade-transform">
                        <keep-alive :max="10" exclude="home,home-index,home-config">
                            <component :is="Component" :msgCount="msgCount"/>
                        </keep-alive>
                    </transition>
                </router-view>
            </el-main>
        </el-container>
    </el-container>
</template>

<script setup>
import {onMounted, ref, nextTick, watch} from "vue";
import {useRouter, useRoute} from 'vue-router'
import {useAppStore} from "~src/store";
import MenuBar from "./modules/MenuBar.vue"
import HelpInfoBar from "./modules/HelpInfoBar.vue"
import UserInfoBar from "./modules/UserInfoBar.vue"
import ConfigBar from "./modules/ConfigBar.vue"
import TopMenuBar from "./modules/TopMenuBar.vue"
import {initButtons, initProjectContract} from "~sto/app";
import NameDark from "~src/assets/logo/name-dark.png";
import NameWhite from "~src/assets/logo/name-white.png";
import website from '~src/config/index'

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

//路由参数
const routerQuery = useRoutes?.query;
const reloadRouter = ref(true)
const BarMenuKey = useRoutes?.name ?? 'home-index';
const BarMenuTitle = useRoutes?.meta?.title ?? '';

//主题和色调变量
const HomeTheme = ref(useAppState.getHomeTheme);
const AppColor = ref(useAppState.getColor);

//顶部菜单数据和相关处理
const MenuBarKey = ref(BarMenuKey);
const RoutesName = ref(BarMenuKey);
const RoutesTitle = ref(BarMenuTitle);
const MenuBarData = ref(useAppState.getMenus)
const isCollapse = ref(useAppState.getCollapse)
const userInfo = ref(useAppState.getUserInfo);

//项目合同段
const projectInfo = ref({});
const contractInfo = ref({});
const projectContract = ref([])
const projectValue = ref(null);
const projectProps = ref({
    value: 'id',
    label: 'projectAlias',
    children: 'contractInfoList',
})

//渲染完成
onMounted(() => {
    initButtons()
    initProjectContract()
    const info = useAppState.getProjectContract || []
    projectContractData(info);
    useAppState.barMenuName = BarMenuTitle
    setIsCollapse(RoutesName.value)
    setInitSocket()
})

//监听
watch(() => [
    useAppState.getProjectContract,
    useAppState.getMenus,
    useAppState.getHomeTheme,
    useAppState.getColor,
    useRoutes?.name,
    useRoutes?.meta?.title,
    useAppState.getCollapse,
], ([projectContractArr, userMenus, theme, ColorVal, RouteName, RouteTitle, collapse]) => {
    MenuBarData.value = userMenus
    HomeTheme.value = theme
    AppColor.value = ColorVal
    RoutesName.value = RouteName ?? 'home-index'
    MenuBarKey.value = RouteName ?? 'home-index'
    RoutesTitle.value = RouteTitle ?? ''
    isCollapse.value = collapse
    setIsCollapse(RoutesName.value)
    projectContractData(projectContractArr || []);
    useAppState.barMenuName = RouteTitle ?? ''
})

//设置折叠
const setIsCollapse = (key) => {
    if (key === 'data-fill-wbs') {
        isCollapse.value = true
        useAppState.setCollapse(true)
    }
}

//是否折叠
const collapseChange = (bool) => {
    isCollapse.value = bool
    useAppState.setCollapse(bool)
}

//处理项目合同段数据
const projectContractData = (projectContractData) => {
    if (projectContractData.length > 0) {
        //处理别名
        projectContractData.forEach(item => {
            let contractArr = item['contractInfoList'] || []
            contractArr.forEach(items => {
                items['projectAlias'] = items['name']
            })
        })
        //处理其他数据
        projectContract.value = projectContractData
        const projectId = useAppState.getProjectId     //项目ID
        const contractId = useAppState.getContractId   //合同段ID
        const UserProjectInfo = useAppState.getProjectInfo
        const UserContractInfo = useAppState.getContractInfo
        //查询缓存的选中ID是否存在
        const pid = projectContractData.findIndex(item => Number(item.id) === Number(projectId))
        const contractList = projectContractData[pid]?.contractInfoList || []
        const cid = contractList.findIndex(item => Number(item.id) === Number(contractId))
        //如果缓存的选中ID不存在
        if (cid === -1) {
            //取项目数组中的第一个数据
            let letProjectInfo = projectContractData[0];
            let contractInfoList = letProjectInfo?.contractInfoList || []
            let letContractInfo = contractInfoList[0] || {};
            projectValue.value = letContractInfo?.id
            projectInfo.value = letProjectInfo
            contractInfo.value = letContractInfo
            //设置缓存
            useAppState.setProjectInfo(letProjectInfo)
            useAppState.setContractInfo(letContractInfo)
            useAppState.setProjectId(letProjectInfo?.id)
            useAppState.setContractId(letContractInfo?.id)
            //发送消息
            socketSend(letProjectInfo?.id + ',' + letContractInfo?.id)
        } else {
            projectValue.value = String(contractId)
            projectInfo.value = UserProjectInfo
            contractInfo.value = UserContractInfo
            //发送消息
            socketSend(projectId + ',' + contractId)
        }
    } else {
        projectContract.value = []
        projectValue.value = null
        projectInfo.value = {}
        contractInfo.value = {}
    }
}

//项目被选择
const ElCascaderRef = ref(null)
const projectContractChange = (val) => {
    const Nodes = ElCascaderRef.value.getCheckedNodes();
    const UserProjectInfo = Nodes[0].parent.data;
    const UserContractInfo = Nodes[0].data;
    //缓存项目数据
    useAppState.setProjectId(val[0])
    useAppState.setContractId(val[1])
    useAppState.setProjectInfo(UserProjectInfo)
    useAppState.setContractInfo(UserContractInfo)
    //更改界面更新
    projectInfo.value = UserProjectInfo
    contractInfo.value = UserContractInfo
    window.$message?.info('切换了项目，数据更新中');
    //发送消息
    socketSend(val[0] + ',' + val[1])
    //刷新路由
    reloadRouter.value = false
    nextTick(() => {
        reloadRouter.value = true
    })
}

//菜单被点击
const MenuBarChange = (item) => {
    MenuBarKey.value = item?.code;
    setIsCollapse(item?.code)
    router.push({name: item?.code});
}

// 获取assets静态资源
const getAssetsHomeFile = (url) => {
    const path = `../assets/icon/${url}`;
    const modules = import.meta.globEager("../assets/icon/*");
    return modules[path].default;
}

const handleChange = () => {
    let file = document.getElementById("file").files[0]; // 获取input上传的图片数据;
    const url = window.URL.createObjectURL(file); // 得到bolb对象路径，可当成普通的文件路径一样使用，赋值给src;
    document.getElementById("imagebox").src = url;
}

//首页
const logoClick = () => {
    router.push({name: 'home-index'});
}

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

//推送系统
let socket;
const setInitSocket = () => {
    const user_id = userInfo.value.user_id;
    socket = new WebSocket(website.socket + user_id);
    try {
        socket.onopen = function (evt) {
            console.log('websocket链接成功');
        };
        socket.onclose = function (evt) {
            console.log('websocket连接已断开')
        };
        socket.onmessage = function ({data}) {
            if (data) {
                msgCount.value = JSON.parse(data)
            }
            console.log(data, '消息信息')
        };
        socket.onerror = function ({data}) {
            console.log('发生错误:', data)
        };
    } catch {
    }
}

//发送消息
const socketSend = (msg) => {
    try {
        if (socket) {
            socket.send(msg);
        } else {
            setTimeout(() => {
                socket.send(msg);
            }, 1000)
        }
    } catch {
    }
}
</script>

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

<style lang="scss">
.hc-layout-box .hc-container-view {
    .hc-header-view .hc-header-content .hc-header-cascader-box {
        .el-cascader {
            width: 100%;
            top: -10px;
        }
        .el-cascader .el-input .el-input__wrapper {
            padding: 4px 15px;
            border: 1px solid #00000000;
            border-radius: 100px;
            background: #f1f5f8;
            color: #202532;
            box-shadow: var(--hc-shadow);
            .el-input__inner, .el-input__suffix {
                color: #202532;
            }
        }
        .el-cascader .el-input.is-focus .el-input__wrapper {
            box-shadow: 4px 4px 8px 0 rgba(54, 92, 167, 0.15), -4px -4px 8px 0px #ffffff;
        }
        .el-cascader .el-input .icon-arrow-down {
            font-size: 18px;
            font-weight: bold;
        }
    }
    &.home {
        .hc-header-view .hc-header-content .hc-header-cascader-box {
            .el-cascader .el-input .el-input__wrapper {
                background-color: #00000000;
                border: 1px solid white;
                box-shadow: initial;
                .el-input__inner, .el-input__suffix {
                    color: white;
                }
            }
            .el-cascader .el-input.is-focus .el-input__wrapper {
                box-shadow: initial;
            }
        }
        .hc-header-view .hc-header-top-menu-bar {
            padding-left: 0;
            .hc-top-menu-bar .bar-menu-content .bar-menu-btn {
                background: rgba(255,255,255, .2);
                border-color: rgba(255,255,255, .2);
                color: rgba(255,255,255, .7);
                backdrop-filter: blur(20px);
                -webkit-backdrop-filter: blur(20px);
                &:hover:not([class*='cur']) {
                    background: var(--el-color-primary-light-9);
                    color: #838791;
                }
                &:active:not([class*='cur']) {
                    background: var(--el-color-primary-light-8);
                    color: #838791;
                }
            }
        }
    }
}

</style>
