<template>
  <a-modal
    title="修改个人信息"
    v-model:visible="visible"
    :confirm-loading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :zIndex="6000"
    wrapClassName="profile-wrapper"
  >
    <a-form labelAlign="right" :labelCol="{ span: 4 }">
      <a-form-item class="tw-mb-2" :required="true" label="姓名">
        <a-input
          @keydown.stop="() => {}"
          v-model:value="user.name"
          placeholder="姓名"
        />
      </a-form-item>
      <a-form-item class="tw-mb-2" label="新密码">
        <a-input
          @keydown.stop="() => {}"
          type="password"
          v-model:value="user.password"
          placeholder="输入新密码"
        />
      </a-form-item>
      <a-form-item class="tw-mb-2" label="确认新密码">
        <a-input
          @keydown.stop="() => {}"
          type="password"
          v-model:value="user.confirmPassword"
          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) {
    message.error({ content: "姓名长度必须在1到30之间" });
    return;
  }
  if (user.password.length !== 0 || user.confirmPassword.length !== 0) {
    if (user.password.length === 0 || user.password.length >= 16) {
      message.error({ content: "密码长度必须在1到16之间" });
      return;
    }
    if (user.password !== user.confirmPassword) {
      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>
