<script lang="ts" setup>
import {
  ElMessage,
  type FormInstance,
  type FormRules,
} from 'element-plus'
import Strings from '@/common/utils/strings.ts'
import UserApi from '@/pages/sys/user/user-api.ts'

const pwdFormIns = ref<FormInstance>()

interface PwdForm {
  oldPasswd?: string
  newPasswd?: string
  confirmPwd?: string
}

const pwdFormData = reactive<PwdForm>({
  oldPasswd: undefined,
  newPasswd: undefined,
  confirmPwd: undefined,
})

const rules = reactive<FormRules<PwdForm>>({
  oldPasswd: [
    {
      validator(_, value, callback) {
        if (Strings.isBlank(value)) {
          callback(new Error('旧密码不能为空'))
        } else {
          callback()
        }
      }, trigger: 'blur',
    },
  ],
  newPasswd: [
    {
      validator(_, value, callback) {
        if (Strings.isBlank(value)) {
          callback(new Error('新密码不能为空'))
        } else {
          callback()
        }
      }, trigger: 'blur',
    },
  ],
  confirmPwd: [
    {
      validator(_, value, callback) {
        if (Strings.isBlank(value)) {
          callback(new Error('请确认密码'))
        } else if (pwdFormData.newPasswd !== value) {
          callback('两次新密码不一致')
        } else {
          callback()
        }
      }, trigger: 'blur',
    },
  ],
})
const loading = ref<boolean>(false)

function submitHandler() {
  loading.value = true
  pwdFormIns.value?.validate((valid) => {
    if (!valid) {
      ElMessage.error('请填写完信息')
      loading.value = false
      return
    }
    UserApi.modifyPasswd({oldPasswd: pwdFormData.oldPasswd!, newPasswd: pwdFormData.newPasswd!})
      .then(() => {
        ElMessage.success('修改成功')
        pwdFormIns.value?.resetFields()
      })
      .finally(() => {
        loading.value = false
      })
  })
}

defineExpose({
  reset() {
    pwdFormIns.value?.resetFields()
  },
})
</script>

<template>
  <ElForm ref="pwdFormIns"
    :model="pwdFormData"
    :rules="rules"
    class="pwd-form"
    status-icon
    @submit.prevent="submitHandler"
  >
    <ElFormItem prop="oldPasswd">
      <ElInput v-model="pwdFormData.oldPasswd" placeholder="旧密码"/>
    </ElFormItem>
    <ElFormItem prop="newPasswd">
      <ElInput v-model="pwdFormData.newPasswd" placeholder="新密码"/>
    </ElFormItem>

    <ElFormItem prop="confirmPwd">
      <ElInput v-model="pwdFormData.confirmPwd" placeholder="确认新密码"/>
    </ElFormItem>
    <ElFormItem class="submit-btn">
      <ElButton :loading="loading" native-type="submit" type="primary">提交</ElButton>
    </ElFormItem>
  </ElForm>
</template>

<style lang="stylus" scoped>
.pwd-form {
  .submit-btn {
    :deep(.el-form-item__content) {
      & > button {
        width 100%;
      }
    }
  }
}

.avatar-uploader {
  width 100%;

  :deep(.el-upload) {
    width 100%;

    & > button {
      width 100%;
    }
  }
}

</style>
