<template>
    <div class="menu-container" v-if="$route.name === 'business'">
        <div class="menu-topic">
            <div v-for="(item, index) in menuList" :key="index" @click="handelGoFirstMenu(item, index)"
                class="menu-topic-item">
                <div class="menu-topic-icon-bg">
                    <div :class="`menu-topic-icon menu-topic-icon-${index + 1}`"></div>
                </div>
                <div class="menu-topic-name">{{ item.name }}</div>
            </div>
        </div>
    </div>
    <div v-else-if="subMenus && subMenus.length > 1" class="subject-container">
        <div :class="[(currentAlias === item.url || index == Numberindex) ? 'subjectItem-active' : '', 'subjectItem']"
            v-for="(item, index) in subMenus" @mouseenter.stop="enter(item.name, index)" @mouseleave.stop="Leave"
            @click="handelGoHtml(item, index)" :key="index">
            <span>{{ item.name }}</span>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { computed, onBeforeMount, reactive, ref, watchEffect } from "vue";
import { useRoute } from "vue-router";
import {
    generateKey,
    getMenuLists,
} from "@/api/operation";
import { routes } from "@/router/index";
import router from "@/router";
import { useStore } from "vuex";
import { key } from "@/store";
const store = useStore(key);
const userCode = computed(() => store.state.auth?.userInfo.userCode);
const secondRouterNameList = [
    "curingManageCopy",
    "curingBusinessCopy",
    "electromechanicalMange",
    "electromechanicalOverview",
];
const menuList = ref(null); // 一级菜单
const newMenuList = ref(null); // 二级菜单
const display = ref(false);
const Numberindex = ref(null); // 一级菜单active
const towMenuListIndex = ref(""); // 二级菜单active


const subMenus = ref(null); // 二级菜单
const currentAlias = ref('')
const route = useRoute();

// onBeforeMount(() => {
//     getMenuList();
// });





// //一级移入
const enter = async (name: any, item: any) => {
    Numberindex.value = item;
    towMenuListIndex.value = "";
    display.value = true;
};

const Leave = async (event) => {
    Numberindex.value = null;
    towMenuListIndex.value = "";
    display.value = false;
};


const handelGoFirstMenu = (item: any, index: any) => {
    if (!item) {
        return;
    } else {
        subMenus.value = item.children || []
        if (item.code === 'ZHFW') {
            const zhfw = subMenus.value.filter((menu) => menu.code === 'JYGK' || menu.code === 'GS')
            zhfw.forEach((menu) => {
                if (menu.code === 'JYGK') {
                    menu.url.indexOf('/') > -1 ? null : menu.url = `/${menu.url}`
                }
            })
            subMenus.value = zhfw
        } else if (item.code === 'ZHYH') {
            getYHMenu()
        } else if (item.code === 'ZHYX') {
            const targetIndex = subMenus.value.findIndex((menu) => menu.code === "LDJSC")
            // 如果找到了目标项
            if (targetIndex !== -1) {
                const target = subMenus.value[targetIndex]
                // 从数组中移除目标项
                subMenus.value.splice(targetIndex, 1);
                // 将目标项添加到数组的开头

                subMenus.value.unshift(target);
            }
        }
        if (subMenus.value && subMenus.value.length) {
            router.push(subMenus.value[0].url || subMenus.value[0].path);
            currentAlias.value = subMenus.value[0].url;
        }

    }
}

const getYHMenu = () => {
    const root = routes.find((e) => e.path === "/");
    let newroute: any[] = [];

    if (root && root.children?.length > 0) {
        root.children?.forEach((ele) => {
            if (secondRouterNameList.includes(ele.name)) {
                let newroute1 = { ...ele }
                newroute1.url = ele.path
                newroute1.code = ele.name
                newroute1.name = ele.title
                newroute.push(newroute1);
            }
        });
    }
    subMenus.value = [...newroute, {
        name: '桥梁监测',
        code: 'JKJC',
    }]
}

const handelGoHtml = async (item: any, index: any) => {
    if (!item) {
        return;
    }
    const { name, code, url, externalLink } = item;
    towMenuListIndex.value = index;

    const linkCodes = ['BI', 'QXGL', "YHYWXT", "JDYWXT", "SFYWXT", "GS", "YHCY", "JKJC", "AQSC"]
    if (linkCodes.includes(code)) {
        generateKey().then((res) => {
            // 机电系统
            // if (name == "机电系统") { window.open(`http://183.64.175.153:8891/?tokenKey=${res.data}#/m-datav/management`) }
            // BI平台
            if (code == "BI") {
                window.open(
                    `http://183.64.175.153:15180/view/user/sso.do?tokenKey=${res.data}`
                );
            }
            // 权限管理
            if (code === "QXGL") {
                window.open(`http://183.64.175.153:28880/#/QXGL`);
            }
            // 养护业务系统
            if (code === "YHYWXT") {
                window.open(
                    ` http://183.64.175.153:8888/fvue/login?tokenKey=${res.data}`
                );
            }
            // 机电业务系统
            if (code === "JDYWXT") {
                window.open(
                    `http://183.64.175.153:8891/?tokenKey=${res.data}#/personal-center/progress-sign`
                );
            }
            // 收费业务系统
            if (code === "SFYWXT") {
                window.open(
                    `http://183.64.175.153:6005/platform.html?tokenKey=${res.data}`
                );
            }
            // // 巡查救援
            // if (code === "GIS") {
            //     window.open(`http://183.64.175.153:28882/#/?tokenKey=${res.data}`);
            // }
            // 服务区
            if (code === "GS") {
                window.open(
                    `http://183.64.175.153:21080/servicearea/index.html#/cqHome?tokenKey=${res.data}`
                );
            }
            // 养护业务系统
            if (code === "YHCY") {
                window.open(
                    // `http://171.221.208.77:9004/#/cqjlLogin?tokenKey=${res.data}`
                    `http://111.9.41.17:9004/#/cqjlLogin?tokenKey=${res.data}`
                );
            }
            // 桥梁监测系统
            if (code === "JKJC") {
                window.open(
                    `http://183.64.175.153:8888/fvue/loginjkjc?tokenKey=${res.data}`
                );
            }

            // 安全生产驾驶舱
            if (code == "AQSC") {
                window.open(`${externalLink}?tokenKey=${res.data}`);
            }
        });
    } else {
        router.push(url);
        setTimeout(() => {
            display.value = false;
        }, 1000);
    }
};

const tonewPath = async (val: any, index: number) => {
    Numberindex.value = null;
    Numberindex.value = index;
    towMenuListIndex.value = "";
    menuList?.value.forEach((item) => {
        if (item.name == val) {
            newMenuList.value = { ...item.children };
        }
    });

    display.value = true;
};
const getMenuList = () => {
    if (menuList.value && menuList.value.length) {
        getSubMenu()
    } else {
        getMenuLists()
            .then((res) => {
                const menus = updateMenuUrl(res?.dataList || [], "GIS", '/patrolAndRescue')  // 巡查救援的url在权限管理中赋值不生效所以手动修改其url
                menuList.value = menus
                getSubMenu()
            })
            .catch(() => { });
    }
};

const updateMenuUrl = (data: { code: string, url: string }[], code: string, url: string): { code: string, url: string }[] => {
    // 先尝试找到并更新第一个匹配的项
    const foundIndex = data.findIndex((item) => item.code === code);
    if (foundIndex !== -1) {
        data[foundIndex] = {
            ...data[foundIndex],
            url
        };
        // 找到后直接返回，不继续遍历
        return data;
    }

    // 如果没有找到匹配的项，则继续遍历子项
    return data.map((item: any) => {
        if (item.children && item.children.length > 0) {
            return {
                ...item,
                children: updateMenuUrl(item.children, code, url)
            };
        }
        return item;
    });
};

const getSubMenu = () => {
    if (route.name === "business") {
        subMenus.value = [];
    } else if (secondRouterNameList.includes(route.name)) {
        getYHMenu()
    } else {
        const isFind = menuList.value.find((item) => {
            if (item.children) {
                return item.children.some((child) => {
                    return child.url === route.path || child.url === route.path.split('/')[1];
                })
            } else {
                return false
            }
        })
        if (isFind) {
            if (isFind.code === 'ZHFW') {
                const zhfw = isFind.children.filter((menu) => menu.code === 'JYGK' || menu.code === 'GS')
                zhfw.forEach((menu) => {
                    if (menu.code === 'JYGK') {
                        menu.url.indexOf('/') > -1 ? null : menu.url = `/${menu.url}`
                    }
                })
                subMenus.value = zhfw
            } else if (isFind.code === 'ZHYX') {
                const targetIndex = isFind.children.findIndex((menu) => menu.code === "LDJSC")
                // 如果找到了目标项
                if (targetIndex !== -1) {
                    // 从数组中移除目标项
                    const target = isFind.children[targetIndex]
                    isFind.children.splice(targetIndex, 1);
                    // 将目标项添加到数组的开头
                    isFind.children.unshift(target);
                }
                subMenus.value = isFind.children;
            } else {
                subMenus.value = isFind.children;
            }
        } else {
            subMenus.value = [];
        }
    }

}

watchEffect(() => {
    currentAlias.value = route.path;
    getMenuList()
});

</script>

<style lang="scss" scoped>
.menu-container {
    width: 620px;
    height: 60px;
    background: url("@/assets/images/layout/menu/menu-container-bg.png") no-repeat center;
    background-size: 100% 100%;
    margin: 0 auto;
    position: relative;
}

.menu-topic {
    position: absolute;
    width: 100%;
    height: 100%;
    top: -50px;
    left: 0;
    display: flex;
    justify-content: space-around;

}

.menu-topic-item {
    // animation: breath 3s linear infinite alternate;
    width: 80px;
    cursor: pointer;

}

.menu-topic-item:nth-child(2),
.menu-topic-item:nth-child(3) {
    margin-top: -36px;
}

.menu-topic-item:nth-child(2),
.menu-topic-item:nth-child(4) {
    .menu-topic-icon-bg {
        animation: breath 2.8s linear infinite alternate;
    }
}

.menu-topic-icon-bg {
    width: 80px;
    height: 67px;
    background: url("@/assets/images/layout/menu/menu-topic-bg.png") no-repeat center;
    background-size: 100% 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    animation: breath 3s linear 1s infinite alternate;
}

.menu-topic-icon {
    width: 36px;
    height: 36px;
    background-size: 100% 100%;
    margin-top: -30px;
}

@for $i from 1 to 5 {
    .menu-topic-icon-#{$i} {
        background: url("@/assets/images/layout/menu/topic-icon-0#{$i}.png") no-repeat center;
        background-size: 100% 100%;
    }
}

.menu-topic-name {
    width: 80px;
    font-weight: bold;
    font-size: 16px;
    line-height: 19px;
    letter-spacing: 1px;
    margin-top: 5px;
    text-align: center;
    font-style: normal;
    text-transform: none;
    background: linear-gradient(0deg, #B2E5FF 0%, #FFFFFF 100%);
    -webkit-text-fill-color: transparent;
    text-shadow: none;
    background-clip: text;
}

.menu-topic-item:hover {
    .menu-topic-icon {
        margin-top: -40px;
    }

    .menu-topic-name {
        font-size: 17px;
    }
}

.subject-container {
    display: flex;
    margin: 0 auto 22px auto;
    justify-content: center;
}

.subjectItem {
    width: 128px;
    height: 46px;
    background: url("@/assets/images/layout/menu/subject-bg.png") no-repeat center;
    background-size: 100% 100%;
    text-align: center;
    line-height: 46px;
    cursor: pointer;

    span {
        font-weight: 400;
        font-size: 18px;
        color: #CCE6FF;
        letter-spacing: 1px;
    }
}

.subjectItem-active {
    line-height: 46px;
    background: url("@/assets/images/layout/menu/subject-bg-active.png") no-repeat center;
    background-size: 100% 100%;

    span {
        font-size: 18px;
        font-weight: bold;
        letter-spacing: 1px;
        text-align: center;
        font-style: normal;
        text-transform: none;
        background: linear-gradient(90deg, #DAFFFF 0%, #00FFFF 100%);
        background-clip: text;
        -webkit-text-fill-color: transparent;
        text-shadow: none;
    }
}

@keyframes breath {
    from {
        transform: translateY(2%) scale(0.96);
    }

    to {
        transform: translateY(-2%) scale(1);
    }
}
</style>
