<template>
  <a-modal
    v-model:visible="visible"
    title="修改个人信息"
    :confirmLoading="confirmLoading"
    :zIndex="6000"
    wrapClassName="profile-wrapper"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form
      labelAlign="right"
      :labelCol="{ span: 4 }"
      @keydown.stop=""
      @keypress.stop=""
    >
      <a-form-item class="tw-mb-2" :required="true" label="姓名">
        <a-input v-model:value="user.name" placeholder="姓名" />
      </a-form-item>
      <a-form-item class="tw-mb-2" label="新密码">
        <a-input
          v-model:value="user.password"
          type="password"
          placeholder="输入新密码"
        />
      </a-form-item>
      <a-form-item class="tw-mb-2" label="确认新密码">
        <a-input
          v-model:value="user.confirmPassword"
          type="password"
          placeholder="再次输入新密码"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { changeUserInfo, doLogout } from "@/api/markPage";
import { message } from "ant-design-vue";
import { reactive, watchEffect } from "vue";
import { store } from "@/store/store";

interface User {
  name: string;
  password: string;
  confirmPassword: string;
}
const user: User = reactive({
  name: "",
  password: "",
  confirmPassword: "",
});
watchEffect(() => {
  user.name = store.setting.userName;
});
let visible = $ref(false);
let confirmLoading = $ref(false);

const showModal = () => {
  visible = true;
};

const handleOk = () => {
  if (user.name.length === 0 || user.name.length >= 30) {
    void message.error({ content: "姓名长度必须在1到30之间" });
    return;
  }
  if (user.password.length !== 0 || user.confirmPassword.length !== 0) {
    if (user.password.length === 0 || user.password.length >= 16) {
      void message.error({ content: "密码长度必须在1到16之间" });
      return;
    }
    if (user.password !== user.confirmPassword) {
      void message.error({ content: "两次输入的密码不一致" });
      return;
    }
  }
  confirmLoading = true;
  changeUserInfo(user.name, user.password)
    .then(() => doLogout())
    .finally(() => {
      visible = false;
      confirmLoading = false;
    });
};

const handleCancel = () => {
  user.name = store.setting.userName;
  user.password = "";
  user.confirmPassword = "";
};

defineExpose({ showModal });
</script>
<style>
.profile-wrapper .ant-modal-title {
  color: var(--app-main-text-color);
}
.profile-wrapper .anticon-close {
  vertical-align: middle;
}
.profile-wrapper .ant-modal-body label {
  color: var(--app-bold-text-color) !important;
}
</style>
