<template>
  <el-dialog
    v-model="dialogVisible"
    title="修改密码"
    :width="500"
    center
    align-center
    :close-on-click-modal="false"
    @closed="closed"
  >
    <el-form :model="formData" ref="formRef" label-width="90px" :rules="formRules">
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input v-model="formData.oldPassword" placeholder="请填写旧密码" type="password" show-password maxlength="20" />
      </el-form-item>
      <el-form-item label="登录密码" prop="password">
        <el-input v-model="formData.password" placeholder="请填写新密码" type="password" show-password maxlength="20" />
      </el-form-item>
      <el-form-item label="确认密码" prop="rePassword">
        <el-input v-model="formData.rePassword" placeholder="请再次填写新密码" type="password" show-password maxlength="20" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" class="ml30" v-throttle="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup name="editTeamMember">
import { reactive, ref, defineExpose } from "vue";
import { FormInstance, FormRules } from "element-plus";
import { updateProfilePwd } from "@/api/modules/common";

//* 接收注入
const dialogVisible = ref(false);
//* data
//* ref
const formRef = ref<FormInstance>();
const openPromise = ref<any>({});
interface FormData {
  oldPassword: string;
  password: string;
  rePassword: string;
}
const formData = reactive<FormData>({
  oldPassword: "",
  password: "",
  rePassword: ""
});
//* 方法

//校验再一次输入密码
const checkResPassword = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("请再次填写密码"));
  } else if (value !== formData.password) {
    return callback(new Error("两次密码输入不一致"));
  }
  return callback();
};
// 校验规则
let formRules = reactive<FormRules>({
  oldPassword: [{ required: true, message: "密码不能为空", trigger: "blur" }],
  password: [
    { required: true, message: "密码不能为空", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" }
  ],
  rePassword: [{ required: true, validator: checkResPassword, trigger: "blur" }]
});
function closed() {
  dialogVisible.value = false;
  formRef.value?.resetFields();
}
// 取消
function handleCancel() {
  dialogVisible.value = false;
}
//提交
function handleSubmit() {
  formRef.value?.validate(async valid => {
    if (!valid) return;
    await updateProfilePwd({
      oldPassword: formData.oldPassword,
      newPassword: formData.password
    });
    openPromise.value.resolve();
    dialogVisible.value = false;
  });
}

function open() {
  dialogVisible.value = true;
  return new Promise(resolve => {
    openPromise.value.resolve = resolve;
  });
}
defineExpose({
  open
});
</script>

<style lang="scss"></style>
