LoginPage.ets 11 KB
import { Logger } from 'wdKit/src/main/ets/utils/Logger'
import { CustomProtocolDialog } from './CustomProtocolDialog'
import router from '@ohos.router'
import { LoginViewModel } from './LoginViewModel'
import { LoginInputComponent } from './LoginInputComponent'
import promptAction from '@ohos.promptAction'
import { SPHelper } from 'wdKit'
import { WDRouterPage } from 'wdRouter/src/main/ets/router/WDRouterPage';
import { WDRouterRule } from 'wdRouter/src/main/ets/router/WDRouterRule';
import { Params } from '../../../../../../../commons/wdRouter/oh_modules/wdBean/src/main/ets/bean/content/Params'

@Extend(Row)
function otherStyle() {
  .backgroundImageSize(ImageSize.Cover)
  .layoutWeight(1)
  .height("100%")
  .justifyContent(FlexAlign.Center)
  .alignItems(VerticalAlign.Center)
}

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

const TAG = "LoginPage"

@Entry
@Component
struct LoginPage {
  @State codeBtnState: boolean = false
  @State timeCount: number = 60
  phoneController: TextInputController = new TextInputController()
  codeSendText = ""
  @State @Watch('onCodeSend') isCodeSend: boolean = false //验证码是否发送
  @State phoneContent: string = "" //手机号
  @State codeContent: string = "" //验证码
  @State protocolState: boolean = false //协议勾选状态
  accountContent = '' //账号
  passwordContent = ''
  @State isSubmit: boolean = false
  @State checkCodePage: boolean = true //判断是否是验证码页面 默认验证码登录
  @State passwordSwitch: boolean = true //密码显示
  // @State isPasswordSubmit: boolean = false //账户密码状态 是否出发登录

  dialogController: CustomDialogController = new CustomDialogController({
    builder: CustomProtocolDialog({
      cancel: () => {

      },
      confirm: () => {
        this.requestLogin()
      }
    }),
    customStyle: true,
    alignment:DialogAlignment.Center
  })
  loginViewModel = new LoginViewModel()

  onCodeSend() {
    Logger.debug(TAG, "isCodeSend:" + this.isCodeSend + "")
    if (this.isCodeSend) {
      this.sendVerifyCode()
    }
  }

  aboutToAppear() {
    Logger.debug(TAG, "aboutToAppear:" + this.isCodeSend + "")
  }

  onPageShow() {
    Logger.debug(TAG, "onPageShow:" + this.isCodeSend + "")
  }

  build() {
    RelativeContainer() {

      //注册内容
      Column() {
        Image($r("app.media.login_logo"))
          .width(120)
          .height(66)
          .margin({ top: 78 })
          .align(Alignment.Center)

        if (this.checkCodePage) {
          LoginInputComponent({
            phoneContent: $phoneContent,
            codeContent: $codeContent,
            isSubmit: $isSubmit,
            isCodeSend: $isCodeSend
          })
        } else {
          this.addPassword()
        }


        Row() {
          Image(this.protocolState ? $r('app.media.login_checkbox_select') : $r('app.media.login_checkbox_unselected'))
            .width(15)
            .height(15)
            .onClick(() => {
              this.protocolState = !this.protocolState
            })

          Text() {
            Span("我已阅读并同意").fontColor("#999999").fontSize(12)
            Span("《用户协议》").fontColor("#ED2800").fontSize(12).onClick(() => {
              let bean={contentID:"1",pageID:""} as Params
              WDRouterRule.jumpWithPage(WDRouterPage.loginProtocolPage,bean)
            })
            Span("及").fontColor("#999999").fontSize(12)
            Span("《隐私政策》").fontColor("#ED2800").fontSize(12).onClick(() => {
              let bean={contentID:"2",pageID:""} as Params
              WDRouterRule.jumpWithPage(WDRouterPage.loginProtocolPage,bean)
            })
          }
        }.margin({ top: 48 }).alignItems(VerticalAlign.Center)

        Row() {
          Text("登录")
            .borderRadius(4)
            .fontColor(this.isSubmit ?"#FFFFFFFF":"#66FFFFFF")
            .fontSize(18)
            .fontWeight(FontWeight.Medium)
            .margin({ top: 20 })
            .height(44)
            .textAlign(TextAlign.Center)
            .width("100%")
            .backgroundColor(this.isSubmit?"#FFED2800":"#99ED2800")
            .onClick(() => {
              if(!this.isSubmit){
                return
              }
              this.loginSubmit()

            })
        }.padding({ left: 25, right: 25 }).width('100%')


        if (!this.checkCodePage) {
          Text('忘记密码').fontColor('#666666').fontSize(14).margin({ top: 16 })
            .onClick(() => {
              // router.pushUrl({ url: 'pages/login/ForgetPasswordPage' })
              let pageType = {'pageType': 0} as Record<string, number>;
              WDRouterRule.jumpWithPage(WDRouterPage.forgetPasswordPage, pageType)
            })
        }

      }.width("100%")
      .alignRules({
        top: { anchor: "__container__", align: VerticalAlign.Top },
      }).id("register")

      //其他登录方式
      Column() {
        this.addOtherLogin()
      }.width('100%')
      .alignRules({
        bottom: { anchor: "__container__", align: VerticalAlign.Bottom },
      }).id("other")

      //关闭按钮
      Image($r('app.media.login_closed'))
        .width(24)
        .height(24)
        .margin({ top: 10, right: 15 })
        .alignRules({
          top: { anchor: "__container__", align: VerticalAlign.Top },
          right: { anchor: "__container__", align: HorizontalAlign.End }
        })
        .onClick(() => {
          router.back()
        })
        .id('id_close')

    }.width('100%').height('100%')
  }

  @Builder
  addPassword() {
    Column() {
      TextInput({ placeholder: "请输入账号", controller: this.phoneController })
        .fontSize(16)
        .maxLength(11)
        .height(48)
        .backgroundColor("#F5F5F5")
        .borderRadius(4)
        .type(InputType.PhoneNumber)
        .onChange((content) => {
          this.accountContent = content
          this.isSubmit = (this.accountContent.length >= 11 && this.passwordContent.length >= 6)
        })

      RelativeContainer() {
        if (this.passwordSwitch) {
          this.addPasswordInputLayout()
        } else {
          this.addPasswordInputLayout()
        }

        Image(this.passwordSwitch ? $r('app.media.login_password_off') : $r('app.media.login_password_on'))
          .onClick(() => {
            this.passwordSwitch = !this.passwordSwitch
          })
          .width(24)
          .height(24)
          .alignRules({
            right: { anchor: "__container__", align: HorizontalAlign.End },
            center: { anchor: '__container__', align: VerticalAlign.Center }
          })
          .margin({ right: 12 })
          .id("password_icon")

      }.margin({ top: 12 })
      .height(48)
      .width('100%')
    }.padding({ left: 25, right: 25 }).width('100%').margin({ top: 36 })

  }

  @Builder
  addPasswordInputLayout() {
    TextInput({ placeholder: "请输入密码", text: this.passwordContent })
      .layoutWeight(1)
      .fontSize(16)
      .height(48)
      .fontColor("#222222")
      .backgroundColor("#F5F5F5")
      .type(this.passwordSwitch ? InputType.Password : InputType.Normal)
      .showPasswordIcon(false)
      .borderRadius({ topLeft: 4, bottomLeft: 4 })
      .alignRules({
        // top:{anchor:"__container__",align:VerticalAlign.Top} ,
        left: { anchor: "__container__", align: HorizontalAlign.Start },

      })
      .onChange((value) => {
        // Logger.debug(TAG, "onChange" + value + "/" + this.passwordContent)
        this.passwordContent = value
        this.isSubmit = (this.accountContent.length >= 11 && this.passwordContent.length >= 6)
      })
      .id("password")
  }

  @Builder
  addOtherLogin() {
    Column() {
      Row() {
        Divider().layoutWeight(1).margin({ left: 25 })
        Text('其他登录方式').margin({ left: 16, right: 16 }).fontSize(14).fontColor("#666666")
        Divider().layoutWeight(1).margin({ right: 25 })
      }.width('100%')

      Row() {
        Row() {
          Image($r('app.media.login_wx'))
            .width(20).height(20)
        }.backgroundImage($r('app.media.login_other_left'), ImageRepeat.NoRepeat)
        .otherStyle()

        Row() {
          Image($r('app.media.login_qq')).size({ width: 20, height: 20 })
        }.backgroundImage($r('app.media.login_other_middle'), ImageRepeat.NoRepeat)
        .otherStyle()

        Row() {
          Image($r('app.media.login_wb')).size({ width: 20, height: 20 })
        }.backgroundImage($r('app.media.login_other_middle'), ImageRepeat.NoRepeat)
        .otherStyle()

        Row() {
          Image(this.checkCodePage ? $r('app.media.login_qt') : $r('app.media.login_other_password'))
            .size({ width: 20, height: 20 })
        }.backgroundImage($r('app.media.login_other_right'), ImageRepeat.NoRepeat)
        .otherStyle().onClick(() => {
          this.checkCodePage = !this.checkCodePage;
          this.passwordContent = ''
          this.passwordSwitch = true
          this.isSubmit = false
        })

      }.height(36)
      .width('100%')
      .padding({ left: 25, right: 25 })
      // .justifyContent(FlexAlign.SpaceEvenly)
      .margin({ top: 24 })
    }.width('100%').margin({ bottom: 40 })
  }

  //发送验证码
  sendVerifyCode() {
    this.loginViewModel.sendVerifyCode(this.phoneContent).then((verifyCode) => {
      promptAction.showToast({ message: "验证码已发送成功" })
      Logger.debug(TAG, "sendVerifyCode: " + verifyCode)
    }).catch((message:string)=>{
      Logger.debug(TAG, "sendVerifyCode: " + message)
    })
  }

  requestLogin() {
    Logger.debug('LoginViewModel', "requestLogin")
    if (this.checkCodePage) {
      this.loginViewModel.appLogin(this.phoneContent, 2, this.codeContent).then((data) => {
        Logger.debug(TAG, "requestLogin: " + data.jwtToken)
        router.back({
          params: { userName: data.userName,
            userId:data.id},
          url: `${WDRouterPage.getBundleInfo()}`
        }
        )
      })
    } else {
      this.loginViewModel.appLoginByPassword(this.accountContent, 0, this.passwordContent, "").then((data) => {
        Logger.debug(TAG, "requestLogin: " + data.jwtToken)
        promptAction.showToast({ message: '登录成功' })
        router.back({
          params: { userName: data.userName,
            userId:data.id},
          url: 'pages/MainPage'
        })
      }).catch((value: string) => {
        promptAction.showToast({ message: value })
      })
    }

  }

  //登录
  loginSubmit() {
    Logger.debug(TAG, "loginSubmit " + this.checkCodePage)
    if (this.checkCodePage) {
      if (isEmpty(this.phoneContent)) {
        Logger.debug(TAG, "手机号为空")
        return
      }
      if (isEmpty(this.codeContent)) {
        Logger.debug(TAG, "验证码为空")
        return
      }

    } else {
      if (isEmpty(this.accountContent)) {
        Logger.debug(TAG, "账号为空")
        return
      }
      if (isEmpty(this.passwordContent)) {
        Logger.debug(TAG, "密码为空")
        return
      }
    }
    if (this.protocolState) {
      this.requestLogin()
    } else {
      this.dialogController.open()
    }

  }
}