OneKeyLoginPage.ets 10.2 KB
import { router } from '@kit.ArkUI'
import { Params } from 'wdBean/Index'
import { WDRouterPage, WDRouterRule } from 'wdRouter/Index'
import HuaweiAuth from '../../utils/HuaweiAuth'
import { BusinessError } from '@kit.BasicServicesKit'
import { Logger, ToastUtils, CustomToast, EmitterUtils, EmitterEventId } from 'wdKit/Index'
import { LoginViewModel } from './LoginViewModel'
import {InterestsHobbiesModel} from '../../bean/InterestsHobbiesModel'
import { TrackConstants, TrackingButton, TrackingPageBrowse } from 'wdTracking/Index'
import { loginComponentManager, LoginWithHuaweiIDButton } from '@kit.AccountKit'
import { JSON } from '@kit.ArkTS'

const TAG = "OneKeyLoginPage"

@Entry
@Component
struct OneKeyLoginPage {
  @State topSafeHeight: number = AppStorage.get<number>('topSafeHeight') || 0
  anonymousPhone: string = ''
  @State agreeProtocol: boolean = false
  viewModel: LoginViewModel = new LoginViewModel()
  @State toastText:string = ""
  dialogToast: CustomDialogController = new CustomDialogController({
    builder: CustomToast({
      msg: this.toastText,
    }),
    autoCancel: false,
    alignment: DialogAlignment.Center,
    offset: { dx: 0, dy: -20 },
    gridCount: 1,
    customStyle: true,
    maskColor:"#00000000"
  })
  // 构造LoginWithHuaweiIDButton组件的控制器。
  controller: loginComponentManager.LoginWithHuaweiIDButtonController =
    new loginComponentManager.LoginWithHuaweiIDButtonController()
      /**
       * 当应用使用自定义的登录页时,如果用户未同意协议,需要设置协议状态为NOT_ACCEPTED,当用户同意协议后再设置
       * 协议状态为ACCEPTED,才可以使用华为账号一键登录功能。
       */
      .setAgreementStatus(loginComponentManager.AgreementStatus.NOT_ACCEPTED)
      .onClickLoginWithHuaweiIDButton((error: BusinessError, response: loginComponentManager.HuaweiIDCredential) => {
        if (error || !response) {
          Logger.debug("HuaweiOneKeyAuth", "onClickLoginWithHuaweiIDButton error: " + JSON.stringify(error))
          if (!this.agreeProtocol) {
            this.showToastTip("请阅读并勾选用户协议、隐私政策和华为账号用户认证协议")
            return
          }
          this.showToastTip("登录失败")
          return;
        }

        // 获取到Authorization Code
        let authorizationCode = response.authorizationCode;
        Logger.debug("HuaweiOneKeyAuth", "第一次授权码: " + authorizationCode)
        // hilog.info(0x0000, 'testTag', 'response: %{public}s', JSON.stringify(response));
        TrackingButton.click("oneClickLoginPageLoginButton", TrackConstants.PageName.OneClick_Login, TrackConstants.PageName.OneClick_Login)
        this.requestLogin(authorizationCode)
      });

  // 埋点计算页面浏览时长
  private pageStartDate: number = 0

  aboutToAppear(): void {
    this.anonymousPhone = HuaweiAuth.sharedInstance().anonymousPhone||""
  }

  onPageShow(): void {
    this.pageStartDate = Date.now()
  }

  onPageHide(): void {
    const duration = Math.floor((Date.now() - this.pageStartDate!)/1000)
    TrackingPageBrowse.trackCommonPageExposureEnd(TrackConstants.PageName.OneClick_Login, TrackConstants.PageName.OneClick_Login, duration)
  }

  // pageTransition() {
  //   // 为目标页面时,进入:从右边侧滑入,退出:是右侧划出;跳转别的页面:左侧划出,返回:左侧划入。
  //   PageTransitionEnter({ type: RouteType.Push, duration: 300 })
  //     .slide(SlideEffect.Right)
  //   PageTransitionEnter({ type: RouteType.Pop, duration: 300 })
  //     .slide(SlideEffect.Left)
  //   PageTransitionExit({ type: RouteType.Push, duration: 300 })
  //     .slide(SlideEffect.Left)
  //   PageTransitionExit({ type: RouteType.Pop, duration: 300 })
  //     .slide(SlideEffect.Right)
  // }

  build() {
    Column() {
      this.CloseRow()

      Image($r("app.media.login_logo"))
        .width(155)
        .height(66)
        .margin({ top: 34, bottom: 64})
        .align(Alignment.Center)

      Text(this.anonymousPhone)
        .fontSize(30)
        .fontWeight(600)
        .fontColor("#222222")
        .margin({bottom: 12})
        .align(Alignment.Center)

      Text("华为账号绑定号码")
        .fontSize(12)
        .fontWeight(400)
        .fontColor("#999999")
        .margin({bottom: 40})
        .align(Alignment.Center)

      this.ProtocolRow()

      this.loginButton()

      Text("账号密码登录")
        .fontColor("#666666")
        .height(26)
        .width(100)
        .margin({top: 20})
        .onClick(() => {
          router.replaceUrl({url: WDRouterPage.loginPage.url()})
        })
    }
    .backgroundColor("#FFFFFF")
    .padding({top: `${this.topSafeHeight}px`})
  }

  // @Builder loginButton() {
  //   Column() {
  //     LoginWithHuaweiIDButton({
  //       params: {
  //         // LoginWithHuaweiIDButton支持的样式。
  //         style: loginComponentManager.Style.BUTTON_CUSTOM,
  //         // LoginWithHuaweiIDButton的边框圆角半径。
  //         borderRadius: 4,
  //         // LoginWithHuaweiIDButton支持的登录类型。
  //         loginType: loginComponentManager.LoginType.QUICK_LOGIN,
  //         // LoginWithHuaweiIDButton支持按钮的样式跟随系统深浅色模式切换。
  //         supportDarkMode: true,
  //         customButtonParams: {
  //           fontColor: loginComponentManager.FontColor.WHITE,
  //           // backgroundColor:!this.agreeProtocol ? "#60ED2800" : "#ED2800"
  //           backgroundColor:"#ED2800"
  //         }
  //       },
  //       controller: this.controller
  //     })
  //   }
  //   .backgroundColor("#ED2800")
  //   .height(48)
  //   .margin({ top: 20 ,left: 25, right: 25 })
  // }

  @Builder loginButton() {
    Row() {
      Stack(){
        Button() {
          Row() {
            // Image($r("app.media.huawei_one_key_login_icon"))
            //   .width(24).height(24)
            Text("华为账号一键登录")
              .fontColor(Color.White)
              // .margin({left:5})
          }
        }
        .width('100%')
        .height(48)
        .borderRadius(4)
        .type(ButtonType.Normal)
        .backgroundColor(!this.agreeProtocol ? "#60ED2800" : "#ED2800")

        Stack(){
          //目前不支持文字和图标同时展示,后面优化
              LoginWithHuaweiIDButton({
                params: {
                  // LoginWithHuaweiIDButton支持的样式。
                  style: loginComponentManager.Style.BUTTON_CUSTOM,
                  // LoginWithHuaweiIDButton的边框圆角半径。
                  // borderRadius: 4,
                  // LoginWithHuaweiIDButton支持的登录类型。
                  loginType: loginComponentManager.LoginType.QUICK_LOGIN,
                  // LoginWithHuaweiIDButton支持按钮的样式跟随系统深浅色模式切换。
                  // supportDarkMode: true,
                  customButtonParams: {
                    fontColor: loginComponentManager.FontColor.WHITE,
                    // backgroundColor:!this.agreeProtocol ? "#60ED2800" : "#ED2800"
                    backgroundColor:"#ED2800"
                  }
                },
                controller: this.controller
              }).opacity(0)
        }
        .width('100%')
        .height('100%')
      }
    }
    .height(48)
    .width("100%")
    .padding({ left: 25, right: 25 })
    .margin({top: 20})
  }

  @Builder ProtocolRow() {
    Row({space: 4}) {
      Image(this.agreeProtocol ? $r('app.media.login_checkbox_select') : $r('app.media.login_checkbox_unselected'))
        .width(15)
        .height(15)
        .margin({top: 3})
        .onClick(() => {
          this.agreeProtocol = !this.agreeProtocol
          if (this.agreeProtocol) {
            this.controller.setAgreementStatus(loginComponentManager.AgreementStatus.ACCEPTED)
          } else {
            this.controller.setAgreementStatus(loginComponentManager.AgreementStatus.NOT_ACCEPTED)
          }
        })
      Text() {
        Span("我已阅读并同意").fontColor("#999999").fontSize(12).lineHeight(18)
        Span("《用户协议》").fontColor("#ED2800").fontSize(12).lineHeight(18).onClick(() => {
          let bean = { contentID: "1", pageID: "" } as Params
          WDRouterRule.jumpWithPage(WDRouterPage.loginProtocolPage, bean)
        })
        Span("、").fontColor("#999999").fontSize(12).lineHeight(18)
        Span("《隐私政策》").fontColor("#ED2800").fontSize(12).lineHeight(18).onClick(() => {
          let bean = { contentID: "2", pageID: "" } as Params
          WDRouterRule.jumpWithPage(WDRouterPage.loginProtocolPage, bean)
        })
        Span("及").fontColor("#999999").fontSize(12).lineHeight(18)
        Span("《华为账号用户认证协议》").fontColor("#ED2800").fontSize(12).lineHeight(18).onClick(() => {
          let bean = { contentID: "4", pageID: "" } as Params
          WDRouterRule.jumpWithPage(WDRouterPage.loginProtocolPage, bean)
        })
      }
      .layoutWeight(1)
    }
    .alignItems(VerticalAlign.Top)
    .margin({top: 15})
    .padding({ left: 25, right: 25 })
    .width('100%')
  }

  @Builder CloseRow() {
    Row() {
      Blank()
      Image($r('app.media.login_closed'))
        .width(24)
        .height(24)
        .onClick(() => router.back())
    }.margin({ top: 10, right: 16 })
    .width("100%")
    .height(44)
  }

  async requestLogin(phoneAuthorizedCode: string) {
    try {
      let data = await this.viewModel.huaweiOneKeyLogin(phoneAuthorizedCode)

      Logger.debug(TAG, "requestLogin: " + data.jwtToken)
      this.showToastTip('登录成功')

      ///同步兴趣tag
      let interestsModel = new InterestsHobbiesModel()
      interestsModel.updateInterests()
      this.queryUserDetail()
      EmitterUtils.sendEvent(EmitterEventId.PEOPLE_SHIP_ATTENTION)

    } catch (error) {
      if (typeof error == "string") {
        this.showToastTip(error)
      } else {
        (error as BusinessError)
        this.showToastTip("登录失败")
      }
    }
  }

  showToastTip(msg:string){
    this.toastText = msg
    this.dialogToast.open()
  }

  queryUserDetail(){
    // router.back({  url: `${WDRouterPage.getBundleInfo()}` })
    this.viewModel.queryUserDetail().then(()=>{
      router.back()
    }).catch(()=>{
      router.back()
    })
  }
}