import { reportLog } from '../logger';
import { getActiveKeyAfterClick } from '@/uilts/help';
import Report from "@/log-center/log"

// 每个窗口共享一个Observer实例
class ShowLogObserver { 
    constructor() { 
        this._observe = null;
        this.showLogMap = new Map();
        this.init();
    }

    init() {
        this._observe = new IntersectionObserver((entries, observer) => {
            entries.forEach((entry) => {
                if (entry.intersectionRatio > 0.5) {
                    this.report(entry);
                    // show-log-once  ===  '1' &&  曝光之后取消观察
                    if (entry?.target?.getAttribute('show-log-once') === '1') {
                        this.remove(entry.target);
                    }
                }
            })
        }, {
            root: null,
            rootMargin: '0px',
            threshold: 1
        })
    }

    remove(el) { 
        this._observe.unobserve(el);
        this.showLogMap.delete(el.denetShowLogkey);
    }

    add(el, binding) { 
        this._observe.observe(el);
        this.showLogMap.set(el.denetShowLogkey, binding.value)
    }

    report(el) { 
        const { extParams, ...eventData } = this.showLogMap.get(el?.target?.denetShowLogkey);
        return eventData && reportLog({
            businessType: Report.businessType.pageView,
            ...eventData
        }, extParams)
    }
}

export default new ShowLogObserver();