import Taro from '@tarojs/taro'
import { getQrCodeParams } from '@/utils/qrcode'
import { savePoint, updatePoint } from '@/services/common'
// import { report } from '@/utils/customer'

function isFunction(fn) {
  return typeof fn === 'function'
}

export function withDetail(opts = {}) {
  return function (OrigComp) {
    class WrapperComponent extends OrigComp {
      // 数据详情加载
      // _$_dataReady 被透传到父组件,  父组件加载完数据之后需要调用 this._$_dataReady()
      _$_dataReady;
      // 父组件调用 _$_dataReady 之后, 当前组件就可以 _$_dataLoadPromise.then 了
      _$_dataLoadPromise = new Promise(resolve => (this._$_dataReady = resolve));

      // 更新埋点时长
      _$_trackOverFn;

      async componentWillMount() {
        // 解析二维码
        if (this.$router.params.scene) {
          this._$_scene = await getQrCodeParams(this.$router.params.scene)
        }

        // 执行埋点
        this._$_dataLoadPromise.then(this._track.bind(this))

        if (super.componentWillMount) {
          super.componentWillMount();
        }
      }

      componentDidHide() {
        // 埋点
        if (isFunction(this._$_trackOverFn)) {
          this._$_trackOverFn()
          this._$_trackOverFn = undefined
        }

        if (super.componentDidHide) {
          super.componentDidHide();
        }
      }

      componentWillUnmount() {
        // 埋点
        if (isFunction(this._$_trackOverFn)) {
          this._$_trackOverFn()
          this._$_trackOverFn = undefined
        }

        if (super.componentWillUnmount) {
          super.componentWillUnmount();
        }
      }

      async _track() {
    
        // 埋点
        let trackPayload = opts.track || {}

        if (isFunction(this._$_track)) {
          trackPayload = {
            ...trackPayload,
            ...this._$_track(),
          }
        }
        const { recordId } = await savePoint(trackPayload)

        this._$_trackOverFn = () => updatePoint(recordId)
      }
    }

    return WrapperComponent
  }
}
