<template>
  <div>
    <n-grid cols="2 s:2 m:2 l:2 xl:2 2xl:2" responsive="screen">
      <n-grid-item>
        <n-form :label-width="80" :model="formValue" :rules="rules" ref="formRef">
          <n-form-item label="当前密码" path="oldPassword">
            <n-input
              type="password"
              v-model:value="formValue.oldPassword"
              placeholder="请输入当前密码"
            />
          </n-form-item>

          <n-form-item label="新密码" path="newPassword">
            <n-input
              type="password"
              v-model:value="formValue.newPassword"
              placeholder="请输入新密码"
            />
          </n-form-item>

          <div>
            <n-space>
              <n-button type="primary" @click="formSubmit">修改并重新登录</n-button>
            </n-space>
          </div>
        </n-form>
      </n-grid-item>
    </n-grid>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { useMessage } from 'naive-ui';
  import { useRouter, useRoute } from 'vue-router';
  import { UpdatePassword } from '@/api/system/role';
  import { TABS_ROUTES } from '@/store/mutation-types';
  import { useUserStore } from '@/store/modules/user';
  const userStore = useUserStore();
  const rules = {
    basicName: {
      required: true,
      message: '请输入网站名称',
      trigger: 'blur',
    },
  };

  const formRef: any = ref(null);
  const message = useMessage();
  const router = useRouter();
  const route = useRoute();
  const formValue = ref({
    oldPassword: '',
    newPassword: '',
  });

  function formSubmit() {
    formRef.value.validate((errors) => {
      if (!errors) {
        console.log('formValue.value:' + JSON.stringify(formValue.value));

        UpdatePassword({
          oldPassword: formValue.value.oldPassword,
          newPassword: formValue.value.newPassword,
        })
          .then((res) => {
            console.log('res:' + JSON.stringify(res));
            message.success('更新成功');

            userStore.logout().then(() => {
              message.success('成功退出登录');
              // 移除标签页
              localStorage.removeItem(TABS_ROUTES);
              router
                .replace({
                  name: 'Login',
                  query: {
                    redirect: route.fullPath,
                  },
                })
                .finally(() => location.reload());
            });
          })
          .catch((error) => {
            message.error(error.toString());
          });
      } else {
        message.error('验证失败，请填写完整信息');
      }
    });
  }
</script>
