<template>
  <IxForm :control="pwdFormData" class="modify_pwd-form" @submit.prevent="modifyPwdHandler">
    <IxFormItem messageTooltip>
      <IxPwdInput control="oldPwd" placeholder="旧密码"/>
    </IxFormItem>
    <IxFormItem class="mima-input" messageTooltip>
      <IxPwdInput control="newPwd" placeholder="新密码"/>
    </IxFormItem>
    <IxFormItem class="mima-input" messageTooltip>
      <IxPwdInput control="confirmPwd" placeholder="确认新密码"/>
    </IxFormItem>
    <IxFormItem>
      <IxButton block mode="primary" type="submit">确定</IxButton>
    </IxFormItem>
  </IxForm>
</template>

<script lang="ts" setup>
import {
  AbstractControl,
  useFormGroup,
  ValidateErrors,
  Validators
} from '@idux/cdk'
import HeaderBarApi from '@/pages/main-zone/header-bar/header-bar-api.ts'
import Toast from '@/components/toast'

const pwdFormData = useFormGroup<{
  oldPwd: string
  newPwd: string
  confirmPwd: string
}>(
    {
      oldPwd: [ '', Validators.required ],
      newPwd: [ '', Validators.required ],
      confirmPwd: [ '', [ Validators.required, (value: string, control: AbstractControl): ValidateErrors | undefined => {
        return value === control.root.get('newPwd')?.getValue() ? undefined : {confirmPwd: {message: '两次密码不一致'}}
      } ] ],
    },
)

function modifyPwdHandler() {
  if (!pwdFormData.valid.value) {
    pwdFormData.markAsDirty()
    return
  }
  const {oldPwd: oldPasswd, newPwd: newPasswd} = pwdFormData.getValue()
  HeaderBarApi.modifyPasswd({oldPasswd, newPasswd})
      .then(() => {
        Toast.success('修改成功')
      })
      .finally(() => {
        pwdFormData.reset()
        pwdFormData.markAsPristine()
      })
}
</script>

<style lang="stylus" scoped>
.modify_pwd-form {
  padding: 1rem 0;
  height 100%
  display grid
  grid-template-columns 80%
  grid-template-rows 1fr 1fr 1fr 1fr
  justify-content center
  align-content: space-evenly
}

</style>
