<template>
  <div class="update-pwd-page">
    <div class="update-pwd-card">
      <h2>修改密码</h2>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" size="small">
        <el-form-item label="新密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入新密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="form.confirmPassword" type="password" placeholder="请再次输入新密码" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="submitFn">确定修改</el-button>
          <el-button @click="$router.push({ name: 'login' })">返回登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { updateUserPwdNoAuth } from '@/api/login'
import { encryptByAES } from '@/utils/crypto'
import type { FormInstance, FormRules } from 'element-plus'

const route = useRoute()
const router = useRouter()
const formRef = ref<FormInstance>()
const loading = ref(false)

const form = reactive({
  password: '',
  confirmPassword: ''
})

const validateConfirmPass = (_rule: any, value: string, callback: any) => {
  if (value !== form.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const rules: FormRules = {
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validateConfirmPass, trigger: 'blur' }
  ]
}

const submitFn = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    loading.value = true
    const code = route.query.code as string
    const res = await updateUserPwdNoAuth({
      password: encryptByAES(form.password),
      code: code || ''
    })
    if (res.code === 200) {
      ElMessage.success('密码修改成功')
      setTimeout(() => {
        router.push({ name: 'login' })
      }, 1500)
    }
  } catch (error: any) {
    ElMessage.error(error?.data?.msg || '修改失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped lang="less">
.update-pwd-page {
  background: #3274f6;
  width: 100%;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;

  .update-pwd-card {
    background: #fff;
    width: 500px;
    border-radius: 10px;
    padding: 40px;
    box-shadow: 0 0 24px #0d3ea18b;

    h2 {
      text-align: center;
      margin-bottom: 30px;
      color: #333;
    }
  }
}
</style>
