import md from '../md';

class ExposureTracker {
    constructor(component) {
        this.component = component;
        this.exposureMap = new Map(); // 记录每个元素的曝光状态
        this.windowHeight = 0;
        this.init();
    }

    init() {
        // 获取窗口高度
        const systemInfo = uni.getSystemInfoSync();
        this.windowHeight = systemInfo.windowHeight;
    }

    // 添加需要追踪的元素配置
    addExposureElement(config) {
        const { id, logParams } = config;
        if (!this.exposureMap.has(id)) {
            this.exposureMap.set(id, {
                isExposed: false,
                logParams
            });
        }
    }

    // 批量添加需要追踪的元素配置
    addExposureElements(configs) {
        configs.forEach(config => this.addExposureElement(config));
    }

    // 检查元素是否在可视区域内
    isElementInViewport(rect, scrollTop) {
        const elementTop = rect.top;
        const elementBottom = rect.top + rect.height;
        const viewportTop = scrollTop;
        const viewportBottom = scrollTop + this.windowHeight;

        return (
            (elementBottom >= viewportTop && elementBottom <= viewportBottom) ||
            (elementTop >= viewportTop && elementTop <= viewportBottom) ||
            (elementTop <= viewportTop && elementBottom >= viewportBottom)
        );
    }

    // 检查所有元素的曝光状态
    checkExposure(scrollTop) {
        const query = uni.createSelectorQuery().in(this.component);
        
        this.exposureMap.forEach((value, id) => {
            if (value.isExposed) return; // 如果已经曝光过，则跳过

            query.select(`#${id}`)
                .boundingClientRect(res => {
                    if (!res) return;

                    const isVisible = this.isElementInViewport(res, scrollTop);
                    if (isVisible && !value.isExposed) {
                        value.isExposed = true;
                        // 触发埋点
                        md.sensorLogTake(value.logParams);
                    }
                });
        });

        query.exec();
    }

    // 重置某个元素的曝光状态
    resetExposure(id) {
        const element = this.exposureMap.get(id);
        if (element) {
            element.isExposed = false;
        }
    }

    // 重置所有元素的曝光状态
    resetAllExposure() {
        this.exposureMap.forEach(value => {
            value.isExposed = false;
        });
    }
}

export default ExposureTracker; 