OneKeyLoginPage.ets 9.21 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 '../../../../../../../products/phone/src/main/ets/pages/viewModel/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) {
          Logger.debug("HuaweiOneKeyAuth", "onClickLoginWithHuaweiIDButton error: " + JSON.stringify(error))
          this.toastText = "请阅读并勾选用户协议、隐私政策和华为账号用户认证协议"
          this.dialogToast.open()
          return;
        }
        if (response) {
          // 获取到Authorization Code
          let authorizationCode = response.authorizationCode;
          // hilog.info(0x0000, 'testTag', 'response: %{public}s', JSON.stringify(response));
          TrackingButton.click("oneClickLoginPageLoginButton", this.pageName, this.pageName)
          this.requestLogin()
          return;
        }
      });

  // 埋点计算页面浏览时长
  private pageStartDate: number = 0
  private pageName = TrackConstants.PageName.OneClick_Login

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

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

  onPageHide(): void {
    const duration = (Date.now() - this.pageStartDate!)
    TrackingPageBrowse.trackCommonPageExposureEnd(this.pageName, this.pageName, 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(120)
        .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()

      Button("账号密码登录")
        .type(ButtonType.Normal)
        .align(Alignment.Center)
        .foregroundColor("#666666")
        .backgroundColor(Color.White)
        .height(26)
        .margin({top: 20})
        .onClick((event) => {
          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
      })
    }
    .height(48)
    .margin({ top: 20 ,left: 25, right: 25 })
  }

  // @Builder loginButton() {
  //   Row() {
  //     Button() {
  //       Row() {
  //         Image($r("app.media.huawei_one_key_login_icon"))
  //           .width(24).height(24)
  //         Text("华为账号一键登录")
  //           .fontColor(Color.White)
  //       }
  //     }
  //     .type(ButtonType.Normal)
  //     .height(48)
  //     .backgroundColor(!this.agreeProtocol ? "#60ED2800" : "#ED2800")
  //     .width("100%")
  //     .onClick((event) => {
  //       if (!this.agreeProtocol) {
  //         return
  //       }
  //
  //       TrackingButton.click("oneClickLoginPageLoginButton", this.pageName, this.pageName)
  //       this.requestLogin()
  //     })
  //   }
  //   .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() {
    try {
      let authorizeCode = await HuaweiAuth.sharedInstance().requestProfile()

      let data = await this.viewModel.huaweiOneKeyLogin(authorizeCode)

      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(){
    this.viewModel.queryUserDetail().then(()=>{
      router.back({
        url: `${WDRouterPage.getBundleInfo()}`
      }
      )
    }).catch(()=>{
      router.back({
        url: `${WDRouterPage.getBundleInfo()}`
      })
    })
  }
}