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

const { closeLoginAndDownloadModal } = useLoginAndDownLoadModal()
const { loading, onGoogleLogin } = useGoogleLogin()

const loginForm = ref<any>({
  email: '',
  captcha: '',
})
const emailStep = ref<number>(0)
const isEmailGoogle = ref<boolean>(false)
const selectedMethod = ref<string>('google')
export default function useRegister() {
  const seconds = ref<number>(0)
  const errorCodeTxt = ref<string>('')
  const formInfo = ref<any>({
    firstName: '',
    catalogueId: '',
    lastName: '',
    mobile: '',
    mobileAreaCode: '+86',
    customServer: 'browing',
    companyName: '',
    purchaseAmount: undefined,
    purchaseRequest: '',

  })
  const visible = computed(() => formInfo.value.customServer === 'suppliers')
  watch(() => visible.value, (val) => {
    if (!val) {
      // 如果visible变为false，重置formInfo的相关字段
      formInfo.value.companyName = ''
      formInfo.value.purchaseAmount = undefined
      formInfo.value.purchaseRequest = ''
    }
  })

  const nextStep = () => {
    emailStep.value++
  }
  const setEmailStep = (val: number) => {
    emailStep.value = val
  }
  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') {
      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', emailStep.value)
      // closeLoginAndDownloadModal({ 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',
    })
  }

  // ------------------------  填写信息部分 ------------------------

  const setSubmitInfo = async (formEl: FormInstance | undefined) => {
    if (!formEl)
      return
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        const { downloadCatalog } = storeToRefs(useCommonStore())
        // 提交用户信息
        console.log('submit info', formInfo.value)
        formInfo.value.catalogueId = downloadCatalog.value?.id || ''
        await submitInfoApi(formInfo.value)
        // 更新用户信息
        const res = await getUpdateUserInfoApi()
        const { updateUserInfo } = useUserStore()
        updateUserInfo(res)
        emailStep.value = 4
      }

      else { console.log('error submit!', fields) }
    })
  }

  /**
   * 已经填写了用户信息---提交请求
   */
  const onSubmitRequest = async () => {
    const { downloadCatalog } = storeToRefs(useCommonStore())
    const { userInfo } = storeToRefs(useUserStore())
    // 提交用户信息
    const params = {
      catalogueId: downloadCatalog.value?.id || '',
      firstName: userInfo.value?.firstName,
      lastName: userInfo.value?.lastName,
    }
    await submitInfoApi(params)
    emailStep.value = 4
  }

  return { emailStep, visible, onGoogleLoginSuccess, loginForm, formInfo, setEmailStep, setSubmitInfo, onSubmitRequest, onSelectAccount, errorCodeTxt, seconds, isEmailGoogle, sendEmail, nextStep, onSelectEmail, finishCode, backStep, getMailCode }
}
