<template>
    <BasePage :title="typeName">
        <van-popup v-model:show="showMainCategory" position="left" :style="{ width: '30%', height: '100%' }">
            <van-cell-group>
                <van-cell>
                    <template #title>
                        <div style="display: flex; justify-content: center;"
                            @click="changeMain(); typeName = ''; showMainCategory = false;">
                            <span
                                :style="{ color: (mainCategory == '' ? 'var(--van-danger-color)' : '#222') }">全部分类</span>
                        </div>
                    </template>
                </van-cell>
                <van-cell v-for="item in firstCategories" :key="item.id">
                    <template #title>
                        <div style="display: flex; justify-content: center;"
                            @click="changeMain(item); showMainCategory = false;">
                            <span :style="{ color: (mainCategory == item.id ? 'var(--van-danger-color)' : '#222') }">
                                {{ item.name }}
                            </span>
                        </div>
                    </template>
                </van-cell>
            </van-cell-group>
        </van-popup>
        <div class="goods-list">
            <div class="_search">
                <van-icon name="list-switch" style="font-size: 24px;" @click="showMainCategory = true;" />
                <van-search style="width: 100%;" v-model="searchKey" shape="round" placeholder="搜索想要的产品"
                    @search="onSearch" />
            </div>

            <div class="_tabs">
                <van-tabs v-model:active="secondCategory" @change="changeSecond" type="card"
                    v-if="selectedSecond.length > 0">
                    <van-tab title="全部" name="" />
                    <van-tab v-for="item in selectedSecond" :key="item.id" :title="item.name" :name="item.id" />
                </van-tabs>
            </div>
            <div class="goodslist">
                <van-sidebar v-model="goodsCategoryIndex">
                    <van-sidebar-item name="" title="全部产品" @click="changeThird('')" />
                    <van-sidebar-item v-for="item in selectedThird" :key="item.id" :title="item.name"
                        @click="changeThird(item.id)" />
                </van-sidebar>

                <div class="pro-list">
                    <div class="px">
                        <a @click="toggleValue(0)" :class="searchParams.SortType == 0 ? 'a' : ''">
                            综合 <img :src="getImageSource(0)" />
                        </a>
                        <a @click="toggleValue(1)" :class="searchParams.SortType == 1 ? 'a' : ''">
                            价格 <img :src="getImageSource(1)" />
                        </a>
                        <a @click="toggleValue(2)" :class="searchParams.SortType == 2 ? 'a' : ''">
                            销量 <img :src="getImageSource(2)" />
                        </a>
                    </div>
                    <div class="content">
                        <BaseList class="pro-list" ref="productList" :url="`/v1/client/EProsClient`"
                            :params="queryParams" @load="onLoad">
                            <template #default="{ item }">
                                <div class="a1" @click="$navigate('/GoodsDetail?id=' + item.id)">
                                    <img :src="$file(item.img)" />
                                    <div class="c">
                                        <div class="name">{{ item.name }}</div>
                                        <div class="box box-pack-between">
                                            <s>￥{{ item.originalprice?.toFixed(2) }}</s>
                                            <!-- <div class="zeng_box">
                                                <span>赠</span>
                                                <div>
                                                    {{ item.gongxianzhi }}贡献值
                                                </div>
                                            </div> -->
                                        </div>
                                        <div class="price">
                                            <b><span>￥</span>{{ item.saleprice?.toFixed(2) }}</b>
                                            <span class="r" style="color: #8a8a8a;font-size: 3.2vw;">销量{{ item.salenums
                                                }}</span>
                                        </div>
                                    </div>
                                </div>
                                <hr
                                    style="height:1px;width: 100%;background: linear-gradient(to bottom, transparent, #f5f5f5, transparent);border: none;">
                            </template>
                        </BaseList>
                    </div>
                </div>
            </div>
        </div>
    </BasePage>
</template>

<script>
import BaseList from '../../components/BaseList.vue';

export default {
    name: 'Category',
    components: { BaseList },
    data() {
        return {
            showMainCategory: false,
            typeName: '',
            searchKey: '',
            secondCategory: '',
            goodsCategoryIndex: 0,
            allCategories: [],
            firstCategories: [],
            secondCategories: [],
            thirdCategories: [],
            selectedSecond: [],
            selectedThird: [],
            mainCategory: '',
            currentThirdId: '',
            searchParams: {
                SortType: 0,
                IsDesc: true,
            },
            queryParams: {
                mallstate: 3,
                pid: '',
                name: '',
            },
            imageSources: [
                "/img/pro-list-px-0.png",
                "/img/pro-list-px-1.png",
                "/img/pro-list-px-2.png",
            ],
        }
    },
    beforeRouteLeave(to, from, next) {
        sessionStorage.setItem('category_scroll', window.scrollY)
        next()
    },
    deactivated() {
        sessionStorage.setItem('category_scroll', window.scrollY)
    },
    mounted() {
        this.init()
    },
    activated() {
    },
    methods: {
        async init() {
            await this.loadCategories();
            if (this.$route.query.id) {
                this.changeMainById(Number(this.$route.query.id));
            }
            // 如果URL带有SortType=2（从热销入口进入），默认以销量排序
            if (this.$route.query.SortType == 2) {
                this.searchParams.SortType = 2;
                this.searchParams.IsDesc = true;
            }
            // 如果URL带有name参数，初始化搜索
            if (this.$route.query.name) {
                this.searchKey = this.$route.query.name;
                this.queryParams.name = this.searchKey;
            }
        },
        async loadCategories() {
            try {
                const res = await this.$get(`/v1/client/EProcatesClient/select`);
                const list = res?.data || res;
                if (list && Array.isArray(list)) {
                    this.allCategories = list;
                    this.buildCategories(list);
                }
            } catch (err) {
                console.error('加载分类失败', err);
            }
        },
        buildCategories(data) {
            this.firstCategories = data.map(item => ({
                id: item.id,
                name: item.name,
                img: item.img
            }));

            this.secondCategories = [];
            this.thirdCategories = [];

            data.forEach(first => {
                if (first.children && first.children.length > 0) {
                    first.children.forEach(second => {
                        this.secondCategories.push({
                            id: second.id,
                            name: second.name,
                            img: second.img,
                            parentId: first.id
                        });

                        if (second.children && second.children.length > 0) {
                            second.children.forEach(third => {
                                this.thirdCategories.push({
                                    id: third.id,
                                    name: third.name,
                                    img: third.img,
                                    parentId: second.id,
                                    rootId: first.id
                                });
                            });
                        }
                    });
                }
            });

            this.selectedSecond = this.secondCategories;
            this.selectedThird = this.thirdCategories;
        },
        changeMain(item) {
            if (!item) {
                this.mainCategory = '';
                this.typeName = '';
                this.selectedSecond = this.secondCategories;
            } else {
                this.mainCategory = item.id;
                this.typeName = item.name;
                this.selectedSecond = this.secondCategories.filter(x => x.parentId === item.id);
            }
            this.secondCategory = '';
            this.changeSecond(this.secondCategory);
        },
        changeMainById(id) {
            const item = this.firstCategories.find(x => x.id === id);
            if (item) {
                this.changeMain(item);
            }
        },
        changeSecond(e) {
            if (e) {
                this.queryParams.pid = e;
                this.selectedThird = this.thirdCategories.filter(x => x.parentId === e);
            } else if (this.mainCategory) {
                this.queryParams.pid = this.mainCategory;
                this.selectedThird = this.thirdCategories.filter(x => x.rootId === this.mainCategory);
            } else {
                this.queryParams.pid = '';
                this.selectedThird = this.thirdCategories;
            }
            this.goodsCategoryIndex = 0;
            this.currentThirdId = '';
            this.refreshProductList();
        },
        changeThird(id) {
            this.currentThirdId = id;
            this.queryParams.pid = id;
            this.refreshProductList();
        },
        onSearch() {
            this.queryParams.name = this.searchKey;
            this.refreshProductList();
        },
        onLoad() {
            // loaded
        },
        refreshProductList() {
            this.$refs.productList?.refresh();
        },
        toggleValue(e) {
            if (this.searchParams.SortType == e) {
                this.searchParams.IsDesc = !this.searchParams.IsDesc;
            } else {
                this.searchParams.SortType = e;
                this.searchParams.IsDesc = true;
            }
            this.refreshProductList();
        },
        getImageSource(e) {
            if (this.searchParams.SortType == e) {
                if (this.searchParams.IsDesc) return this.imageSources[2];
                else return this.imageSources[1];
            } else return this.imageSources[0];
        },
    }
}
</script>

<style lang="less">
.goods-list {
    position: relative;

    .van-tabs__nav--card .van-tab.van-tab--active {
        color: #fff !important;
        background-color: var(--van-danger-color);
        border-radius: 6px;
        margin-right: 6px !important;
        border: 1px solid #fff !important;
    }

    .van-tab--card {
        color: #222 !important;
        background-color: #fff;
        border-radius: 6px;
        margin-right: 6px !important;
        border: 1px solid #ccc !important;
        font-size: 12px;
    }

    .van-tabs__nav--card {
        border: unset;
    }

    .zeng_box {
        display: flex;
        flex-wrap: nowrap;
        margin-left: auto;
        width: auto;
        margin-bottom: 3.2vw;

        >div {
            border-radius: 0 0.67vw 0.67vw 0;
            border: 1px solid #fcc;
            border-left: 0;
            font-size: 2.93vw;
            color: #ff3234;
            padding: 0 0.6vw;
            line-height: calc(4vw - 0.53333vw);
        }

        span {
            display: flex;
            flex-wrap: nowrap;
            justify-content: center;
            align-items: center;
            text-align: center;
            line-height: 3.52vw;
            width: 5.87vw;
            height: 4vw;
            line-height: 4vw;
            background-color: #ff3234;
            border-radius: 0.67vw 0 0 0.67vw;
            padding: 0.4vw 1vw;
            font-size: 3.2vw;
            color: #ffffff;
        }
    }
}
</style>
<style scoped>
.van-sidebar {
    height: 100%;
}
</style>
