import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit';
import { KVStore } from '@ohos/common/src/main/ets/utils/KVStore';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
import { AppUtil } from '@pura/harmony-utils';
import { init } from '@dcloudio/uni-app-runtime';
import * as wxopensdk from '@tencent/wechat_open_sdk';
import { emitter } from '@kit.BasicServicesKit';
import {
  EVT_BIND_WX_AUTHOR_SUCCESS,
  EVT_LOGIN_WX_AUTHOR_SUCCESS } from '@ohos/common/src/main/ets/constants/EventConstants';
import { AFServiceCenter } from '@alipay/afservicesdk';
import { WXApi } from '@ohos/common/src/main/ets/viewmodel/CommonService';
import { setWechatAuthCode } from '@ohos/common/src/main/ets/utils/KVManager';
import { Logger } from '@ohos/common';
import { WX_BIND_AUTHOR } from '@ohos/common/src/main/ets/constants/AppConstants';


const DOMAIN = 0x0000;

export default class AppAbility extends UIAbility {

  onCreate(want: Want, _launchParam: AbilityConstant.LaunchParam): void {
    try {
      this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
      AppUtil.init(this.context);
      KVStore.init(this.context);
      this.handleWxResponse(want)
    } catch (err) {
      hilog.error(DOMAIN, 'testTag', 'Failed to set colorMode. Cause: %{public}s', JSON.stringify(err));
    }
    hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');
  }

  onNewWant(want: Want, _launchParam: AbilityConstant.LaunchParam): void {
    // 所有回调（如：微信、支付宝等授权完成）都在这里统一处理：支付宝-com.alipay.mobile.client，微信-
    const callerBundle = want.parameters?.['ohos.aafwk.param.callerBundleName'];
    if(callerBundle === 'com.alipay.mobile.client'){
      //支付宝
      AFServiceCenter.handleResponse(want);
    }else{
      //微信
      this.handleWxResponse(want)
    }

  }

  private handleWxResponse(want: Want) {
    WXApi.handleWant(want, {
      onResp(resp: wxopensdk.BaseResp) {
        // 处理微信回传响应（即授权结果）
        if (resp instanceof wxopensdk.SendAuthResp) {
          if (resp.errCode === 0) {
            Logger.info('LoginWechat', '微信授权回调----->微信授权成功，授权码: ' + resp.code);
            const authCode = resp.code;
            // 保存授权码，用于后续使用
            setWechatAuthCode(authCode)
            const eventData: emitter.EventData = {
              data: { "result": authCode }
            };
            const bindAuthorType = AppStorage.get<number>(WX_BIND_AUTHOR) ?? 0;
            if(bindAuthorType === 1){
              emitter.emit({ eventId: EVT_LOGIN_WX_AUTHOR_SUCCESS }, eventData);
            }else if(bindAuthorType === 2){
              emitter.emit({ eventId: EVT_BIND_WX_AUTHOR_SUCCESS }, eventData);
            }
          } else {
            Logger.info('LoginWechat', '微信授权失败，错误码: ' + resp.errCode);
          }
          AppStorage.setOrCreate<number>(WX_BIND_AUTHOR, 0);
        }
      },

      onReq(req: wxopensdk.BaseReq) {
        // 授权登录场景下，微信通常不会主动向 App 发送 Req，留空即可
        Logger.info('LoginWechat', '收到微信请求: ' + JSON.stringify(req));
      }
    } as wxopensdk.WXApiEventHandler);
  }


  onDestroy(): void {
    // 生命周期管理：销毁
    hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onDestroy');
  }

  onWindowStageCreate(windowStage: window.WindowStage): void {
    // 生命周期管理：主窗口已创建，为此功能设置主页
    //获取主窗口，设置沉浸式
    windowStage.getMainWindow((err, data) => {
      let windowClass: window.Window = data;
      // 1. 设置窗口为全屏模式（沉浸式）
      windowClass.setWindowLayoutFullScreen(true);

      // 2. 设置状态栏文字颜色（白色/黑色）
      let sysBarProps: window.SystemBarProperties = {
        statusBarContentColor: '#000000' // 黑色文字
      };
      windowClass.setSystemBarProperties(sysBarProps);

      // 3. 获取避让区域（状态栏等）
      // 注意：使用 window.AvoidAreaType.TYPE_SYSTEM 明确类型
      let type: window.AvoidAreaType = window.AvoidAreaType.TYPE_SYSTEM;
      let avoidArea: window.AvoidArea = windowClass.getWindowAvoidArea(type);

      // 4. 计算高度并存储 (px2vp 是内置函数，直接使用)
      let statusBarHeight: number = px2vp(avoidArea.topRect.height);

      // 5. 存入全局存储，Key 名为 'statusBarHeight'
      AppStorage.setOrCreate<number>('statusBarHeight', statusBarHeight);
    });

    hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
    init(this, windowStage, {
      debug: true
    })


    // 加载页面(启动页)
    windowStage.loadContent('pages/SplashScreenPage', (err) => {
      if (err.code) {
        hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err));
        return;
      }
      hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.');
    });
  }

  onWindowStageDestroy(): void {
    // 生命周期管理：主窗口已销毁，释放与UI相关的资源
    hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
  }

  onForeground(): void {
    // 生命周期管理：已处于前台页面
    hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground');
  }

  onBackground(): void {
    // 生命周期管理：已处于后台页面
    hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onBackground');
  }
}