import * as React from 'react';
import { BasicProps } from './type'
import log from './utils/lofter-log'

import 'intersection-observer'


export class BaseComponent extends React.Component<BasicProps> {

  componentRef: HTMLDivElement

  judgeEqual = (value1: number, value2: number) => {
    if (Math.abs(value1 - value2) < 0.1) {
      return true
    }
    return false
  }

  componentDidMount() {
    if (!this.props.isEdit) {
      // 阈值为 1 的话，
      let options = {
        rootMargin: '5%',
        threshold: [0, 1]
      }
      let prevRatio = 0
      let observer = new IntersectionObserver((entries) => {
        entries.forEach((entry) => {
          if (
            this.judgeEqual(entry.intersectionRatio, 1)
            && !this.judgeEqual(prevRatio, 1)
          ) {
            console.log(this.props.instanceKey, '元素可见了')
            log.capture(`cmsact-1-${this.props.instanceKey.slice(14)}`, {
              category: 'cmsact',
              action: 0,
              scene: 'cmsact',
              v: '1.0.0'
            })
          }
          prevRatio = entry.intersectionRatio
        })
      }, options);
      observer.observe(this.componentRef)
    }
  }

  render() {
    const style = this.props.customStyle || {}
    return (
      <div
        style={{width: '100%', ...style}}
        ref={ref => this.componentRef = ref}
      >
        {this.props.children}
      </div>
    )
  }
}

export const handleComponentClickLog = (key: string) => {
  log.capture(`cmsact-2-${key.slice(14)}`, {
    category: 'cmsact',
    action: 0,
    scene: 'cmsact',
    v: '1.0.0'
  })
}
