<template>
  <div class="step2">
    <el-form :model="form" :rules="rules" ref="ruleFormRef" label-position="top">
      <el-form-item prop="pass" label="新密码">
        <el-input
          v-model="form.pass"
          placeholder="请输入新密码，仅支持6～15位字母数字组合"
          type="password"
        />
      </el-form-item>
      <el-form-item prop="checkPass" label="确认密码">
        <el-input v-model="form.checkPass" placeholder="请确认密码" type="password" />
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { FormInstance, FormRules } from 'element-plus'
import { reactive, ref } from 'vue'

const form = ref({
  pass: '',
  checkPass: ''
})

const emit = defineEmits<{
  (event: 'success', value: typeof form.value): void
}>()

const ruleFormRef = ref<FormInstance>()

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入新密码'))
  } else {
    if (form.value.checkPass !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('checkPass', () => null)
    }
    callback()
  }
}
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== form.value.pass) {
    callback(new Error('两次密码不一致'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  pass: [
    { validator: validatePass, trigger: 'blur' },
    {
      pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,15}$/,
      message: '不符合密码格式',
      trigger: 'blur'
    }
  ],
  checkPass: [
    { validator: validatePass2, trigger: 'blur' },
    {
      pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,15}$/,
      message: '不符合密码格式',
      trigger: 'blur'
    }
  ]
})

const next = () => {
  ruleFormRef.value!.validate((valid: any) => {
    if (valid) {
      emit('success', form.value)
    } else {
      return false
    }
  })
}

defineExpose({
  next
})
</script>

<style scoped lang="less">
.step2 {
  width: 100%;
}
</style>
