import { authentication } from '@kit.AccountKit'
import { util } from '@kit.ArkTS'
import { hilog } from '@kit.PerformanceAnalysisKit'
import { BusinessError } from '@kit.BasicServicesKit'
import { YTLog } from '../../../../Index'

export class HuaweiAuthPlugin {
  // 代替了用户输入用户名密码
  static async requestAuth() {
    // 1. 创建一个Account Kit授权请求对象，可通过返回值设置请求参数。
    const huaweiIdProvider = new authentication.HuaweiIDProvider()
    const authCreateRequest = huaweiIdProvider.createAuthorizationWithHuaweiIDRequest() // 创建华为授权请求
    // 2. 添加请求参数
    // authCreateRequest.scopes = ['phone']
    authCreateRequest.permissions = ['serviceauthcode']
    authCreateRequest.forceAuthorization = true
    // 3. 执行授权请求，获取认证码
    const authController = new authentication.AuthenticationController(getContext())
    const authResponse: authentication.AuthorizationWithHuaweiIDResponse =
      await authController.executeRequest(authCreateRequest) // 执行授权请求
    const authorizationCode = authResponse.data?.authorizationCode // 华为授权code码(有了它 有了用户信息)
    return authorizationCode
  }

  static async getPhoneNumber() {
    // 创建授权请求，并设置参数
    const authRequest = new authentication.HuaweiIDProvider().createAuthorizationWithHuaweiIDRequest();
    // 获取手机号需要传如下scope，传参数之前需要先申请对应scope权限,才能返回对应数据
    authRequest.scopes = ['phone'];
    // 获取code需传如下permission
    authRequest.permissions = ['serviceauthcode'];
    //用户是否需要登录授权，该值为true且用户未登录或未授权时，会拉起用户登录或授权页面
    authRequest.forceAuthorization = true;
    // 用于防跨站点请求伪造
    authRequest.state = util.generateRandomUUID();

    // 执行请求
    try {
      const controller = new authentication.AuthenticationController(getContext());
      controller.executeRequest(authRequest).then((data) => {
        const authorizationWithHuaweiIDResponse = data as authentication.AuthorizationWithHuaweiIDResponse;
        const state = authorizationWithHuaweiIDResponse.state;
        if (state && authRequest.state !== state) {
          hilog.error(0x0000, 'testTag', `Failed to authorize. The state is different, response state: ${state}`);
          return;
        }
        hilog.info(0x0000, 'testTag', 'Succeeded in authentication.');
        const authorizationWithHuaweiIDCredential = authorizationWithHuaweiIDResponse.data!;
        const code = authorizationWithHuaweiIDCredential.authorizationCode;
        const unionID = authorizationWithHuaweiIDCredential.unionID;
        const openID = authorizationWithHuaweiIDCredential.openID;
        // 开发者处理code、unionID、openID
      }).catch((err: BusinessError) => {
        YTLog.error(err)
      });
    } catch (error) {
      YTLog.error(error)
    }
  }

  // getHuaweiIDState  api12 支持

  static async cancelAuth() {
    try {
      // 1. 创建一个Account Kit授权请求对象，可通过返回值设置请求参数。
      const huaweiIdProvider = new authentication.HuaweiIDProvider()
      const authCancelRequest = huaweiIdProvider.createCancelAuthorizationRequest()
      // 2. 取消授权
      const authController = new authentication.AuthenticationController(getContext())
      await authController.executeRequest(authCancelRequest)
      return true
    } catch (e) {
      console.log('yt-logger', JSON.stringify(e))
      return false
    }
  }
}

