<template>
    <div>
        <el-dialog
            v-model="dialogVisible"
            title="修改密码"
            width="500" 
            :show-close='false'
            :close-on-click-modal="false"
           
        >
            <div v-loading="loading">
                <el-form ref="pwdRef" :model="user" :rules="rules" label-width="100px">
                    <el-form-item label="旧密码" prop="oldPassword">
                        <el-input
                        v-model="user.oldPassword"
                        placeholder="请输入旧密码"
                        type="password"
                        show-password
                        />
                    </el-form-item>
                    <el-form-item label="新密码" prop="newPassword">
                        <el-input
                        v-model="user.newPassword"
                        placeholder="请输入新密码"
                        type="password"
                        show-password
                        />
                    </el-form-item>
                    <el-form-item label="确认密码" prop="confirmPassword">
                        <el-input
                        v-model="user.confirmPassword"
                        placeholder="请确认新密码"
                        type="password"
                        show-password
                        />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submit">保存</el-button>
                        <el-button type="danger" @click="close">关闭</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-dialog>
    </div>

  </template>
  
  <script setup>
  import { changePwd ,checkPwdStrength } from '@/api/login.js'
  import { useUserStore } from '@/stores/modules/user.js'
  import { ref, reactive } from 'vue'
  import { ElMessage } from 'element-plus'

  const { proxy } = getCurrentInstance()
  const userStore = useUserStore()
  const dialogVisible = ref(false)
  const loading = ref(false)
  // 密码规则
  function passwords(value) {
    let validatorA = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/
    let validatorB = /^(?=.*\d)(?=.*[a-z])(?=.*[!@#$%^&*()\-_=+{};:,<.>]).{8,}$/
    let validatorC = /^(?=.*\d)(?=.*[A-Z])(?=.*[!@#$%^&*()\-_=+{};:,<.>]).{8,}$/
    let validatorD = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()\-_=+{};:,<.>]).{8,}$/
    if (
      validatorA.test(value) ||
      validatorB.test(value) ||
      validatorC.test(value) ||
      validatorD.test(value)
    ) {
      return true
    } else {
      return false
    }
  }
  
  // 新增用户检验密码规则
const validatorPasswords = async (rule, value, callback) => {
    const resPwd = await checkPwdStrength(user.newPassword); 
    if(resPwd.meta.code !== 200) {
        ElMessage.error(resPwd.meta?.message || '密码强度校验失败');
        return
    }else{
        if(!resPwd.data.is_strong){  
            callback(new Error(resPwd.data.suggestions.join(', ')|| '密码强度校验失败'))
            return
        }
    }
}
  
  const user = reactive({
    oldPassword: undefined,
    newPassword: undefined,
    confirmPassword: undefined,
  })
  
  const equalToPassword = (rule, value, callback) => {
    if (user.newPassword !== value) {
      callback(new Error('两次输入的密码不一致'))
    } else {
      callback()
    }
  }
  const rules = ref({
    oldPassword: [{ required: true, message: '旧密码不能为空', trigger: 'blur' }],
    newPassword: [
      { required: true, message: '新密码不能为空', trigger: 'blur' }, 
      { required: true, validator: validatorPasswords, trigger: 'blur' }
    ],
    confirmPassword: [
      { required: true, message: '确认密码不能为空', trigger: 'blur' },
      { required: true, validator: equalToPassword, trigger: 'blur' },
    ],
  })
   
  /** 提交按钮 */
async function submit() {
    loading.value = true;
  try {
    const valid = await proxy.$refs.pwdRef.validate();
    if (!valid) return;

    const resPwd = await checkPwdStrength(user.newPassword); 
    if(resPwd.meta.code !== 200) {
        ElMessage.error(resPwd.meta?.message || '密码强度校验失败');
        return
    }else{
        if(!resPwd.data.is_strong){ 
            ElMessage.error(resPwd.data.suggestions.join(', ') || '密码强度校验失败');
            return
        }
    } 
    const res = await changePwd(user.oldPassword, user.newPassword); 
    if(res.meta.code !== 200){
        ElMessage.error(res.meta?.message || '密码修改失败');
        return
    }else{
        ElMessage.success('密码修改成功，请重新登录');
    }
    await userStore.logOut();
    location.href = '/';
    
  } catch (error) {
    console.log(error,'error')
  } finally {
    loading.value = false;
  }
}

  /** 关闭按钮 */
  function close() {
      dialogVisible.value = false
      proxy.$refs.pwdRef.resetFields()
  }

  function open(){
    dialogVisible.value = true
  }
defineExpose({
    open
  })
  </script>
  