<script setup lang="ts">
import { ref } from 'vue'
import { api } from '@/tools/web.ts'
import { useNowUser } from '@/stores/now-user.ts'
import { useMessage } from 'naive-ui'
import { useRouter } from 'vue-router'

const ROUTER = useRouter()
const MESSAGE = useMessage()
const NOWUSER = useNowUser()

const showModal = defineModel('showModal', { required: true })

const changeForm = ref({
  old_password: '',
  new_password: '',
})

function change() {
  api
    .post('/admin/me/password/', JSON.stringify(changeForm.value))
    .then(() => {
      MESSAGE.success('密码修改成功，请重新登录。')
      NOWUSER.isLogin = false
      localStorage.removeItem('user-id')
      localStorage.removeItem('access-token')
      ROUTER.push('/')
    })
    .catch((err) => {
      MESSAGE.error(`密码修改失败：${err}`)
      MESSAGE.warning('如果您忘记了原密码，请选择「忘记密码」。')
    })
}
</script>

<template>
  <n-modal style="width: 600px" v-model:show="showModal" title="修改密码" preset="card">
    <n-form label-align="right" label-placement="left" label-width="auto" :model="changeForm">
      <n-form-item label="原密码" path="old_password">
        <n-input v-model:value="changeForm.old_password" />
      </n-form-item>
      <n-form-item label="新密码" path="new_password">
        <n-input v-model:value="changeForm.new_password" type="password" show-password-toggle />
      </n-form-item>
      <n-form-item label="确认修改">
        <n-flex>
          <n-button type="error" @click="change()">确认修改</n-button>
          <n-tag type="warning" size="large"
            >修改密码会注销所有已登录状态，您将需要重新登录。</n-tag
          >
        </n-flex>
      </n-form-item>
    </n-form>
  </n-modal>
</template>

<style scoped></style>
