import { common } from '@kit.AbilityKit';
import { advertising } from '@kit.AdsKit';
import { router } from '@kit.ArkUI';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { emitter } from '@kit.BasicServicesKit';
import { YTLog } from '../../../../Index';
import { AppStorageKeyCollect } from '../constants';

export enum AdType {
  // 开屏广告的类型
  SPLASH_AD = 1
}

export class JhStartAd {
  // 鲸鸿开屏广告的单例
  private static declare instance: JhStartAd
  private declare context: common.UIAbilityContext
  private oaid: string = '';
  private isTimeOut: boolean = false;
  // 超时时间(单位毫秒)，开发者可根据实际情况修改
  private timeOutDuration: number = 1 * 1000;
  // 超时index
  private timeOutIndex: number = -1;
  // 广告展示参数
  private declare ads: Array<advertising.Advertisement>
  private adDisplayOptions: advertising.AdDisplayOptions = {
    // 是否静音，默认不静音
    mute: false
  }
  // 广告配置
  private adOptions: advertising.AdOptions = {
    // 是否允许流量下载0：不允许，1：允许，不设置以广告主设置为准
    allowMobileTraffic: 0,
    // 是否希望根据 COPPA 的规定将您的内容视为面向儿童的内容: -1默认值，不确定 0不希望 1希望
    tagForChildProtection: -1,
    // 是否希望按适合未达到法定承诺年龄的欧洲经济区 (EEA) 用户的方式处理该广告请求： -1默认值，不确定 0不希望 1希望
    tagForUnderAgeOfPromise: -1,
    // 设置广告内容分级上限: W: 3+,所有受众 PI: 7+,家长指导 J:12+,青少年 A: 16+/18+，成人受众
    adContentClassification: 'A'
  }
  // 开屏视频广告请求参数
  private splashVideoAdReqParams: advertising.AdRequestParams = {
    // 'testd7c5cewoj6'为测试专用的广告位ID，App正式发布时需要改为正式的广告位ID
    adId: 'testd7c5cewoj6',
    adType: AdType.SPLASH_AD,
    adCount: 1,
    oaid: this.oaid
  }
  // 开屏图片广告请求参数
  private splashImageAdReqParams: advertising.AdRequestParams = {
    // 'testq6zq98hecj'为测试专用的广告位ID，App正式发布时需要改为正式的广告位ID
    adId: 'testq6zq98hecj',
    adType: AdType.SPLASH_AD,
    adCount: 1,
    oaid: this.oaid
  }

  //进一步优化单例 使外部无法创建实例
  private constructor() {
  }

  //获取单例
  static getInstance() {
    if (!JhStartAd.instance) {
      JhStartAd.instance = new JhStartAd()
    }
    return JhStartAd.instance
  }

  init(UIContext: common.UIAbilityContext, oaid: string) {
    this.context = UIContext
    this.oaid = oaid
    this.requestAd(this.splashImageAdReqParams, this.adOptions)

  }

  private requestAd(adReqParams: advertising.AdRequestParams, adOptions: advertising.AdOptions): void {
    // 广告请求回调监听
    const adLoaderListener: advertising.AdLoadListener = {
      // 广告请求失败回调
      onAdLoadFailure: (errorCode: number, errorMsg: string) => {
        clearTimeout(this.timeOutIndex);
        YTLog.error(errorCode + ':' + errorMsg)

        if (this.isTimeOut) {
          return;
        }
        emitter.emit('adLoadFail')
      },
      // 广告请求成功回调
      onAdLoadSuccess: (ads: Array<advertising.Advertisement>) => {
        clearTimeout(this.timeOutIndex);
        if (this.isTimeOut) {
          return;
        }
        YTLog.info('广告加载成功')
        if (canIUse("SystemCapability.Advertising.Ads")) {
          this.ads = ads
          AppStorage.setOrCreate(AppStorageKeyCollect.AD_IS_LOADED, true)
        }
      }
    };
    // 创建AdLoader广告对象
    const load: advertising.AdLoader = new advertising.AdLoader(this.context);
    // 调用广告请求接口
    this.timeOutHandler();
    load.loadAd(adReqParams, adOptions, adLoaderListener);
  }

  private timeOutHandler(): void {
    this.isTimeOut = false;
    // 超时处理
    this.timeOutIndex = setTimeout(() => {
      this.isTimeOut = true;
      const options: router.RouterOptions = {
        // 开发者可根据项目实际情况修改超时之后要跳转的目标页面
        url: 'pages/Index',
      };
      router.pushUrl(options);
      hilog.error(0x0000, 'testTag', '%{public}s', 'load ad time out');
    }, this.timeOutDuration);
  }
}

export const jHStartAd = JhStartAd.getInstance()

