<template>
    <div
        :class="[
            'aside-menu',
            currentMenuGroupAlias === 'homePage' ||
            customSystemRouter.some((i) => i.path === currentMenuGroupAlias)
                ? 'menu-hide'
                : '',
            longMenu ? 'menu-long' : 'menu-short'
        ]"
    >
        <!--  侧边栏面板  -->
        <div class="sidebar-panel" @mouseleave="sidebarPanelLeave">
            <div class="sidebar-panel-header" @click="panelHeaderClick">
                <el-tooltip
                    placement="right"
                    trigger="hover"
                    :disabled="longMenu"
                    popper-class="menu-popover expand-panel-tooltip"
                >
                    <template v-slot:content>
                        <span>展开面板</span>
                    </template>
                    <el-icon class="show-icon"><Expand /></el-icon>
                </el-tooltip>
                <div class="sidebar-panel-header-right">
                    <div class="header-title" title="服务列表">服务列表</div>
                    <el-icon :class="['arrow-icon', isShowPopupList ? 'arrow-icon-open' : '']"
                        ><CaretRight
                    /></el-icon>
                </div>
            </div>
            <p></p>

            <!--  快捷菜单  -->
            <transition-group name="drag" class="sidebar-collection-service" tag="ul">
                <li
                    :class="[
                        'service-item',
                        item.dragIconPress ? 'service-item-drag' : '',
                        item.isDragEnter ? 'service-item-dragEd' : '',
                        routerPath === item.routerPath ? 'service-item-active' : ''
                    ]"
                    v-for="(item, index) in swiftMenusData"
                    :key="item.id"
                    @click="menuClick(item)"
                    :draggable="item.dragIconPress"
                    @dragstart="dragstart($event, index)"
                    @dragenter="dragenter($event, index, item)"
                    @dragend="dragend($event, index, item)"
                    @dragover="dragover($event, index, item)"
                    @dragleave="dragleave($event, item, index)"
                    @drop="item.isDragEnter = false"
                >
                    <el-tooltip
                        placement="right"
                        trigger="hover"
                        :disabled="longMenu"
                        popper-class="menu-popover expand-panel-tooltip"
                    >
                        <template v-slot:content>
                            <span>{{ item.name }}</span>
                        </template>
                        <div class="service-item-left">
                            <svg-icon
                                icon-style="icon header-icon"
                                :icon-class="item.menuIcon ? item.menuIcon : ''"
                            />
                        </div>
                    </el-tooltip>
                    <div class="service-item-right" :title="item.name">
                        <div class="service-item-title">
                            {{ item.name }}
                        </div>

                        <div class="function-box">
                            <i
                                class="collect-icon"
                                @click.stop="changeCollect(item, index)"
                                title="取消收藏"
                            />
                            <i
                                class="drag-icon"
                                title="拖拽排序"
                                @mousedown="(_) => (item.dragIconPress = true)"
                            />
                        </div>
                    </div>
                </li>
            </transition-group>
        </div>
        <!--  弹出层菜单列表  -->
        <div :class="['service-popup', isShowPopupList ? 'service-popup-show' : '']">
            <service-popup-list
                ref="popupList"
                :swiftMenusData="swiftMenusData"
                :routerPath="routerPath"
                :isShowPopupList="isShowPopupList"
                @close-popup="closeAll"
                @change-collect="(item) => changeCollect(item)"
            />
        </div>
        <!--  遮罩层  -->
        <div
            :class="['aside-menu-modal', isShowPopupList ? 'aside-menu-modal-show' : '']"
            @click="closeAll"
        ></div>
    </div>
</template>
<script lang="ts" setup>
import servicePopupList from './components/ServicePopupList.vue'
import customSystemRouter from '@/router/custom-system-router'
import { getSwiftMenus, removeSwiftMenus, saveSwiftMenu, updateSequence } from '@/api/system/menu'
import { useRoute, useRouter } from 'vue-router'
import { ref, watch, computed } from 'vue'
import { useMenuStore } from '@/stores/menu'
const longMenu = ref(false)
const isShowPopupList = ref(false)

const sidebarPanelLeave = () => {
    if (longMenu.value) return
    longMenu.value = false
}

const panelHeaderClick = () => {
    if (longMenu.value) {
        longMenu.value = false
        isShowPopupList.value = false
    } else {
        longMenu.value = true
        isShowPopupList.value = true
    }
}

const popupList = ref<InstanceType<typeof servicePopupList>>()

const showDirectory = (router: any) => {
    longMenu.value = true
    isShowPopupList.value = true
    if (router && popupList.value) {
        // 可以根据routerPath进行特定操作
        popupList.value.searchMenuDirctory(router)
    }
}

defineExpose({
    showDirectory
})

// 关闭面板和菜单弹层
const closeAll = () => {
    isShowPopupList.value = false
    longMenu.value = false
}

interface SwiftMenuItem {
    id: string | number
    name: string
    routerPath: string
    menuIcon?: string
    swiftId?: string | number
    dragIconPress?: boolean
    isDragEnter?: boolean
    // add other fields as needed
}

const swiftMenusData = ref<SwiftMenuItem[]>([])

const getSwiftMenusData = async (parentMenuPath: string) => {
    const resMenu = (await getSwiftMenus(parentMenuPath)) as SwiftMenuItem[]
    swiftMenusData.value = resMenu.map((i) => ({
        ...i,
        routerPath: i.routerPath.replace('normal', '/platLayout'),
        dragIconPress: false,
        isDragEnter: false
    }))
}

const route = useRoute()
const router = useRouter()
const menuStore = useMenuStore()
const currentMenuGroup = computed(() => menuStore.getCurrentMenuGroup)
const currentMenuGroupAlias = computed(() => menuStore.currentMenuGroupAlias)
const routerPath = computed(() => route.path)

watch(
    () => route.path,
    async (newPath, oldPath) => {
        // 获取一级菜单的别名
        const newCurrentMenu = newPath.split('/')[2] || ''
        const oldCurrentMenu = oldPath?.split('/')[2] || ''
        closeAll()
        if (newCurrentMenu) {
            // 当为初次刷新时或一级菜单切换时请求快捷菜单
            if (!oldCurrentMenu || newCurrentMenu !== oldCurrentMenu) {
                swiftMenusData.value = []
                // 递归菜单数据查询path
                if (currentMenuGroup.value.path)
                    await getSwiftMenusData(currentMenuGroup.value.path)
            }
        }
    },
    { immediate: true }
)
const menuClick = (item: SwiftMenuItem) => {
    closeAll()
    router.push(item.routerPath)
}

const changeCollect = async (item: SwiftMenuItem, changeIndex = undefined) => {
    if (typeof changeIndex === 'undefined') {
        changeIndex = swiftMenusData.value.findIndex((i) => i.alias === item.alias)
    }
    if (changeIndex === -1) {
        swiftMenusData.value.push({
            ...item,
            dragIconPress: false,
            isDragEnter: false
        })
        try {
            const {
                data: { state, value }
            } = await saveSwiftMenu(item.alias)
            if (!state) {
                swiftMenusData.value.splice(
                    swiftMenusData.value.findIndex((i) => i.alias === value),
                    1
                )
            }
        } catch ({ data: { value } }) {
            swiftMenusData.value.splice(
                swiftMenusData.value.findIndex((i) => i.alias === value),
                1
            )
        }
    } else {
        const {
            data: { state }
        } = await removeSwiftMenus(item.alias)
        if (state) swiftMenusData.value.splice(changeIndex, 1)
    }
}

const enterIndex = ref('')
const dragIndex = ref('')
// 拖动开始
const dragstart = (e, index) => {
    enterIndex.value = index
    const img = new Image()
    img.src =
        "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' %3E%3Cpath /%3E%3C/svg%3E"
    e.dataTransfer.setDragImage(img, 0, 0)
}

// 记录移动到哪个盒子
const dragenter = (e, index) => {
    dragIndex.value = index
    e.preventDefault()
}

// 拖拽最终操作
const dragend = async (e, index, item) => {
    item.dragIconPress = false
    if (dragIndex.value !== index) {
        const arr = swiftMenusData.value
        const dragStartItem = arr[index]
        const dragenterItem = arr[dragIndex.value]

        /**
         *  @param {Object} changItem 交换位置的菜单对象
         * */
        const menuTransposition = (changItem) => {
            arr.splice(dragIndex.value, 1, ...arr.splice(index, 1, changItem))
        }
        menuTransposition(dragenterItem)
        try {
            const {
                data: { state }
            } = await updateSequence({
                [dragStartItem.swiftId]: dragIndex.value + 1,
                [dragenterItem.swiftId]: index + 1
            })
            if (!state) menuTransposition(dragStartItem)
        } catch {
            menuTransposition(dragStartItem)
        }
    }
}

// 拖动事件（主要是为了拖动时鼠标光标不变为禁止）
const dragover = (e, index, item) => {
    if (enterIndex.value !== index) item.isDragEnter = true
    e.preventDefault()
}

const dragleave = (e, item, index) => {
    if (enterIndex.value !== index) item.isDragEnter = false
}
</script>

<style lang="scss" scoped>
$font-color: var(--theme-text-primary);
$icon-color: var(--theme-text-primary);
$icon-color-hover: $system-hover-active-text;
$menu-long-width: 250px;

.aside-menu {
    height: 100% !important;
    position: relative;
    transition: width 0.15s;
    width: 0;
    flex-shrink: 0;

    &.menu-long {
        width: $menu-long-width;

        .sidebar-panel {
            .sidebar-panel-header {
                .sidebar-panel-header-right {
                    transition: opacity 0s;
                }
            }

            .sidebar-collection-service {
                .service-item {
                    .service-item-right {
                        transition: opacity 0s;
                    }
                }
            }
        }
    }

    &.menu-short {
        width: 58px;

        .sidebar-panel {
            .sidebar-panel-header {
                .sidebar-panel-header-right {
                    transition: opacity 1s;
                    opacity: 0;
                }
            }

            .sidebar-collection-service {
                .service-item {
                    .service-item-right {
                        transition: opacity 1s;
                        opacity: 0;
                    }
                }
            }
        }
    }

    &.menu-hide {
        width: 0 !important;
        right: 2px;
    }

    .sidebar-panel {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        position: absolute;
        top: 0;
        left: 0;
        overflow: hidden;
        z-index: 999;
        background-color: var(--theme-system-module-1);
        background-image: url('@/assets/img/layout/menu-bg.png');
        background-repeat: no-repeat;
        background-position: 0 35vh;
        background-size: $menu-long-width calc(100% - 30vh);

        .sidebar-panel-header {
            width: $menu-long-width;
            display: flex;
            align-items: center;
            box-sizing: border-box;
            position: relative;
            white-space: nowrap;
            cursor: pointer;
            user-select: none;
            left: 0;
            top: 0;

            .show-icon {
                width: 58px;
                height: 58px;
                text-align: center;
                line-height: 58px;
                font-size: 28px;
                color: var(--theme-text-primary);
            }

            .sidebar-panel-header-right {
                height: 100%;
                display: flex;
                align-items: center;
                justify-content: space-between;
                flex: 1;
                padding-right: 20px;
                opacity: 1;

                .header-title {
                    height: 20px;
                    line-height: 20px;
                    color: var(--theme-text-primary);
                    font-size: 14px;
                    font-family:
                        Microsoft YaHei,
                        serif;
                }

                .arrow-icon {
                    color: $icon-color;
                    font-size: 18px;
                    transition: 0.15s;
                    transform-origin: center;
                    transform: rotateZ(180deg);

                    &.arrow-icon-open {
                        transition: 0.3s;
                        transform-origin: center;
                        transform: rotateZ(0deg);
                    }
                }
            }
        }

        p {
            margin: 0 10px;
            bottom: 0;
            height: 1px;
            background: var(--theme-border-divider);
        }

        .sidebar-collection-service {
            width: $menu-long-width;
            position: relative;
            left: 0;
            top: 0;
            flex: 1;
            overflow-x: hidden;
            overflow-y: auto;

            .drag-move {
                transition: transform 1s;
            }

            &::-webkit-scrollbar {
                display: none;
            }

            .service-item {
                width: 100%;
                display: flex;
                align-items: center;
                transition: all 0.3s;
                cursor: pointer;
                user-select: none;
                border-bottom: 1px solid transparent;

                @mixin hover-dragEd {
                    background: var(--theme-box-color-3);

                    .service-item-left {
                        svg {
                            color: $icon-color-hover;
                        }
                    }

                    .service-item-right {
                        .service-item-title {
                            color: $icon-color-hover;
                        }
                    }
                }

                &:hover {
                    @include hover-dragEd;

                    .service-item-right {
                        .function-box {
                            opacity: 1;
                        }
                    }
                }

                &.service-item-active {
                    @include hover-dragEd;
                }

                &.service-item-drag {
                    opacity: 0.7;
                }

                &.service-item-dragEd {
                    @include hover-dragEd;
                    border-color: $icon-color-hover;
                }

                .service-item-left {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    width: 58px;
                    height: 52px;
                    flex-shrink: 0;

                    svg {
                        font-size: 28px;
                        color: $icon-color;
                        transition: all 0.3s;
                    }
                }

                .service-item-right {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    flex: 1;
                    padding-right: 10px;

                    .service-item-title {
                        width: 140px;
                        height: 20px;
                        line-height: 20px;
                        color: $font-color;
                        font-size: 14px;
                        font-family:
                            Microsoft YaHei,
                            serif;
                        transition: all 0.3s;
                        text-overflow: ellipsis;
                        overflow: hidden;
                        word-break: break-all;
                        white-space: nowrap;
                    }

                    .function-box {
                        opacity: 0;
                        transition: all 0.1s;
                        display: flex;
                        align-items: center;
                        column-gap: 2px;

                        .collect-icon {
                            display: inline-block;
                            width: 20px;
                            height: 20px;
                            background-image: url('@/assets/img/layout/collect2.png');
                            background-repeat: no-repeat;
                            background-position: 50% 50%;
                            background-size: 75% 75%;
                            transition: all 0.2s;

                            &:hover {
                                background: url('@/assets/img/layout/collect1.png') no-repeat 50%
                                    50%;
                                background-size: 75% 75%;
                            }
                        }

                        .drag-icon {
                            display: inline-block;
                            width: 20px;
                            height: 20px;
                            background: url('@/assets/img/layout/drag-icon.png') no-repeat 50% 50%;
                            background-size: 85% 85%;
                            transition: all 0.2s;
                            cursor: move;
                        }
                    }
                }
            }
        }
    }

    .service-popup {
        position: absolute;
        width: 1000px;
        top: 0;
        height: 100%;
        background: #fff;
        box-shadow: 4px 0 10px 0 rgba(53, 152, 220, 0.1);
        z-index: 2001;
        left: -1000px;
        transition: all 0.15s;

        &.service-popup-show {
            left: $menu-long-width;
            transition: all 0.3s;
        }

        &::before {
            content: '';
            background-color: #1a3d5c;
            width: 1px;
            height: 100%;
            position: absolute;
            left: 0;
            top: 0;
        }

        &::after {
            content: '';
            background-color: #1e4266;
            width: 1px;
            height: 100%;
            position: absolute;
            right: 0;
            top: 0;
        }
    }

    .aside-menu-modal {
        width: 100vw;
        height: 100%;
        margin-left: $menu-long-width;
        position: absolute;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 5;
        opacity: 0;
        transition: opacity 0.2s;
        pointer-events: none;

        &.aside-menu-modal-show {
            opacity: 1;
            pointer-events: auto;
        }
    }
}
</style>
