<template>
    <el-container class="hc-layout-box">
        <div class="hc-layout-bg-box" v-show="MenuBarKey === 'home-index'">
            <img :src="HomeTheme.bg" alt="" id="imagebox" v-if="HomeTheme.bg" crossOrigin="anonymous">
        </div>
        <el-aside :width="isCollapse?'120px':'250px'" class="hc-aside-box" :class="[isCollapse?'collapse':'', MenuBarKey]">
            <div class="hc-aside-logo-box" @click="logoClick">
                <img class="logo-img" :src="getAssetsHomeFile(`${AppColor.name}.png`)" alt="">
                <img class="logo-img-1" :src="MenuBarKey === 'home-index' ? NameWhite : NameDark" alt="" v-show="!isCollapse">
            </div>
            <div class="hc-aside-menu-box">
                <el-scrollbar>
                    <MenuBar :datas="MenuBarData" :cur="MenuBarKey" :collapse="isCollapse" @change="MenuBarChange"/>
                </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" :class="MenuBarKey === 'home-index'?'home':''">
            <el-header class="hc-header-view">
                <div class="hc-header-page-name">
                    {{RoutesTitle}}
                    <input multiple type="file" id="file" @change="handleChange" v-if="userInfo?.user_id == '1541381503819694081'">
                </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 class="hc-main-box" id="hc-main-box">
                <router-view v-slot="{ Component }" v-if="reloadRouter">
                    <transition name="fade-transform">
                        <keep-alive include="ProductList">
                            <component :is="Component" />
                        </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 {initButtons,initProjectContract} from "~sto/app";
import NameDark from "~src/assets/logo/name-dark.png";
import NameWhite from "~src/assets/logo/name-white.png";

//初始组合式
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);
    setIsCollapse(RoutesName.value)
})

//监听
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 || []);
})

//设置折叠
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});
}

// 获取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上传的图片数据;
    let img = new Image();
    let url = window.URL.createObjectURL(file); // 得到bolb对象路径，可当成普通的文件路径一样使用，赋值给src;
    document.getElementById("imagebox").src = url;
}

//首页
const logoClick = () => {
    router.push({name: 'home-index'});
}
</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>
