<template>
  <div class="form">
    <div class="username">
      <a-form size="large" ref="usernameFormRef" :model="usernameForm" class="form" @submit="changeName">
        <a-form-item field="username" label="用户名"
          :rules="[{ required: true, message: '用户名不能为空' }, { minLength: 4, maxLength: 12, message: '用户名长度需在4~12位间' }]"
          :validate-trigger="['change']">
          <a-input placeholder="请输入用户名" allow-clear v-model="usernameForm.username">
            <template #prefix>
              <icon-user />
            </template>
          </a-input>
        </a-form-item>
        <a-button class="button" type="primary" html-type="submit" :loading="state.usernameButton"
          :disabled="user?.username === usernameForm.username">更新用户名</a-button>
      </a-form>
    </div>
    <a-divider />

    <div class="email">
      <a-form size="large" ref="emailFormRef" :model="emailForm" class="form" @submit="changeEmail">
        <a-form-item field="email" label="邮箱" :rules="[{ type: 'email', required: true, message: '请填写正确的邮箱地址' }]"
          :validate-trigger="['change']">
          <EmailAutoComplete placeholder="请输入邮箱" allow-clear v-model="emailForm.email">
            <template #prefix>
              <icon-email />
            </template>
          </EmailAutoComplete>
        </a-form-item>

        <a-form-item field="captcha" label="图片验证码" :rules="[{ length: 4, required: true, message: '请正确填写图片验证码' }]">
          <a-input placeholder="请输入图片验证码" allow-clear v-model="emailForm.captcha">
            <template #prefix>
              <icon-check-circle />
            </template>
            <template #append>
              <img alt="!点我重试" height="34" :src="ImageCaptcha" class="captcha" @click="getCaptcha()">
            </template>
          </a-input>
        </a-form-item>

        <a-form-item field="code" label="邮箱验证码" :rules="[{ length: 6, required: true, message: '请正确填写邮箱验证码' }]">
          <a-input placeholder="请输入邮箱验证码" allow-clear v-model="emailForm.code">
            <template #prefix>
              <icon-code-square />
            </template>
            <template #append>
              <a-button type="text" style="width: 80px" @click="SendEmail" :disabled="state.smsSendBtn || user?.email === emailForm.email">
                <span v-if="!state.smsSendBtn">获取验证码</span>
                <span v-else>{{ state.time }} s</span>
              </a-button>
            </template>
          </a-input>
        </a-form-item>
        <a-button class="button" type="primary" html-type="submit" :loading="state.emailButton"
        :disabled="user?.email === emailForm.email">更新邮箱</a-button>
      </a-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onBeforeMount } from 'vue'
import { ChangeUsername, BindEmail } from '@/api/user'
import { getImageCaptcha, sendEmail } from '@/api/login'
import { useUserStore } from '@/store/modules/user'
import { Notification, Message } from '@arco-design/web-vue'

const userStore = useUserStore()
let user = ref(null)

let usernameFormRef = ref(null)
let emailFormRef = ref(null)

let state = reactive({
  usernameButton: false,
  emailButton: false,
  smsSendBtn: false,
  time: 60
})

let usernameForm = reactive({
  username: ''
})

let emailForm = reactive({
  email: '',
  captcha: '',
  code: ''
})

const getUser = async () => {
  const userInfo = await userStore.getInfo()
  user.value = userInfo
  usernameForm.username = userInfo.username
  emailForm.email = userInfo.email
}

onBeforeMount(getUser)


let CaptchaId = ref('')
let ImageCaptcha = ref('')

const getCaptcha = async () => {
    try {
        const res = await getImageCaptcha()
        if (!res || res.code != 0)
            return Message.error('获取图片验证码失败！' + res?.msg ?? '')
        ImageCaptcha.value = res.data.img
        CaptchaId.value = res.data.id
    } catch (error) {
      Message.error('获取图片验证码失败！')
    }
}

getCaptcha()

const changeName = async () => {
  try {
    state.usernameButton = true
    const v = await usernameFormRef.value.validate()
    if (v || user.value.username === usernameForm.username) return

    const res = await ChangeUsername({ username: usernameForm.username })
    if (!res || res.code !== 0) throw new Error(res?.msg ?? '更新失败！请稍后再试')

    user.value = await userStore.getInfoFromServer()
    Message.success('更新用户名成功！')
  } catch (error) {
    Notification.error({
      title: '更新用户名失败！',
      content: error.message || ''
    })
  } finally {
    state.usernameButton = false
  }
}

const SendEmail = async () => {
    try {
        const v = await emailFormRef.value.validateField(['email', 'captcha'])
        if (v) return

        let email = emailForm.email
        let text = emailForm.captcha

        state.smsSendBtn = true
        const interval = window.setInterval(() => {
            if (state.time-- <= 0) {
                state.time = 60
                state.smsSendBtn = false
                window.clearInterval(interval)
            }
        }, 1000)

        Message.loading('验证码发送中..')

        const res = await sendEmail({ email, text, id: CaptchaId.value, type: 'bind' })

        if (!res || res.code != 0) {
            state.time = 60
            state.smsSendBtn = false
            window.clearInterval(interval)
            getImageCaptcha()
            emailForm.captcha = ''

            if (res.code === -10501) {
                return Notification.error({
                    title: '验证码输入错误',
                    content: res?.msg ?? '请求出现错误，请稍后再试'
                })
            }

            return Notification.error({
                title: '获取验证码失败',
                content: res?.msg ?? '请求出现错误，请稍后再试'
            })
        }
    } catch (error) {
        Message.error('验证码发送失败')
    }
}

const changeEmail = async () => {
  try {
    state.emailButton = true
    const v = await emailFormRef.value.validate()
    if (v || user.value.email === emailForm.email) return

    const res = await BindEmail({ email: emailForm.email, code:  emailForm.code})
    if (!res || res.code !== 0) throw new Error(res?.msg ?? '更新失败！请稍后再试')

    user.value = await userStore.getInfoFromServer()
    Message.success('更新邮箱成功！')
  } catch (error) {
    Notification.error({
      title: '更新邮箱失败！',
      content: error.message || ''
    })
    getCaptcha()
    emailForm.captcha = ''
  } finally {
    state.emailButton = false
  }
}

</script>

<style scoped lang="less">
.form {
  width: min(100%, 540px);
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.button {
  width: 150px;
}

:deep(.arco-form-item-label-col > label) {
  white-space: nowrap;
}

@media (max-width: 768px) {
  .form {
    width: 100%;
    align-items: stretch;
  }

  .button {
    width: 100%;
  }

  :deep(.arco-form-item) {
    margin-bottom: 12px;
  }

  :deep(.arco-form-item-label-col),
  :deep(.arco-form-item-wrapper-col) {
    flex: 0 0 100%;
    max-width: 100%;
  }

  :deep(.arco-form-item-label-col) {
    margin-bottom: 4px;
  }

  :deep(.arco-input-group-append .arco-btn) {
    width: 86px !important;
    padding-left: 0;
    padding-right: 0;
  }
}
</style>
