<template>
    <div class="box_home_left">
        <div class="scroll-view" ref="scrollViewRef" @mouseenter="onMouseenter" @mouseleave="onMouseleave">
            <div ref="listRef" class="item_home_water" v-for="(item, index) in leftData" :key="index">
                <waterIntaking :waterData="item"></waterIntaking>
            </div>
        </div>
    </div>
</template>

<script setup>
import waterIntaking from './waterIntaking.vue'

const props = defineProps({
    resultData: {
        type: Object,
        default: {}
    }
})

const leftData = ref([])
const listRef = ref([]); // 这是一个数组引用
const scrollViewRef = ref(); //滚动区域dom
const count = ref(1); //列表个数
let intervalId = null;
let isAutoScrolling = true; //是否自动滚动标识
let scrollDirection = 1; // 滚动方向：1向下，-1向上

watch(() => props.resultData, (newVal) => {
    if (newVal) {
        leftData.value = newVal;
        intervalId && clearInterval(intervalId);
        nextTick(() => {
            //判断列表是否生成滚动条
            count.value = hasScrollBar() ? 2 : 1;
            //有滚动条开始自动滚动
            if (count.value == 2) {
                autoScrolling();
            }
        });
    }
}, { deep: true, immediate: true })

//判断列表是否有滚动条
const hasScrollBar = () => {
    if (scrollViewRef.value) {
        return scrollViewRef.value.scrollHeight > scrollViewRef.value.clientHeight;
    }
    return false;
};

//设置自动滚动
const autoScrolling = () => {
    intervalId = setInterval(() => {
        if (!isAutoScrolling || !scrollViewRef.value) return;
        
        const { scrollTop, scrollHeight, clientHeight } = scrollViewRef.value;
        const maxScroll = scrollHeight - clientHeight;
        
        // 根据方向滚动
        let newScrollTop = scrollTop + (scrollDirection * 1);
        
        // 判断是否到达边界，改变滚动方向
        if (newScrollTop >= maxScroll) {
            // 到达底部，向上滚动
            scrollDirection = -1;
            newScrollTop = maxScroll;
        } else if (newScrollTop <= 0) {
            // 到达顶部，向下滚动
            scrollDirection = 1;
            newScrollTop = 0;
        }
        
        scrollViewRef.value.scrollTop = newScrollTop;
    }, 30);
};

onBeforeUnmount(() => {
    //离开页面清理定时器
    intervalId && clearInterval(intervalId);
});

//鼠标进入，停止滚动
const onMouseenter = () => {
    isAutoScrolling = false;
};

//鼠标移出，继续滚动
const onMouseleave = () => {
    isAutoScrolling = true;
};
</script>

<style scoped lang="scss">
.box_home_left {
    position: absolute;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    z-index: 2;
}

.scroll-view {
    flex: 1;
    height: auto;
    width: 100%;
    overflow-y: auto;
    
    /* 隐藏滚动条 - Webkit浏览器 */
    &::-webkit-scrollbar {
        display: none; /* Chrome Safari */
    }
    
    /* 隐藏滚动条 - Firefox */
    scrollbar-width: none; /* Firefox */
    
    /* 隐藏滚动条 - IE/Edge */
    -ms-overflow-style: none; /* IE and Edge */
}

.item_home_water {
    width: 100%;
    box-sizing: border-box;
}
</style>