<template>
  <div class="container">
    <n-form ref="formRef" label-placement="left" :label-width="100" :model="form" :rules="rules" size="large" require-mark-placement="left">
      <n-form-item label="密码：" path="newPassword">
        <n-input v-model:value="form.newPassword" @input="handlePasswordInput" type="password" show-password-on="click" placeholder="请输入密码" />
      </n-form-item>
      <n-form-item label="确认密码：" path="confirmNewPassword" ref="confirmPasswordRef">
        <n-input v-model:value="form.confirmNewPassword" type="password" show-password-on="click" placeholder="请输入确认密码" />
      </n-form-item>
    </n-form>
    <n-button class="login-btn" attr-type="button" type="info" color="#18A058" :disabled="submitLoading" @click="handleSure">
      {{ submitLoading ? "提交中..." : "确认" }}
    </n-button>
  </div>
</template>

<script lang="ts" setup>
import {
  NForm,
  NFormItem,
  NInput,
  NButton,
  FormRules,
  FormItemRule,
  createDiscreteApi,
} from "naive-ui";
import { ref, reactive } from "vue";

const emit = defineEmits(["closeSginDialog"]);

const message = createDiscreteApi(["message"]);

const formRef = ref();
const submitLoading = ref(false);
const confirmPasswordRef = ref();

const form = reactive({
  newPassword: "",
  confirmNewPassword: "",
});

const confirmPasswordValidate = (
  rule: FormItemRule,
  value: string
): boolean => {
  return value && value == form.newPassword;
};

const rules: FormRules = {
  newPassword: [
    {
      required: true,
      message: "请输入密码",
      trigger: ["input", "blur", "password-input"],
    },
  ],
  confirmNewPassword: [
    {
      required: true,
      message: "请输入密码",
      trigger: ["input", "blur"],
    },
    {
      required: true,
      validator: confirmPasswordValidate,
      message: "两次密码输入不一致",
      trigger: ["blur", "password-input"],
    },
  ],
};

const handlePasswordInput = () => {
  if (form.confirmNewPassword) {
    confirmPasswordRef.value?.validate({ trigger: "password-input" });
  }
};

const handleSure = () => {
  formRef.value?.validate(async (errors: any) => {
    if (!errors) {
      submitLoading.value = true;
      const params = JSON.parse(JSON.stringify(form));
      params.newPassword = encryptByBase64(params.newPassword);
      params.confirmNewPassword = encryptByBase64(params.confirmNewPassword);
      try {
        const { code } = await updatePwd_Api(params);
        if (code === 200) {
          message.message.success("修改成功");
          emit("closeSginDialog", "success");
        }
      } catch (error) {}
      submitLoading.value = false;
    }
  });
};
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  padding: 30px 20px;

  .login-btn {
    display: block;
    width: 50%;
    height: 50px;
    color: #fff;
    font-size: 18px;
    border-radius: 8px;
    margin: 0 auto;

    :deep(.n-button__content) {
      display: block;
    }
  }
}
</style>
