import window from '@ohos.window';
import { AbilityConstant, Want } from '@kit.AbilityKit';
import { SetToGlobalThis } from 'tuanjieLib';
import { TuanjiePlayerAbilityBase } from 'tuanjieLib';
import { fastSdk, InitResult, LogUtil, WindowVersionCompat } from 'fastsdk';
import { processMgr } from 'fastsdk/src/main/ets/utils/PageManager';
import { LoginResult } from 'fastsdk/src/main/ets/model/LoginResult';
import { GoodsInfo } from 'fastsdk/src/main/ets/model/GoodsInfo';

export default class TuanjiePlayerAbility extends TuanjiePlayerAbilityBase {
  uiContext?: UIContext;
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    this.setConfig();
    super.onCreate(want, launchParam);
    //fastsdk相关方法
    fastSdk.onCreate(want, launchParam, this.context);
  }

  onDestroy(): void {
    super.onDestroy();
    fastSdk.onDestory();
  }

  onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    super.onNewWant(want, launchParam);
    fastSdk.onNewWant(want, launchParam);
  }

  onWindowStageCreate(windowStage: window.WindowStage): void {
    super.setPageUri('pages/Index');
    super.onWindowStageCreate(windowStage);
    // 调用工具类获取UIContext（屏蔽版本差异）
    WindowVersionCompat.getInstance().getUIContextAfterLoadContent(
      windowStage,
      (uiContext: UIContext) => {
        // 获取UIContext成功，初始化SDK
        this.uiContext = uiContext;
        fastSdk.loadContentSuccess(windowStage);
        this.register();
        fastSdk.initSDK();
      },
      (errorMsg: string) => {
        // 获取失败的兜底处理
        LogUtil.error(errorMsg);
      }
    );
  }

  onWindowStageDestroy(): void {
    super.onWindowStageDestroy();
  }

  onForeground(): void {
    super.onForeground();
  }

  onBackground(): void {
    super.onBackground();
  }

  setConfig(): void {
    SetToGlobalThis("staticSplashScreenFit", $r('app.integer.StaticSplashScreenFit'));
    SetToGlobalThis("appSplash", $r('app.media.app_splash'));
    SetToGlobalThis("showStaticSplash", $r('app.integer.ShowStaticSplashScreen'));
  }

  private register(): void {
    fastSdk.hlSystemListener = {
      onInitSuccess: (result: InitResult) => {
        LogUtil.info('初始化成功:' + JSON.stringify(result));

      },
      onInitFailed: (reason: string) => {
        LogUtil.error('初始化失败:' + reason);
      },
      onCustomExit: () => {
        LogUtil.info('自定义退出流程触发');
        this.uiContext?.showAlertDialog({
          title: '自定义退出',
          message: '确定退出游戏？',
          autoCancel: true,
          alignment: DialogAlignment.Center,
          buttons: [{
            value: "再玩一会",
            action: () => {
              LogUtil.info("点击了再玩一会");
            }
          }, {
            enabled: true,
            defaultFocus: true,
            style: DialogButtonStyle.HIGHLIGHT,
            value: '确定退出',
            action: () => {
              //自定义退出弹窗
              LogUtil.info('自定义退出成功');
              fastSdk.hlSystemListener?.onExitSuccess("");
            }
          }]
        })
      },
      onExitSuccess: (result: string) => {
        LogUtil.info('退出成功:' + result);
        processMgr.exit(0)
      }
    };
    fastSdk.hlAccountListener = {
      onRefreshUser: (result: LoginResult): void => {
        //暂不使用
      },
      onLoginSuccess: (result: LoginResult): void => {
        LogUtil.info('登录成功:' + JSON.stringify(result));
      },
      onLoginFailed: (reason: string): void => {
        LogUtil.info('登录失败:' + reason);
      },
      onLogout: (): void => {
        LogUtil.info('已登出');
      }
    };

    fastSdk.hlPaymentListener = {
      onPaySuccess: (result: string): void => {
        LogUtil.info(`支付成功:${result}`);
      },
      onPayFailed: (reason: string): void => {
        LogUtil.info(`支付失败:${reason}`);
      },
      onQuerySuccess: (products: GoodsInfo[]): void => {
        //暂不使用
      }
    }
  }
}


// @Aspect
// export class LoadContentAop {
//   // 拦截WindowStage.prototype.loadContent方法
//   @Around('execution(* Window.WindowStage.loadContent(..))')
//   interceptLoadContent(jp: JoinPoint) {
//     console.log('子类AOP：父类即将调用loadContent方法');
//     try {
//       // 执行原方法（父类的loadContent调用）
//       const result = jp.proceed();
//       // 方法调用完成（同步结果，实际UI渲染是异步）
//       console.log('子类AOP：父类loadContent方法调用完成，结果：', result);
//       return result;
//     } catch (err) {
//       // 捕获方法调用异常
//       console.error('子类AOP：父类loadContent方法调用失败', err);
//       throw err;
//     }
//   }
// }