<script setup lang="ts">
import { ref } from 'vue'
import { api } from '@/tools/web.ts'
import type { ReturnDto } from '@/types/response.ts'
import { useMessage } from 'naive-ui'
import VerifyCodeModal from '@/components/admin/VerifyCodeModal.vue'
import { useNowUser } from '@/stores/now-user.ts'

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

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

const showVerifyCodeModal = ref(false)
const newEmail = ref('')
const verifyCode = ref('')

function sendEmail() {
  api
    .post('/admin/me/email-verify/send/', JSON.stringify({ to: newEmail.value }))
    .then((res) => res.data as ReturnDto)
    .then((res) => {
      if (res.success) {
        MESSAGE.success('验证邮件已发送，请检查收件箱~')
        showVerifyCodeModal.value = true
      } else {
        throw TypeError('未知原因后端错误')
      }
    })
    .catch((err) => {
      MESSAGE.error(`获取验证码失败：${err}`)
    })
}

function verifyEmail() {
  api
    .post(
      '/admin/me/email-verify/',
      JSON.stringify({
        to: newEmail.value,
        verify_code: String(verifyCode.value).split(',').join(''),
      }),
    )
    .then((res) => res.data as ReturnDto)
    .then((res) => {
      if (res.success) {
        MESSAGE.success('邮件地址修改成功~')
        showVerifyCodeModal.value = false
        showModal.value = false
        NOWUSER.email = newEmail.value
      } else {
        throw TypeError('未知原因后端错误')
      }
    })
    .catch((err) => {
      MESSAGE.error(`验证失败：${err}`)
    })
}
</script>

<template>
  <n-modal v-model:show="showModal" preset="card" style="width: 600px" title="修改邮件地址">
    <n-form label-placement="left">
      <n-p>你需要使用新的邮件地址接收一个验证码来完成修改。</n-p>
      <n-form-item path="to" label="新的邮件地址">
        <n-input v-model:value="newEmail" />
      </n-form-item>
      <n-flex>
        <n-button type="warning" @click="sendEmail()">获取验证码</n-button>
        <n-button type="tertiary" @click="showVerifyCodeModal = true">直接输入验证码</n-button>
        <n-tag type="info">验证码有效期为 5 分钟，且不允许多个同时有效。</n-tag>
      </n-flex>
    </n-form>
  </n-modal>

  <verify-code-modal
    v-model:show-modal="showVerifyCodeModal"
    v-model:verify-code="verifyCode"
    :verify="verifyEmail"
  />
</template>

<style scoped></style>
