import type { FormInstance, FormRules } from 'element-plus'
import { getEmailCodeApi, validateEmailIsExistApi } from '@/api/model/user'
import { useUserStore } from '@/stores/modules/user'

const { closeLoginModal } = useLoginModal()
const { loading, onGoogleLogin } = useGoogleLogin()

const loginForm = ref<any>({
  email: '',
  captcha: '',
})
const emailStep = ref<number>(0)
const selectedMethod = ref<string>('google')
const seconds = ref<number>(0)
const errorCodeTxt = ref<string>('')
const isEmailGoogle = ref<boolean>(false)
export default function useRegister() {
  const nextStep = () => {
    emailStep.value++
  }
  const backStep = () => {
    if (emailStep.value > 0)
      emailStep.value--
  }
  /**
   * 二选一选择邮箱--下一步
   */
  const onSelectEmail = () => {
    selectedMethod.value = 'email'
    loginForm.value.email = ''
    nextStep()
  }
  /**
   * 选择曾经登陆过的账号--下一步
   */
  const onSelectAccount = async (item: any) => {
    console.log('onSelectAccount', item, loading.value)
    // type: 'google' | 'email'
    if (item.type === 'google') {
      const result = await onGoogleLogin()
      await onGoogleLoginSuccess(result)
    }
    if (item.type === 'email') {
      selectedMethod.value = 'email'
      loginForm.value.email = item.email
      emailStep.value = 1
    }
  }
  /**
   * dao: 倒计时60秒
   */
  const countSeconds = () => {
    seconds.value = 60
    const timer = setInterval(() => {
      seconds.value--
      if (seconds.value === 0)
        clearInterval(timer)
    }, 1000)
  }
  /**
   * 邮箱--发送验证码
   */
  const getMailCode = async () => {
    try {
      if (seconds.value > 0)
        return
      // 获取验证码
      await getEmailCodeApi({ account: loginForm.value.email, type: 's003_login' })
      countSeconds()
    }
    catch (error) {
      console.error('Error sending email code:', error)
    }
  }
  /**
   * 邮箱--验证是否存在--是否与已存在google的邮箱--下一步
   * @returns
   */
  async function sendEmail(formEl: FormInstance | undefined) {
    if (!formEl)
      return
    await formEl.validate(async (valid, fields) => {
      if (valid) {
      // 验证已存在google的邮箱
        const res: any = await validateEmailIsExistApi({ email: loginForm.value.email })
        if (!res || res !== 'google')
          // 如果没有google的邮箱，直接下一步，或者没有注册过邮箱
          isEmailGoogle.value = false
        if (res === 'google') {
          // 显示google登陆按钮
          isEmailGoogle.value = true
          loginForm.value.email = ''
        }
        nextStep()
      }
      else { console.log('error submit!', fields) }
    })
  }
  /**
   * 邮箱--验证码--完成登陆 （后台默认为注册）
   * @returns
   */
  async function finishCode(formEl: FormInstance | undefined) {
    errorCodeTxt.value = ''
    if (!formEl)
      return
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        await handleLogin({
          email: loginForm.value.email,
          captcha: loginForm.value.captcha,
          type: 'email',
        })
      }

      else { console.log('error submit!', fields) }
    })
  }
  /**
   * 登录--提交
   */
  async function handleLogin(params: any) {
    try {
      const { login } = useUserStore()
      await login(params)
      console.log('登陆成功回调------1111')
      closeLoginModal({ status: true, isFirstLogin: true })
    }
    catch (err: any) {
      console.log('Login error:', err, selectedMethod.value)
      if (selectedMethod.value === 'email')
        errorCodeTxt.value = 'The code is wrong or invalid.'
      else
        ElMessage.error(err.message || 'Login failed, please try again later.')
    }
  }

  /**
   * google登陆成功
   */
  async function onGoogleLoginSuccess(info: any) {
    await handleLogin({
      googleKey: info.token,
      email: info.userInfo.email,
      type: 'google',
    })
  }
  return { emailStep, loginForm, onSelectAccount, errorCodeTxt, seconds, isEmailGoogle, sendEmail, nextStep, onSelectEmail, finishCode, onGoogleLoginSuccess, backStep, getMailCode }
}
