import { defineStore } from 'pinia'
import { ref } from 'vue'
import { postForm } from '@/utils/request'

const COUNTDOWN_SEC = 60

export const useChangePasswordStore = defineStore('changePassword', () => {
  const loading = ref(false)
  const sendingCode = ref(false)
  const codeCountdown = ref(0)
  const error = ref<string | null>(null)

  let countdownTimer: ReturnType<typeof setInterval> | null = null

  function stopCountdown() {
    if (countdownTimer) {
      clearInterval(countdownTimer)
      countdownTimer = null
    }
    codeCountdown.value = 0
  }

  function startCountdown() {
    stopCountdown()
    codeCountdown.value = COUNTDOWN_SEC
    countdownTimer = setInterval(() => {
      codeCountdown.value--
      if (codeCountdown.value <= 0) {
        stopCountdown()
      }
    }, 1000)
  }

  async function sendEmailCode() {
    sendingCode.value = true
    error.value = null
    try {
      await postForm('/uc/updatePassword/email/code', {})
      startCountdown()
    } catch (e) {
      error.value = e instanceof Error ? e.message : '验证码发送失败'
      throw e
    } finally {
      sendingCode.value = false
    }
  }

  async function submitChangePassword(oldPassword: string, newPassword: string, vcode: string) {
    loading.value = true
    error.value = null
    try {
      await postForm('/uc/approve/update/password', {
        oldPassword,
        newPassword,
        vtype: '2',
        vcode,
      })
    } catch (e) {
      error.value = e instanceof Error ? e.message : '修改密码失败'
      throw e
    } finally {
      loading.value = false
    }
  }

  return {
    loading,
    sendingCode,
    codeCountdown,
    error,
    sendEmailCode,
    submitChangePassword,
    stopCountdown,
  }
})
