<script setup lang="ts">
import { Form, FormSchema } from '../../../../components/Form'
import { useForm } from '../../../../hooks/web/useForm'
import { reactive, ref } from 'vue'
import { useValidator } from '../../../../hooks/web/useValidator'
import { changePassword } from '../../../../api'

const { required } = useValidator()

const formSchema = reactive<FormSchema[]>([
  {
    field: 'password',
    label: '旧密码',
    component: 'InputPassword',
    colProps: {
      span: 24
    }
  },
  {
    field: 'newPassword',
    label: '新密码',
    component: 'InputPassword',
    colProps: {
      span: 24
    },
    componentProps: {}
  },
  {
    field: 'newPassword2',
    label: '确认新密码',
    component: 'InputPassword',
    colProps: {
      span: 24
    },
    formItemProps: {
      tip: '支持输入英文、数字、特殊字符，至少6位'
    }
  }
])

const regx = '^(?=[A-Za-z\\d])(?=.*[A-Za-z])(?=.*\\d)(?=.*[@$!%*?&#_])[A-Za-z\\d@$!%*?&#_]{6,}$'
const { formRegister, formMethods } = useForm()
const { getFormData, getElFormExpose } = formMethods

const rules = reactive({
  password: [required()],
  newPassword: [
    required(),
    {
      asyncValidator: async (_, val, callback) => {
        const formData = await getFormData()
        const { newPassword } = formData
        if (!val.match(regx)) {
          callback(new Error('密码格式错误'))
        } else if (val === newPassword) {
          const elForm = await getElFormExpose()
          elForm?.validateField('newPassword2')
          callback()
        } else {
          callback()
        }
      }
    }
  ],
  newPassword2: [
    required(),
    {
      asyncValidator: async (_, val, callback) => {
        const formData = await getFormData()
        const { newPassword } = formData
        if (!val.match(regx)) {
          callback(new Error('密码格式错误'))
        } else if (val !== newPassword) {
          callback(new Error('确认新密码与新密码不一致'))
        } else {
          callback()
        }
      }
    }
  ]
})

const saveLoading = ref(false)
const emits = defineEmits(['success'])
const save = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    ElMessageBox.confirm('是否确认修改?', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        try {
          const formData = await getFormData()
          const { success } = await changePassword({
            originalPassword: formData.password,
            newPassword: formData.newPassword
          })
          saveLoading.value = true
          if (success) {
            ElMessage.success('修改成功')
            elForm?.resetFields()
            emits('success')
          }
        } catch (error) {
          console.log(error)
        } finally {
          saveLoading.value = false
        }
      })
      .catch(() => {})
  }
}
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" class="w-400px" />
  <ElDivider />
  <BaseButton type="primary" @click="save">确认修改</BaseButton>
</template>
