<template>
    <el-container class="hc-layout-box">
        <div class="hc-app-bg-box" v-show="AppTheme === 'dark'">
            <img :src="appViewBg" alt="" crossOrigin="anonymous">
        </div>
        <el-aside :width="isCollapse?'100px':'250px'" class="hc-aside-box" :class="[isCollapse?'is-collapse':'']" v-show="MenuBarKey !== 'home-index'">
            <div class="hc-aside-logo-box" @click="logoClick">
                <img :src="appLogoIcon" alt="" id="logo-icon">
                <img :src="appLogoName" alt="" id="logo-name" v-if="!isCollapse">
            </div>
            <div class="hc-aside-menu-box">
                <el-scrollbar>
                    <MenuBar :datas="MenuBarData" :cur="MenuBarKey" :collapse="isCollapse" @change="MenuBarChange" :msgCount="msgCount"/>
                </el-scrollbar>
            </div>
            <div class="hc-aside-bar-box">
                <div :class="isCollapse?'':'active'" @click="collapseChange(false)">
                    <HcIcon name="menu-unfold"/>
                </div>
                <div :class="isCollapse?'active':''" @click="collapseChange(true)" v-show="!isCollapse">
                    <HcIcon name="menu-fold"/>
                </div>
            </div>
        </el-aside>
        <el-container class="hc-container-view">
            <el-header class="hc-header-view" v-show="MenuBarKey !== 'home-index'">
                <div class="hc-header-page-name" id="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" v-if="userRoleId !== website.role_id">
                        <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>
                    <div class="hc-header-project-name-box" @click="userProjectClick" v-else>
                        <span class="project-icon">
                            <HcIcon name="arrow-right"/>
                        </span>
                        <span class="project-name">{{projectInfoData?.projectName??'请先选择项目'}}</span>
                    </div>
                    <HelpInfoBar></HelpInfoBar>
                    <ConfigBar></ConfigBar>
                    <UserInfoBar></UserInfoBar>
                </div>
            </el-header>
            <el-main class="hc-main-box" id="hc-main-box" :class="MenuBarKey">
                <router-view v-slot="{ Component }" v-if="reloadRouter">
                    <transition name="fade-transform">
                        <keep-alive include="ProductList">
                            <component :is="Component" :msgCount="msgCount" :msgChange="msgChange"/>
                        </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 TopMenuBar from "./modules/TopMenuBar.vue"
import HelpInfoBar from "./modules/HelpInfoBar.vue"
import UserInfoBar from "./modules/UserInfoBar.vue"
import ConfigBar from "./modules/ConfigBar.vue"
import {initButtons,initProjectContract} from "~sto/app";
import website from '~src/config/index'
import appViewBg from "~src/assets/view/bg.png";
import {setImageColorStyle} from "js-fast-way";
import {setAppName} from "~uti/tools";

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

//系统信息
const appTitle = ref(useAppState.getTitle)
const appLogoIcon = ref(useAppState.getLogoIcon)
const appLogoName = ref(useAppState.getLogoName)

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

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

//顶部菜单数据和相关处理
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 userRoleId = ref(useAppState.getRoleId);
const projectInfoData = ref(useAppState.getProjectInfo);

//项目合同段
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()
    if (userRoleId.value !== website.role_id) {
        const info = useAppState.getProjectContract || []
        projectContractData(info);
    }
    setIsCollapse(RoutesName.value)
    useAppState.barMenuName = BarMenuTitle
    setInitSocket()
    setLogoImageColor()
    setLogoNameColor(useAppState.getTheme)
})

//监听
watch(() => [
    useAppState.getProjectContract,
    useAppState.getMenus,
    useAppState.getTheme,
    useAppState.getColor,
    useRoutes?.name,
    useRoutes?.meta?.title,
    useAppState.getCollapse,
    useAppState.getProjectInfo,
], ([projectContractArr, userMenus, theme, ColorVal, RouteName, RouteTitle, collapse, projectInfo]) => {
    MenuBarData.value = userMenus
    AppColor.value = ColorVal
    AppTheme.value = theme
    RoutesName.value = RouteName ?? 'home-index'
    MenuBarKey.value = RouteName ?? 'home-index'
    RoutesTitle.value = RouteTitle ?? ''
    isCollapse.value = collapse
    setIsCollapse(RoutesName.value)
    if (userRoleId.value !== website.role_id) {
        projectContractData(projectContractArr || []);
    } else {
        projectInfoData.value = projectInfo
    }
    useAppState.barMenuName = RouteTitle ?? ''
    setAppName(appTitle.value)
    setLogoNameColor(theme)
})

//监听
watch(() => [
    useAppState.getTitle,
    useAppState.getLogoIcon,
    useAppState.getLogoName,
    useAppState.getColor,
], ([Title, LogoIcon, LogoName, ColorVal]) => {
    appTitle.value = Title
    appLogoIcon.value = LogoIcon
    appLogoName.value = LogoName
    AppColor.value = ColorVal
    setLogoImageColor()
})

//设置Logo图片颜色
const setLogoImageColor = () => {
    setImageColorStyle('logo-icon', AppColor.value?.color)
}

//设置Logo图片颜色
const setLogoNameColor = (theme) => {
    if (theme === 'dark') {
        setImageColorStyle('logo-name', '#ffffff')
    } else {
        setImageColorStyle('logo-name', '#000000')
    }
}

//设置折叠
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)
        } else {
            projectValue.value = String(contractId)
            projectInfo.value = UserProjectInfo
            contractInfo.value = UserContractInfo
        }
    } 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('切换了项目，数据更新中');
    //刷新路由
    reloadRouter.value = false
    nextTick(()=>{
        reloadRouter.value = true
    })
}

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

//首页
const logoClick = () => {
    router.push({
        name: useAppState.homeUrl
    });
}

//项目档案汇总
const userProjectClick = () => {
    router.push({path: '/user/project'});
}
const msgCount = ref({
})
const msgChange=ref(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 = data
                console.log(data,'消息信息');
                msgChange.value++

            }
        };
        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;
            }
        }
    }
}
</style>
