<template>
    <!-- 左侧分类导航 -->
    <aside class="category-sidebar">
        <ul class="category-list">
            <li class="category-item" style="color: #E02020;"><img src="../img/hot.svg" style="margin-right: 10px;"
                    alt=""> 热门推荐 / 活动促销</li>
            <li v-for="category in categories" :key="category.id" class="category-item"
                @mouseenter="showProductList(category)" @mouseleave="hideProductList">
                <span class="category-icon"> <img style="width: 24px;height: 24px;" :src="category.icon" alt=""> </span>
                <span class="category-name">{{ category.first_level_name }}</span>
                <span style="display: flex;margin-left: 0px;padding-left: 0px;">|</span>
                <div class="menu-item">
                    <span v-for="(secondary, index) in category.secondaryClassification" :key="secondary.id">
                        {{ secondary.second_level_name }}{{ index < category.secondaryClassification.length - 1 ? ' / '
                            : '' }} </span>
                </div>
            </li>
        </ul>
        <transition name="slide-fade">
            <!-- v-if="currentCategory" -->
            <div v-loading="loading" element-loading-text="加载中..." element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(255, 255, 255, 0.8)" class="rightBox" v-if="currentCategory"
                @mouseenter="keepProductList" @mouseleave="hideProductList">
                <div class="rightBox-content">
                    <!-- 二级菜单标题 -->
                    <div class="secondary-menu">
                        <div v-for="secondary in currentCategory.secondaryClassification" :key="secondary.id"
                            class="secondary-item" :class="{ active: selectedSecondary === secondary }"
                            @mouseenter="selectSecondary(secondary)">
                            {{ secondary.second_level_name }}
                        </div>
                    </div>

                    <!-- 三级和四级菜单内容 -->
                    <div class="menu-content">
                        <!-- 如果有选中的二级菜单且有三级菜单，显示京东风格的分类区域 -->
                        <div v-if="selectedSecondary && selectedSecondary.thirdClassification && selectedSecondary.thirdClassification.length > 0"
                            class="jd-style-menu">
                            <div v-for="third in selectedSecondary.thirdClassification" :key="third.id"
                                class="category-section">
                                <!-- 只有当有四级菜单时才显示三级菜单标题 -->
                                <div v-if="third.product_list && third.product_list.length > 0" class="section-header">
                                    <span class="section-title">{{ third.third_level_name }}</span>
                                    <span class="section-arrow">></span>
                                </div>
                                <div class="section-content">
                                    <!-- 如果有四级菜单（product_list），直接显示所有四级菜单项 -->
                                    <div v-if="third.product_list && third.product_list.length > 0"
                                        class="product-grid">
                                        <div @click="goSearch(product)" v-for="(product, index) in third.product_list"
                                            :key="product.id"
                                            class="product-tag">
                                            {{ product.first_level_name }}
                                        </div>
                                    </div>
                                    <!-- 如果没有四级菜单，将三级菜单项视为四级菜单项显示 -->
                                    <div v-else class="product-grid">
                                        <div @click="openTalk" class="product-tag ">
                                            {{ third.third_level_name }}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 如果没有三级菜单，显示二级菜单项 -->
                        <div v-else-if="selectedSecondary" class="jd-style-menu">
                            <div class="category-section">
                                <div class="section-header">
                                    <span class="section-title">{{ selectedSecondary.second_level_name }}</span>
                                    <span class="section-arrow">></span>
                                </div>
                                <div class="section-content">
                                    <div class="product-grid">
                                        <div class="product-tag hot-tag">
                                            {{ selectedSecondary.second_level_name }}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 默认：显示所有二级菜单项 -->
                        <div v-else class="jd-style-menu">
                            <div v-for="secondary in currentCategory.secondaryClassification" :key="secondary.id"
                                class="category-section">
                                <div class="section-header">
                                    <span class="section-title">{{ secondary.second_level_name }}</span>
                                    <span class="section-arrow">></span>
                                </div>
                                <div class="section-content">
                                    <div class="product-grid">
                                        <div class="product-tag ">
                                            {{ secondary.second_level_name }}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </transition>
        <Talk></Talk>
    </aside>
</template>
<script>
import { reqNcMatchMenu, reqSearch } from '@/api/ncmatch';
import { buildDynamicStructure } from './buildNcmatchTree';
import Talk from '@/views/homePage/dialog/talk/index.vue';
import eventBus from '@/utils/eventBus'
export default {
    name: 'menuAside',
    components: {
        Talk
    },
    data() {
        return {
            currentCategory: null,
            selectedSecondary: null,
            hideTimer: null,
            categories: [],
            loading: false,
            keyword: '',
            publish_type: '',
        }
    },
    created() {
        this.getCategories();
    },
    methods: {
        performFormalSearch(keyword, type) {
      console.log('=== 执行正式搜索开始 ===');
      console.log('搜索参数:', { keyword, type });
      console.log('当前路由:', this.$route.path);
      console.log('事件总线实例:', eventBus);

      reqSearch({
        url_link: window.location.href,
        keyword: keyword,
        publish_type: type,
        display_page: 'list',  // 正式搜索使用 list
        current_page: 1,
        page_size: 8
      }).then(res => {
        console.log('正式搜索结果:', res);

        // 准备发送事件数据
        const eventData = {
          type: type,
          keyword: keyword,
          data: res.data
        };
        console.log('准备发送事件数据:', eventData);

        // 通过事件总线触发搜索事件，让兄弟组件处理结果
        try {
          eventBus.$emit('search', eventData);
          console.log('事件总线事件发送成功');
        } catch (error) {
          console.error('事件总线事件发送失败:', error);
        }

        console.log('正式搜索完成，已触发搜索事件');

      }).catch(error => {
        console.error('正式搜索失败:', error);
        this.$message.error('搜索失败，请重试');
      });
    },
        goSearch(product) {
            console.log("product",product);
            if(product.source=='search'){

                      // 统一与 search 组件的行为：跳转到 /ncmatchHome/search 并触发正式搜索
            const keywordFromItem = product && (product.first_level_name || product.product_name || product.second_level_name)
            this.keyword = keywordFromItem || this.keyword || ''
            this.publish_type = this.publish_type || '1'
            this.$router.push({
                path: '/ncmatchHome/search',
                query: {
                    keyword: this.keyword,
                    publish_type: this.publish_type,
                    display_page: 'list',
                    current_page: 1,
                    page_size: 8
                }
            }).catch(err => {
                if (err && err.name !== 'NavigationDuplicated') {
                    // ignore duplicate
                    // console.error(err)
                }
            })
            this.performFormalSearch(this.keyword, this.publish_type);
            }else{
                this.openTalk()
            }
            
      
        },

        async openTalk() {
            await this.hideProductList('quick')
            this.$store.commit('setShowTalk', true);
        },
        getCategories() {
            this.loading = true;
            reqNcMatchMenu({ url_link: window.location.href }).then(res => {
                this.loading = false;
                if (res.status) {
                    this.categories = buildDynamicStructure(res.data)
                    console.log("测试", this.categories);

                    // this.categories = res.data.map(item => {
                    //     return {
                    //         name: item.name,
                    //         icon: item.icon,
                    //         product_list: item.product_list
                    //     }
                    // });
                }
            })
        },
        showProductList(category) {
            // 清除之前的定时器
            if (this.hideTimer) {
                clearTimeout(this.hideTimer);
                this.hideTimer = null;
            }
            this.currentCategory = category;
            // 自动选中第一个二级菜单
            if (category.secondaryClassification && category.secondaryClassification.length > 0) {
                this.selectedSecondary = category.secondaryClassification[0];
            } else {
                this.selectedSecondary = null;
            }
        },
        selectSecondary(secondary) {
            this.selectedSecondary = secondary;
        },

        keepProductList() {
            // 清除隐藏定时器，保持显示
            if (this.hideTimer) {
                clearTimeout(this.hideTimer);
                this.hideTimer = null;
            }
        },
        hideProductList(type) {
            if (type === 'quick') {
                this.currentCategory = null;
                this.selectedSecondary = null;
                this.hideTimer = null;
                return
            }
            // 延迟隐藏，给用户时间移动到rightBox
            this.hideTimer = setTimeout(() => {
                this.currentCategory = null;
                this.selectedSecondary = null;
                this.hideTimer = null;
            }, 200);
        }
    }
}
</script>
<style scoped lang="scss">
.menu-item {
    flex: 1;
    font-size: 14px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    min-width: 0;
    /* 确保flex子项可以收缩 */
}

// 左侧分类导航
.category-sidebar {
    position: relative;
    background-color: #f8fbfe;
    height: 100%;
    border-radius: 10px;
    // padding: 15px;
    padding: 5px;

    .category-list {
        list-style: none;
        padding: 0;
        margin: 0;

        .category-item {
            display: flex;
            margin-bottom: 10px;
            align-items: center;
            gap: 10px;
            padding: 4px 0;
            cursor: pointer;
            transition: all 0.3s;
            padding: 0 10px;

            &:hover {
                color: #2c96fc !important;
                background: #c3daee !important;
            }

            &:last-child {
                border-bottom: none;
            }

            .category-icon {

                width: 20px;
                text-align: center;
                display: flex;
                justify-content: center;
                align-items: center;
            }

            .category-name {
                // font-size: 14px;
                font-size: 16px;
            }
        }
    }
}

@media (max-width: 768px) {
    .main-content .content-wrapper {
        grid-template-columns: 1fr;
    }

    .category-sidebar,
    .user-sidebar {
        display: none;
    }

    .header .header-content {
        flex-direction: column;
        gap: 10px;
    }

    .search-section {
        width: 100%;
    }
}

.rightBox {
    position: absolute;
    left: 100%;
    top: 0;
    width: 1000px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    z-index: 9999;
    padding: 25px;
   min-height: 350px;
    margin-left: 10px;
    overflow: visible;
    white-space: nowrap;

    /* 添加一个透明的连接区域，防止鼠标移动时意外消失 */
    &::before {
        content: '';
        position: absolute;
        left: -10px;
        top: 0;
        width: 10px;
        height: 100%;
        background: transparent;
    }

    .rightBox-content {


        .secondary-menu {

            line-height: 1.5;
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            margin-bottom: 20px;

            .secondary-item {
                padding: 4px 8px;
                background: #f8f9fa;
                border-radius: 4px;
                cursor: pointer;
                display: flex;
                transition: all 0.3s ease;
                font-size: 16px;
                color: #333;
                font-weight: 500;

                &:hover,
                &.active {
                    background-color: #ffebf1;
                    color: #ff0f23;
                }
            }
        }

        .menu-content {
            min-height: 200px;
            height: 100%;
            max-height: calc(100vh - 280px);
            overflow-y: auto;

            .jd-style-menu {
                width: 100%;
                display: flex;
                flex-direction: column;
                gap: 20px;

                .category-section {
                    display: flex;
                    justify-content: flex-start;
                    align-items: center;

                    .section-header {
                        display: flex;
                        align-items: center;


                        .section-title {
                            font-size: 16px;
                            font-weight: 600;
                            color: #333;
                            margin-right: 8px;
                        }

                        .section-arrow {
                            color: #999;
                            font-size: 12px;
                        }
                    }

                    .section-content {
                        line-height: 1.5;

                        .product-grid {
                            display: flex;
                            flex-wrap: wrap;
                            gap: 10px;
                            align-items: center;

                            .product-tag {
                                height: fit-content !important;
                                font-size: 14px;
                                color: #666;
                                cursor: pointer;
                                transition: all 0.3s ease;
                                white-space: nowrap;
                                position: relative;

                                &:hover {
                                    color: #e1251b;

                                }
                            }
                        }
                    }
                }
            }

            .hot-tag {
                color: #e1251b !important;
                border-color: #e1251b !important;
                background: #fff5f5 !important;
                font-weight: 500 !important;
                position: relative;

                &::after {
                    content: '';
                    position: absolute;
                    bottom: -1px;
                    left: 0;
                    width: 100%;
                    height: 2px;
                    background: #e1251b;
                    border-radius: 0 0 4px 4px;
                }
            }

            .product-list {
                flex: 1;
                display: grid;
                grid-template-columns: repeat(3, 1fr);
                gap: 12px;
                align-content: start;
                justify-content: center;

                .product-item {
                    width: fit-content;
                    border-radius: 6px;
                    text-align: center;
                    transition: all 0.3s ease;
                    cursor: pointer;

                    &:hover {
                        * {
                            color: #2c96fc;
                        }

                    }

                    .product-name {
                        font-size: 14px;
                        color: #333;
                        font-weight: 500;
                    }
                }
            }
        }
    }
}

.category-sidebar {
    position: relative;
}

/* 过渡动画样式 */
.slide-fade-enter-active {
    transition: all 0.3s ease;
}

.slide-fade-leave-active {
    transition: all 0.3s ease;
}

.slide-fade-enter {
    //   transform: translateX(-20px);
    opacity: 0;
}

.slide-fade-leave-to {
    //   transform: translateX(-20px);
    opacity: 0;
}

.slide-fade-enter-to,
.slide-fade-leave {
    //   transform: translateX(0);
    opacity: 1;
}
</style>