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

const COUNTDOWN_SEC = 60

export const useFundPasswordStore = defineStore('fundPassword', () => {
  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 setInitialFundPassword(jyPassword: string) {
    loading.value = true
    error.value = null
    try {
      await postForm('/uc/approve/transaction/password', { jyPassword })
    } catch (e) {
      error.value = e instanceof Error ? e.message : '设置失败'
      throw e
    } finally {
      loading.value = false
    }
  }

  /** 重置流程：发送邮件验证码 */
  async function sendResetEmailCode() {
    sendingCode.value = true
    error.value = null
    try {
      await postForm('/uc/transaction/email/code', {})
      startCountdown()
    } catch (e) {
      error.value = e instanceof Error ? e.message : '验证码发送失败'
      throw e
    } finally {
      sendingCode.value = false
    }
  }

  /** 重置资金密码 */
  async function resetFundPassword(newPassword: string, vcode: string) {
    loading.value = true
    error.value = null
    try {
      await postForm('/uc/approve/reset/transaction/password', {
        newPassword,
        vtype: '2',
        vcode,
      })
    } catch (e) {
      error.value = e instanceof Error ? e.message : '重置失败'
      throw e
    } finally {
      loading.value = false
    }
  }

  return {
    loading,
    sendingCode,
    codeCountdown,
    error,
    setInitialFundPassword,
    sendResetEmailCode,
    resetFundPassword,
    stopCountdown,
  }
})
