<template>
  <popup
    v-model="showDialog"
    title="修改密码"
    width="480px"
    :close-on-click-modal="false"
    style="--el-dialog-border-radius: 1.5rem; --el-dialog-padding-primary: 1.5rem"
  >
    <el-form
      ref="formRef"
      v-loading="isLoading"
      class="change-password-form"
      :model="formData"
      label-width="90px"
      label-position="top"
      :rules="formRules"
    >
      <el-form-item label="手机号" prop="mobile">
        <el-input
          v-model="formData.mobile"
          class="change-password-form__input"
          placeholder="请输入手机号"
          size="large"
          maxlength="11"
        />
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-input
          ref="captchaInputRef"
          v-model="formData.code"
          class="change-password-form__input"
          placeholder="请输入手机验证码"
          size="large"
        >
          <template #suffix>
            <el-button :disabled="countdown > 0" type="primary" link @click="getCaptcha">
              {{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
            </el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item style="margin-bottom: 0" label="新密码" prop="password">
        <el-input
          v-model="formData.password"
          class="change-password-form__input"
          type="password"
          placeholder="请输入新密码"
          show-password
          size="large"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button class="change-password-btn" type="primary" @click="handleSubmit">重置密码</el-button>
    </template>
  </popup>
</template>

<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { validation } from '~/utils/util'
import { sendCode, resetPassword } from '~/api/user'

// 定义组件事件
const emit = defineEmits<{
  (event: 'success'): void
}>()

// 表单引用
const formRef = shallowRef<FormInstance>()
// 加载状态
const isLoading = ref(false)
// 是否显示弹窗
const showDialog = ref(false)
// 表单数据
const formData = reactive({
  mobile: '',
  code: '',
  password: ''
})
// 表单验证规则
const formRules = computed(() => ({
  mobile: [
    { required: true, message: '请输入手机号', trigger: ['blur', 'change'] },
    {
      validator: (rule: object, value: string, callback: any) => {
        if (!validation('phone', value)) {
          callback(new Error('请输入正确的手机号'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'change' }],
  password: [{ required: true, message: '请输入密码', trigger: ['blur', 'change'] }]
}))
// 验证码倒计时
const countdown = ref(0)
// 验证码输入框引用
const captchaInputRef = shallowRef<HTMLInputElement>()

// 打开弹窗
const open = () => {
  showDialog.value = true
  resetForm()
}
// 表单重置
const resetForm = () => {
  formData.mobile = ''
  formData.code = ''
  formData.password = ''
  countdown.value = 0
}
// 获取验证码
const getCaptcha = async () => {
  formRef.value?.validateField('mobile', (valid) => {
    if (valid) {
      sendCode({ mobile: formData.mobile, scene: 'reset_password' }).then(() => {
        countdown.value = 60
        captchaInputRef.value?.focus()
        const timer = setInterval(() => {
          countdown.value--
          if (countdown.value <= 0) {
            clearInterval(timer)
          }
        }, 1000)
      })
    } else {
      ElMessage.error('请输入正确的手机号')
    }
  })
}
// 提交表单
const handleSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      isLoading.value = true
      resetPassword({ ...formData, scene: 'reset_password' })
        .then(() => {
          isLoading.value = false
          showDialog.value = false
          ElMessage.success('操作成功')
          emit('success')
        })
        .catch(() => {
          isLoading.value = false
        })
    }
  })
}

defineExpose({
  open
})
</script>

<style lang="scss" scoped>
.change-password-form {
  @apply w-full;
  --el-form-label-font-size: var(--el-font-size-medium);

  :deep(.el-form-item) {
    @apply mb-6;
  }

  &__input {
    @apply h-12;

    :deep(.el-input__wrapper) {
      @apply rounded-xl;

      .el-input__inner {
        @apply h-full;
      }
    }
  }
}

.change-password-btn {
  @apply w-full h-12 rounded-xl;
}
</style>
