let _ADRootService = null;
try {
  const { ADRootService } = requirePlugin('adbright-ad')
  _ADRootService = ADRootService
} catch (error) {
  
}



class ADService extends _ADRootService {
  constructor (config) {
    super(config)
    this.__modules = {}
  }

  // 请求
  sendRequest ({
    url,
    data,
    header = { 'content-type': 'application/x-www-form-urlencoded' },
    timeout = 30000,
    method = 'GET',
    dataType = 'json'
  }) {
    return new Promise((resolve, reject) => {
      wx.request({
        url,
        data,
        header,
        timeout,
        method,
        dataType,
        success (res) {
          if (res.statusCode === 200 && res.data.code === 200) {
            resolve(res.data)
          } else {
            reject(res.data)
          }
        },
        fail (error) {
          reject(error)
        }
      })
    })
  }

  // 请求/曝光/点击上报
  request (opt) {
    return new Promise((resolve, reject) => {
      // 获取网络情况
      wx.getNetworkType().then(({ networkType }) => {
        this.sendRequest(this.addCommonQuery(opt, this.createNetworkParam({ connect_type: networkType }))).then(resolve).catch(reject)
      }).catch(err => {
        console.log(err)
      })
    })
  }

  // 跳转页面
  navigateTo ({ url }) {
    return wx.navigateTo({
      url,
    })
  }

  // 跳转小程序
  navigateToMiniProgram (opt) {
    return wx.navigateToMiniProgram(opt)
  }

  // 添加监听
  addListeners (target) {
    target.listeners = {
      onLoad: () => {},
      onShow: () => {},
      onError: () => {},
      onClose: () => {}
    }
    return target
  }

  // 创建激励视频
  createWeixinMotivation (placementId, weixin, callback) {
    try {
      if (!weixin.unitId) {
        return
      }
      this.destroyMotivation(placementId)
      // 在页面中定义激励视频广告
      let videoAd = null
      // 在页面onLoad回调事件中创建激励视频广告实例
      if (wx.createRewardedVideoAd) {
        videoAd = wx.createRewardedVideoAd({
          adUnitId: weixin.unitId,
          multiton: weixin.multiton || false
        })
        const result = this.addListeners({
          videoAd
        })
        videoAd.onLoad(() => {
          // 回调
          result.listeners.onLoad()
        })
        videoAd.onError((err) => {
          // 回调
          result.listeners.onError(err)
        })
        videoAd.onClose((res) => {
          // 回调
          result.listeners.onClose(res)
        })
        this.__modules[placementId] = result
        typeof callback === 'function' && callback(videoAd)
        return result
      }
    } catch (err) {
      console.log(err)
    }
  }

  // 显示激励视频
  showMotivation (placementId, weixin) {
    try {
      if (this.__modules[placementId]) {
        const videoAd = this.__modules[placementId].videoAd
        const listeners = this.__modules[placementId].listeners
        videoAd.load().then(() => {
          videoAd.show().then(() => {
            console.log('广告显示1')
            // 回调
            listeners.onShow()
          }).catch(() => {
            console.log('videoAd.isReady: ', videoAd.isReady())
            if (videoAd.isReady()) {
              return
            }
            this.showMotivationAgain(placementId)
          })
        }).catch(err => {
          // 回调
          listeners.onError(err)
        })
        return this.__modules[placementId]
      } else if (weixin) {
        return this.createWeixinMotivation(weixin, placementId, () => {
          this.showMotivation(placementId)
        })
      }
    } catch (err) {
      console.log(err)
    }
  }

  // 第二次显示
  showMotivationAgain (placementId) {
    if (this.__modules[placementId]) {
      const videoAd = this.__modules[placementId].videoAd
      const listeners = this.__modules[placementId].listeners
      console.log('videoAd.isReady: ', videoAd.isReady())
      videoAd.load().then(() => {
        videoAd.show().then(() => {
          console.log('广告显示2')
          // 回调
          listeners.onShow()
        }).catch((err) => {
          console.log('videoAd.isReady: ', videoAd.isReady())
          // 回调
          listeners.onError(err)
        })
      }).catch(err => {
        // 回调
        listeners.onError(err)
      })
    }
  }

  // 移除
  destroyMotivation (placementId) {
    const videoAd = this.__modules[placementId]
    if (videoAd) {
      videoAd.videoAd.destory()
      delete this.__modules[placementId]
    }
  }


  // 创建插屏
  createWeixinInterstitial (placementId, weixin, callback) {
    try {
      if (!weixin.unitId) {
        return
      }
      this.destroyInterstital(placementId)
      // 在页面中定义激励视频广告
      let interstitialAd = null
      // 在页面onLoad回调事件中创建激励视频广告实例
      if (wx.createInterstitialAd) {
        interstitialAd = wx.createInterstitialAd({
          adUnitId: weixin.unitId
        })
        const result = this.addListeners({
          interstitialAd
        })
        interstitialAd.onLoad(() => {
          // 回调
          result.listeners.onLoad()
        })
        interstitialAd.onError((err) => {
          // 回调
          result.listeners.onError(err)
        })
        interstitialAd.onClose((res) => {
          // 回调
          result.listeners.onClose(res)
        })
        interstitialAd.load()
        this.__modules[placementId] = result
        typeof callback === 'function' && callback(interstitialAd)
        return result
      }
    } catch (err) {
      console.log(err)
    }
  }

  // 显示
  showInterstital (placementId, weixin) {
    try {
      if (this.__modules[placementId]) {
        const interstitialAd = this.__modules[placementId].interstitialAd
        const listeners = this.__modules[placementId].listeners
        console.log(interstitialAd.getSplashAdShowStatus())
        if (interstitialAd.getSplashAdShowStatus()) {
          interstitialAd.show().then(() => {
            console.log('广告显示1')
            // 回调
            listeners.onShow()
          }).catch(err => {
            // 回调
            listeners.onError(err)
          })
        } else {
          interstitialAd.load().then(() => {
            interstitialAd.show().then(() => {
              console.log('广告显示1')
              // 回调
              listeners.onShow()
            }).catch(err => {
              // 回调
              listeners.onError(err)
            })
          }).catch(err => {
            // 回调
            listeners.onError(err)
          })
        }
        return this.__modules[placementId]
      } else if (weixin) {
        return this.createWeixinInterstitial(weixin, placementId, () => {
          this.showInterstital(placementId)
        })
      }
    } catch (err) {
      console.log(err)
    }
  }

  // 移除
  destroyInterstital (placementId) {
    const interstitialAd = this.__modules[placementId]
    if (interstitialAd) {
      interstitialAd.interstitialAd.destory()
      delete this.__modules[placementId]
    }
  }

}

export default ADService