ChangeBindPhonePage.ets 8.12 KB
import { SpConstants } from 'wdConstant/Index'
import { CustomToast, Logger, NetworkUtil, ToastUtils, SPHelper, EmitterEventId,
  DateTimeUtils } from 'wdKit/Index'
import { LoginViewModel } from './LoginViewModel'
import { router } from '@kit.ArkUI'
import { emitter } from '@kit.BasicServicesKit'
import { TrackingPageBrowse, TrackConstants, TrackingButton } from 'wdTracking/Index'

const TAG = 'ChangeBindPhonePage'
/*更换手机号页面*/
@Entry
@Component
struct ChangeBindPhonePage {
  @State phoneContent: string = ''
  @State codeContent: string = ''
  @State isSubmit: boolean = false //是否可以提交  默认不可以
  loginViewModel: LoginViewModel = new LoginViewModel()
  @State @Watch('onCodeSend') isCodeSend: boolean = false //验证码点击发送事件
  @State pageTitle:string = '更换手机号';
  @State @Watch('startCount') codeStateSuccess:boolean=false
  @State codeBtnState: boolean = false
  @State timeCount: number = 60
  isFirst:boolean=true//是否第一次获取验证码
  lastTime: number = 0
  pageShowTime:number = 0;
  pageHideTime:number = 0;
  @State topSafeHeight: number = AppStorage.get<number>('topSafeHeight') || 0
  @State bottomSafeHeight: number = AppStorage.get<number>('bottomSafeHeight') || 0


  onPageShow() {
    this.pageShowTime = DateTimeUtils.getTimeStamp()
  }

  onPageHide(): void {
    this.pageHideTime = DateTimeUtils.getTimeStamp()
    let duration = 0
    duration = Math.floor((this.pageHideTime - this.pageShowTime)/1000)
    TrackingPageBrowse.trackCommonPageExposureEnd(TrackConstants.PageName.Change_PhoneNum,TrackConstants.PageName.Change_PhoneNum,duration)
  }

  onCodeSend() {
    if (this.isCodeSend) {
      TrackingButton.click("changePhoneNumberPageSendVerificationCode",TrackConstants.PageName.Change_PhoneNum,TrackConstants.PageName.Change_PhoneNum)
      this.sendVerifyCode()
    }
  }

  @State toastText:string = ""
  dialogToast: CustomDialogController = new CustomDialogController({
    builder: CustomToast({
      msg: this.toastText,
    }),
    autoCancel: false,
    alignment: DialogAlignment.Center,
    customStyle: true,
    maskColor:"#00000000"
  })



  build() {
    Column(){
      Column() {
        Image($r('app.media.login_back_icon'))
          .width(24)
          .height(24)
          .margin({ left: 16, top: 8 })
          .onClick(() => {
          router.back()
        })

        Text(this.pageTitle)
          .fontSize(22)
          .lineHeight(32)
          .fontColor('#222222')
          .fontWeight(600)
          .margin({ left: 25, top: 112 })

        Column(){
          TextInput({text: this.phoneContent, placeholder: "请输入手机号" })
            .fontSize(16)
            .lineHeight(24)
            .height(48)
            .placeholderColor("#CCCCCC")
            .maxLength(11)
            .margin({ top: 40 })
            .backgroundColor("#F5F5F5")
            .borderRadius(4)
            .type(InputType.Number)
            .onChange((content) => {
              this.phoneContent = content
              this.isSubmit = (this.phoneContent.length >= 11 && this.codeContent.length >= 4)

              if (content.length >= 11 ) {
                this.codeBtnState = true
              } else {
                this.codeBtnState = false
              }
            })


          Row() {
            TextInput({ text: this.codeContent,placeholder: "验证码" })
              .placeholderColor("#CCCCCC")
              .layoutWeight(1)
              .fontSize(16)
              .lineHeight(24)
              .height(48)
              .type(InputType.Number)
              .fontColor("#222222")
              .backgroundColor("#00000000")
              .borderRadius({ topLeft: 4, bottomLeft: 4 })
              .onChange((value) => {
                this.codeContent = value
                this.isSubmit = (this.phoneContent.length >= 11 && this.codeContent.length >= 4)
              })

            Text(this.codeStateSuccess ? this.timeCount + "s" : this.isFirst?"发送验证码":'重新获取')
              .fontColor(this.codeBtnState?'#ED2800':'#80ED2800')
              .width(110)
              .fontSize(14)
              .lineHeight(24)
              .fontWeight( FontWeight.Bold)
              .height(48)
              .textAlign(TextAlign.Center)
              .enabled(this.codeStateSuccess?false:true)
              .onClick(() => {
                if (this.phoneContent.length < 11) {
                  return
                }

                let currentTime = DateTimeUtils.getTimeStamp()
                if (currentTime - this.lastTime < 500) {
                  return
                }
                this.lastTime = currentTime;
                this.isCodeSend = true

              })


          }.margin({ top: 12 })
          .height(48)
          .alignItems(VerticalAlign.Center)
          .justifyContent(FlexAlign.Start)
          .backgroundImage($r('app.media.code_login_bg'))
          .backgroundImageSize({width:'100%',height:48})
        }.width('100%')
        .padding({ left: 25, right: 25 })


        Row() {
          Text("确认")
            .layoutWeight(1)
            .fontColor("#FFFFFF")
            .borderRadius(4)
            .fontSize(18)
            .lineHeight(26)
            .textAlign(TextAlign.Center)
            .fontWeight(FontWeight.Medium)
            .margin({ top: 36 })
            .height(44)
            .backgroundColor("#ED2800")
            .enabled(this.isSubmit ? true : false)
            .opacity(this.isSubmit ? 1: 0.6)
            .onClick(() => {
              TrackingButton.click("changePhoneNumberPageConfirm",TrackConstants.PageName.Change_PhoneNum,TrackConstants.PageName.Change_PhoneNum)
              this.changeBindPhone()
            })
        }.width('100%')
        .padding({ left: 25, right: 25 })

      }.width('100%').height('100%').alignItems(HorizontalAlign.Start)
    }.width("100%")
    .height("100%")
    .padding({top:px2vp(this.topSafeHeight),bottom:px2vp(this.bottomSafeHeight)})

  }

  //发送验证码
  sendVerifyCode() {
    if (this.isEmpty(this.phoneContent)) {
      return
    }

    this.loginViewModel.sendVerifyCode(this.phoneContent).then((verifyCode) => {
      this.showToastTip("已发送")
      this.codeStateSuccess=true
      this.isCodeSend=false
      Logger.debug(TAG, "sendVerifyCode: " + verifyCode)
    }).catch((message: string)=>{
      let netStatus = NetworkUtil.isNetConnected()
      if (netStatus) {
        this.showToastTip(message)
      } else {
        this.showToastTip("验证码获取失败,请重新尝试")
      }
      this.codeStateSuccess=false
      this.isCodeSend=false
    })
  }

  isEmpty(obj: undefined|null|string): boolean {
    return (obj == undefined || obj == null || obj == '');
  }

  changeBindPhone(){
    if (!this.isSubmit) {
      return
    }
    if (this.isEmpty(this.phoneContent)) {
      return
    }
    if (this.isEmpty(this.codeContent)) {
      return
    }
    this.loginViewModel.changeBindPhone(this.phoneContent,this.codeContent).then(()=>{
      ToastUtils.shortToast('绑定成功')
      this.querySecurity()
    }).catch((message: string) => {
      if (message != '') {
        ToastUtils.shortToast(message)
      }
    })
  }

  querySecurity(){
    this.loginViewModel.querySecurity().then(()=>{
      SPHelper.default.save(SpConstants.USER_PHONE,this.phoneContent)
      this.sendEmitEvent()
      router.back()
    }).catch(()=>{

    })
  }

  sendEmitEvent(){
    // 定义一个eventId为1的事件,事件优先级为Low
    let event: emitter.InnerEvent = {
      eventId: EmitterEventId.PHONE_CHANGE_SUCCESS,
      priority: emitter.EventPriority.LOW
    };

    let eventData: emitter.EventData = {
      data: {
        content: this.phoneContent,
      }
    };

    // 发送eventId为1的事件,事件内容为eventData
    emitter.emit(event, eventData);
  }

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

  startCount() {
    this.isFirst = false
    let time = setInterval(() => {
      Logger.debug("倒计时:" + this.timeCount)
      this.timeCount--
      if (this.timeCount < 1) {
        this.codeStateSuccess = false
        this.timeCount = 60
        clearInterval(time)
      }
    }, 1000)
  }
}