<template>
    <view>
        <view class="u-wrap">
            <view class="u-menu-wrap">
                <scroll-view scroll-y scroll-with-animation class="u-tab-view menu-scroll-view" :scroll-top="scrollTop"
                    :scroll-into-view="itemId">
                    <view v-for="(item, index) in tabbar" :key="index" class="u-tab-item"
                        :class="[current == index ? 'u-tab-item-active' : '']" @tap.stop="swichMenu(index)">
                        <text class="u-line-1">{{ item.businessName }}</text>
                        <view v-if="activesParentIds[item.id]" class="u-tab-item-radio flex_c_c">{{
                            activesParentIds[item.id].length }}</view>
                    </view>
                </scroll-view>
                <scroll-view :scroll-top="scrollRightTop" scroll-y scroll-with-animation class="right-box"
                    @scroll="rightScroll">
                    <view class="page-view">
                        <view class="class-item" :id="'item' + index" v-for="(item, index) in tabbar" :key="index">
                            <view class="item-title">
                                <text class="item-businessName">{{ item.businessName }}</text>
                                <text class="item-title-text">{{ item.businessDescribe }}</text>
                            </view>
                            <view class="item-container">
                                <view v-for="(item1, index1) in (item.children ? item.children : [item])" :key="index1"
                                    :class="[activesIds.includes(item1.id) ? 'thumb-box thumb-box-active ' : 'thumb-box']"
                                    @click="clickMenu(item1)">
                                    <image class="item-menu-image" :src="item1.businessIcon"></image>
                                    <view class="item-menu-name">{{ item1.businessName }}</view>
                                </view>
                            </view>
                        </view>
                    </view>
                </scroll-view>
            </view>
        </view>
        <view class="class-footer">
            <view class="footer-title flex_c_s">
                <view class="footer-text">已选服务</view>
                <!-- <view class="footer-text">{{ activeList.length }}/6</view> -->
            </view>
            <view class="footer-btns" v-if="activeList && activeList.length > 0">
                <view class="footer-btn" v-for="item in activeList" :key="item.id">
                    {{ item.businessName || 'xx' }}
                    <view class="footer-class-close" @click="deleteActiveList(item.id)"></view>
                </view>
            </view>
            <view class="footer-submit-box flex_c_c">
                <view class="footer-submit flex_c_c" @click="onSubmit">确定</view>
            </view>
        </view>

    </view>
</template>
<script>
import { getTreeList } from '@/api/volunteer'
import { volunteerSeachgetTreeList } from "@/api/volunteerDetailsApi/details.js"
import { getVolunteerInfo } from '@/api/volunteer.js'
import CustomTabBar from '@/components/CustomTabBar/index.vue'
import { computed } from 'vue'

export default {
    components: { CustomTabBar },
    data() {
        return {
            scrollTop: 0, //tab标题的滚动条位置
            oldScrollTop: 0,
            current: 0, // 预设当前项的值
            menuHeight: 0, // 左边菜单的高度
            menuItemHeight: 0, // 左边菜单item的高度
            itemId: '', // 栏目右边scroll-view用于滚动的id
            tabbar: [],

            arr: [],
            scrollRightTop: 0, // 右边栏目scroll-view的滚动条高度
            timer: null, // 定时器
            userType: uni.getStorageSync('userType') || 1,

            activeList: [],

        }
    },
    computed: {
        activesIds() {
            return this.activeList.map(item => item.id);
        },
        activesParentIds() {
            const result = this.activeList.reduce((acc, item) => {
                const { parentId } = item;

                if (!acc[parentId]) {
                    acc[parentId] = [];
                }
                
                acc[parentId].push(item.id); // 推入整个对象

                return acc;
            }, {});

            return result;
        }
    },
    onReady() {

    },
    onShow() {
        this.getData();
        this.getMenuItemTop()
    },
    onLoad(options) {
        const data = decodeURIComponent(options.data)
        console.log("TCL: options", )
        if(data){
            this.activeList = data ? JSON.parse(data) : [];
        }
        
    },
    methods: {
        deleteActiveList(id) {
            console.log("TCL: deleteActiveList -> id", id)
            this.activeList = this.activeList.filter(item => item.id !== id);
        },
        getData() {
            getTreeList({ parentId: '0' }).then(res => {
                this.tabbar = res.data;
            })
        },
        // 点击左边的栏目切换
        async swichMenu(index) {
            if (this.arr.length == 0) {
                await this.getMenuItemTop();
            }
            if (index == this.current) return;
            this.scrollRightTop = this.oldScrollTop;
            this.$nextTick(() => {
                this.scrollRightTop = this.arr[index];
                this.current = index;
                this.leftMenuStatus(index);
            })
        },
        // 获取一个目标元素的高度
        getElRect(elClass, dataVal) {
            new Promise((resolve, reject) => {
                const query = uni.createSelectorQuery().in(this);
                query.select('.' + elClass).fields({
                    size: true
                }, res => {
                    // 如果节点尚未生成，res值为null，循环调用执行
                    if (!res) {
                        setTimeout(() => {
                            this.getElRect(elClass);
                        }, 10);
                        return;
                    }
                    this[dataVal] = res.height;
                    resolve();
                }).exec();
            })
        },
        // 观测元素相交状态
        async observer() {
            this.tabbar.map((val, index) => {
                let observer = uni.createIntersectionObserver(this);
                // 检测右边scroll-view的id为itemxx的元素与right-box的相交状态
                // 如果跟.right-box底部相交，就动态设置左边栏目的活动状态
                observer.relativeTo('.right-box', {
                    top: 0
                }).observe('#item' + index, res => {
                    if (res.intersectionRatio > 0) {
                        let id = res.id.substring(4);
                        this.leftMenuStatus(id);
                    }
                })
            })
        },
        // 设置左边菜单的滚动状态
        async leftMenuStatus(index) {
            this.current = index;
            // 如果为0，意味着尚未初始化
            if (this.menuHeight == 0 || this.menuItemHeight == 0) {
                await this.getElRect('menu-scroll-view', 'menuHeight');
                await this.getElRect('u-tab-item', 'menuItemHeight');
            }
            // 将菜单活动item垂直居中
            this.scrollTop = index * this.menuItemHeight + this.menuItemHeight / 2 - this.menuHeight / 2;
        },
        // 获取右边菜单每个item到顶部的距离
        getMenuItemTop() {
            new Promise(resolve => {
                let selectorQuery = uni.createSelectorQuery();
                selectorQuery.selectAll('.class-item').boundingClientRect((rects) => {
                    // 如果节点尚未生成，rects值为[](因为用selectAll，所以返回的是数组)，循环调用执行
                    if (!rects.length) {
                        setTimeout(() => {
                            this.getMenuItemTop();
                        }, 10);
                        return;
                    }
                    rects.forEach((rect) => {
                        // 这里减去rects[0].top，是因为第一项顶部可能不是贴到导航栏(比如有个搜索框的情况)
                        this.arr.push(rect.top - rects[0].top);
                        resolve();
                    })
                }).exec()
            })
        },
        // 右边菜单滚动
        async rightScroll(e) {
            this.oldScrollTop = e.detail.scrollTop;
            if (this.arr.length == 0) {
                await this.getMenuItemTop();
            }
            if (this.timer) return;
            if (!this.menuHeight) {
                await this.getElRect('menu-scroll-view', 'menuHeight');
            }
            setTimeout(() => { // 节流
                this.timer = null;
                // scrollHeight为右边菜单垂直中点位置
                let scrollHeight = e.detail.scrollTop + this.menuHeight / 2;
                for (let i = 0; i < this.arr.length; i++) {
                    let height1 = this.arr[i];
                    let height2 = this.arr[i + 1];
                    // 如果不存在height2，意味着数据循环已经到了最后一个，设置左边菜单为最后一项即可
                    if (!height2 || scrollHeight >= height1 && scrollHeight < height2) {
                        this.leftMenuStatus(i);
                        return;
                    }
                }
            }, 10)
        },
        async clickMenu(record) {
            try {
                console.log(record, this.activesIds, this.activesParentIds);
                // if (this.activesIds && this.activesIds.length === 6) {
                //     uni.showToast({
                //         title: '最多可选择6个类目!',
                //         icon: 'none',
                //     });
                //     return
                // }
                !this.activesIds.includes(record.id) ? this.activeList.push({ ...record, children: [] }) : uni.showToast({
                    title: '已勾选该类目!',
                    icon: 'none',
                });

            } catch (error) {
                console.log("TCL: clickMenu -> error", error)
            }
        },
        onSubmit() {
           try {
            const pages = getCurrentPages();
            const prevPage = pages[pages.length - 2];

            if (prevPage && prevPage.$vm) {
                // 假设上一页有一个方法叫 handleReturnData
                prevPage.$vm.activeProjectBack({
                    serves: encodeURIComponent(JSON.stringify(this.activeList)),
                });
            }
            uni.navigateBack({
                delta: 1
            });
           } catch (error) {
            console.log("TCL: onSubmit -> error", error)
            
           }
            // uni.redirectTo({
            //     url: `/pages_home/pages/certification/index?serves=${encodeURIComponent(JSON.stringify(this.activeList))}`
            // })
            console.log('this.activeList', this.activeList);

        }


    }
}
</script>

<style lang="scss" scoped>
.u-wrap {
    display: flex;
    flex-direction: column;

    position: fixed;
    top: 0px;
    left: 0px;
    right: 0px;
    // bottom: 150rpx;
    bottom: 0;
    // padding-bottom: 150px;

}

.u-search-box {
    padding: 18rpx 30rpx;
}

.u-menu-wrap {
    flex: 1;
    display: flex;
    overflow: hidden;
}

.u-search-inner {
    background-color: rgb(234, 234, 234);
    border-radius: 100rpx;
    display: flex;
    align-items: center;
    padding: 10rpx 16rpx;
}

.u-search-text {
    font-size: 26rpx;
}

.u-tab-view {
    width: 250rpx;
    height: 100%;
}

.u-tab-item {
    height: 100rpx;
    background: #f6f6f6;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;

    font-family: PingFang SC;
    font-size: 26rpx;
    font-weight: 500;
    line-height: 42rpx;
    text-align: center;
    letter-spacing: normal;
    color: #818181;
    border-left: 4rpx solid #fff;

    position: relative;
}

.u-tab-item-radio {
    width: 32rpx;
    height: 32rpx;
    padding: 8rpx;
    border-radius: 50%;
    background: #F53F3F;
    position: absolute;
    right: 0px;

    font-size: 24rpx;
    color: #FFFFFF;
}

.u-tab-item-active {
    position: relative;
    background: #fff;
}

.u-tab-item-active::before {
    border-left: 4rpx solid rgba(221, 94, 69, 1) !important;
}

.u-tab-item-active::before {
    content: "";
    position: absolute;
    border-left: 4px solid $u-primary;
    height: 100%;
    left: -5rpx;
    top: 0;
}

.u-tab-view {
    height: 100%;
    background: #F6F6F6;
}


.right-box {
    background-color: rgb(250, 250, 250);
}

.page-view {
    // padding: 16rpx;
}

.class-item {
    // margin-bottom: 30rpx;
    background-color: #fff;
    padding: 34rpx;
    border-radius: 8rpx;
}

.class-item:last-child {
    min-height: 100vh;
}

.item-title {
    // font-size: 26rpx;
    // color: $u-main-color;
    // font-weight: bold;
    // text-align: center;
    display: flex;
    align-items: center;
    justify-content: space-between;

    border-radius: 14rpx;
    background: linear-gradient(180deg, #FFF9F3 0%, rgba(255, 255, 255, 0) 100%);
}

.item-businessName {
    font-family: PingFang SC;
    font-size: 26rpx;
    font-weight: 600;
    line-height: 42rpx;
    letter-spacing: normal;
    color: #262626;
}

.item-title-text {
    font-family: Yuppy SC;
    font-size: 24rpx;
    font-weight: 500;
    line-height: 42rpx;
    text-align: right;
    letter-spacing: normal;
    color: #E58182;
}

.item-menu-name {
    font-family: PingFang SC;
    font-size: 26rpx;
    font-weight: 500;
    line-height: 42rpx;
    text-align: center;
    letter-spacing: normal;
    color: #5D5D5D;
}

.item-container {
    // display: flex;
    // flex-wrap: wrap;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12rpx;
    margin: 24rpx 0;
}

.thumb-box {
    // width: 33.333333%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    // margin-top: 20rpx;

    // background: #f5f5f5;
    padding: 12rpx 0;
}

.thumb-box-active {
    .item-menu-image::before {
        content: '';
        width: 138rpx;
        height: 138rpx;
        position: absolute;
        left: 0px;
        top: 0px;
        background: rgba(216, 216, 216, 0.6);
        z-index: 2;
        border-radius: 50%;
    }

    .item-menu-image::after {
        content: '';
        width: 138rpx;
        height: 138rpx;
        position: absolute;
        left: 0px;
        top: 0px;
        z-index: 3;
        background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAcCAYAAAAAwr0iAAAAAXNSR0IArs4c6QAAAARzQklUCAgICHwIZIgAAAKOSURBVEiJxZVPSFRRFId/59zXH8JFS4sIA3MGdCO4KEo4zhC4CqMWLQrcii1ql7ugRS5aNNDCZSJBEdFSwXpeMDFwkYGjDgS1MHHRwoXQVPPuadE8m3nMc3zjON3d3HvP+b53z5l7Cf9hfBE5/pP5IQEF02r4qsgFZZ4mwlUQnfVaBZ4T8U4xPwLhLgAPAFR1kloBXxPpYGNeAdoXzqliJO37E3zY8EI2O8SGP0bg99K+PwEAhyqwlsk8APQNgJMR+JPw96H0QF6kzTM8BWCocl6BXCUcAJreA3mR9iPMs0roqV7Rl6l3czej+5tagoJI2mNejMJVdeFooMO1YpomUBC5DMPzIHREljYCpzfOWVusFdeUEpTh0wDaIktFCtzFLmuX42J3mzAv0naUedRzLhdnmxAOUozsBQfKJciLdHrMS44w/suY+U8iZw4KB3Syy/ef1cvB61kZ9AwvgZAuB/YdM7y0JiKNwkmxUgr0zn4+ggk0jIqLAgAIaCfDs4VsdrRW0KpIT/yXowTnbndbu7Mvgc1Abyn0dXSBAA/Qp4VsZiovsgv6LNLJhmdj4HCKsXp1j3DKL5WhFwS6HrNt2QXBtSKwfYJ58V+5osnow7cg6B+wtpRIIJQ4zTQDomzM3u8Afa18VCKjiMD1pqxd3y+8SgD4+1c0TDNEdClJEgCAYizl++NJw6puwm5rdwKng6q6kCQJKVY2nXucFA7E3ISJT4Jcf+qtfd+IQM23IDwJUqzUS6DQ543CYwVCid/OXYFir6YqmkDvNwrfU6AssVVybiBOQhW589ZuHJpAHYntH84l7vrEAlUSwFY45xS5Xmu3WyIQSiDYlSg65yYOCm9oFETS65nMgY8+HH8AWxQUPX3zeH8AAAAASUVORK5CYII=);
        background-position: center;
        background-size: 32rpx auto;
        background-repeat: no-repeat;
    }

    .item-menu-name {
        color: #FF6E51;
    }
}

.item-menu-image {
    width: 138rpx;
    height: 138rpx;
    margin-bottom: 12rpx;
}

.class-footer {
    position: fixed;
    bottom: 0rpx;
    left: 0px;
    right: 0;
    z-index: 999;
    background: #fff;
    padding-bottom: 60rpx;

    .footer-title {
        padding: 38rpx 28rpx;

    }

    .footer-btns {
        display: grid;
        grid-template-columns: repeat(3, 1fr); // 创建 3 列，每列等宽
        gap: 10rpx; // 设置列与行之间的间距
        padding: 0 26rpx 48rpx;

        .footer-btn {
            border-radius: 66rpx;
            box-sizing: border-box;
            border: 2rpx solid #FF6E51;
            padding: 16rpx 16rpx 16rpx 36rpx;
            font-size: 30rpx;
            font-weight: 500;
            color: #FF6E51;
            display: flex;
            align-items: center;
            gap: 14rpx;

            .footer-class-close {
                width: 34rpx;
                height: 34rpx;
                background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB8AAAAfCAYAAAAfrhY5AAAAAXNSR0IArs4c6QAAAARzQklUCAgICHwIZIgAAALgSURBVEiJ5ZdNS9xAGMfnzRBB0UJhdw/DIriga8B63BRLbz31Yl08iIUc21IQP8F+glLoocehUg8S62cIlcabVMhFVvCwUHbBg16C7M5LL91lk0xi1t1Dwf8pmZknv38yz0yeAeCxCo4awBibLxQK60KIBQgh4pxLwzCuOp3OieM4NxOHM8bM2dnZ90qpnV6v9yxt3NTU1G+M8f7t7e1Xx3Huxoa7rrsthPgipXySxygAAGCMrxFCu/V6/eBB8EajQSzLOux2uxt5oXEZhnEcBMFWo9HgWpNp4Gq16vV6vVcPBQMAgBBiuVQqvaxWq989z5PxfqQLsizrkHP+fBxwX91u94VlWYe6vgTcdd3tcT51ioEN13W34+2ROWeMmdPT039GSa68whhfh2FIh1dB5M1nZmY+pIEhhMC2bUAp1T6cUgps2wYQ6nNYCPF0bm7u3XBbBK6U2klzXqvVQLlc1hrog8vlMqjVammPAEKIt1o4Y2yec76aFthqtYCUEiCEIgb6YIQQkFKCVquVCuecrzLG5hPwQqGwnhr1D+77fsTA2tpaBOz7fiZcKQWLxaKdgAshFrLgOgNLS0u5wX1xzhcTcAihds3rDDSbzUhbs9nMBY5zBhdKqcQOpBOlFFQqlUhbpVJJXQVxDXMGcIzxVR7w8BxfXFxokzBLhJDLBLzT6ZyMAvZ9H5ydnSWSMMsAhFC1220/AXcc54YQcp4F1yVXPAmz4ISQ8+GCg8Q6v3HOP+kCT09PB7B4cvUNUEoH43TCGO8P3/8/e7vjOHcY44+TBgMAAEJoN15aaf8CR0dHPyb5WzUM43hzc/NNwpBucBAEW4SQXxMC/wyCYEvXpy2jPM+TKysr+6VSyRJCLI8BPg6C4HVaDZerepVSfhZCPM0LzVu93ruf1+v1gzAMqWmae1n7AIRQEULOTdPcC8OQ3gcG4IEnlmKxaHPOFyGESCklCSGX7XbbH/XE8nj1FxvKd+/WNl3DAAAAAElFTkSuQmCC);
                background-position: center;
                background-size: 34rpx auto;
                background-repeat: no-repeat;
            }
        }
    }

    .footer-submit-box {
        .footer-submit {
            border-radius: 14rpx;
            background: linear-gradient(180deg, #FD8F7C -75%, #FE534B 140%);
            width: 580rpx;
            height: 80rpx;

            font-family: PingFang SC;
            font-size: 30rpx;
            font-weight: 500;
            line-height: 42rpx;
            letter-spacing: normal;
            color: #FFFFFF;
        }
    }
}

.footer-text {
    font-size: 30rpx;
    font-weight: 500;
    line-height: 30rpx;
    color: rgba(0, 0, 0, 0.9);
}
</style>
