<template>
  <div class="login-container">
    <img class="login-bg" src="@/assets/images/login_bg.png" />
    <el-card class="login-card !border-none" body-style="padding: 2rem;" shadow="never">
      <div class="text-center text-[1.75rem] leading-[2.25rem] font-semibold">账号登录</div>
      <el-radio-group v-model="loginForm.type" class="login-card__switch" size="large">
        <el-radio-button class="login-card__switch-item" label="验证码登录" :value="1" />
        <el-radio-button class="login-card__switch-item" label="密码登录" :value="2" />
      </el-radio-group>
      <el-form ref="loginFormRef" class="login-card__form" :rules="loginRules" :model="loginForm" label-position="top">
        <el-form-item label="手机号" prop="mobile">
          <el-input
            v-model="loginForm.mobile"
            class="login-card__input"
            placeholder="请输入手机号"
            size="large"
            maxlength="11"
            @keyup.enter="handleEnter"
          />
        </el-form-item>
        <el-form-item v-if="loginForm.type === 1" label="验证码" prop="code">
          <el-input
            ref="captchaInputRef"
            v-model="loginForm.code"
            class="login-card__input"
            placeholder="请输入手机验证码"
            size="large"
            @keyup.enter="handleLogin"
          >
            <template #suffix>
              <el-button :disabled="countdown > 0" type="primary" link @click="getCaptcha">
                {{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item v-else label="密码" prop="password">
          <el-input
            ref="passwordInputRef"
            v-model="loginForm.password"
            class="login-card__input"
            type="password"
            placeholder="请输入密码"
            show-password
            size="large"
            @keyup.enter="handleEnter"
          />
        </el-form-item>
        <el-form-item style="margin-bottom: 0">
          <el-button class="login-card__button" type="primary" :loading="isLoading" @click="handleLogin">
            登 录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import type { FormInstance, InputInstance, FormRules } from 'element-plus'
import { useUserStore } from '~/stores/user'
import { validation } from '~/utils/util'
import { sendCode } from '~/api/user'

const loginFormRef = shallowRef<FormInstance>()
const captchaInputRef = shallowRef<InputInstance>()
const passwordInputRef = shallowRef<InputInstance>()
const router = useRouter()
const userStore = useUserStore()

// 登录加载状态
const isLoading = ref(false)
// 验证码倒计时
const countdown = ref(0)
// 登录表单数据
const loginForm = reactive({
  type: 1,
  mobile: '',
  password: '',
  code: ''
})
// 登录表单验证规则
const loginRules = reactive<FormRules>({
  mobile: [
    { required: true, message: '请输入手机号', trigger: ['blur', 'change'] },
    {
      validator: (rule: object, value: string, callback: any) => {
        if (!validation('phone', value)) {
          callback(new Error('请输入正确的手机号'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'change' }],
  password: [{ required: true, message: '请输入密码', trigger: ['blur', 'change'] }]
})

// 获取验证码
const getCaptcha = async () => {
  loginFormRef.value?.validateField('mobile', (valid) => {
    if (valid) {
      sendCode({ mobile: loginForm.mobile, scene: 'mobile_login' }).then(() => {
        countdown.value = 60
        captchaInputRef.value?.focus()
        const timer = setInterval(() => {
          countdown.value--
          if (countdown.value <= 0) {
            clearInterval(timer)
          }
        }, 1000)
      })
    } else {
      ElMessage.error('请输入正确的手机号')
    }
  })
}
// 用户名输入框回车事件
const handleEnter = () => {
  loginFormRef.value?.validateField('mobile', (valid) => {
    if (valid) {
      if (loginForm.type === 1) {
        if (!loginForm.code) {
          loginFormRef.value?.validateField('code')
          captchaInputRef.value?.focus()
          return
        }
      } else {
        if (!loginForm.password) {
          loginFormRef.value?.validateField('password')
          passwordInputRef.value?.focus()
          return
        }
      }
      handleLogin()
    }
  })
}
// 处理登录
const handleLogin = async () => {
  loginFormRef.value?.validate(async (valid) => {
    if (valid) {
      isLoading.value = true
      try {
        await userStore.login({
          type: loginForm.type,
          mobile: loginForm.mobile,
          scene: 'mobile_login',
          ...(loginForm.type === 1 ? { code: loginForm.code } : { password: loginForm.password })
        })
        await userStore.getUser()
        isLoading.value = false
        router.replace('/user')
      } catch (error) {
        isLoading.value = false
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.login-container {
  @apply flex items-center justify-end py-12;
  min-height: calc(100vh - var(--nav-height));

  .login-bg {
    @apply fixed left-0 w-full h-full object-cover;
    top: var(--nav-height);
  }

  .login-card {
    @apply w-full max-w-[100%] md:max-w-[460px] relative z-[1];
    border-radius: 24px;

    &__switch {
      @apply mt-8 w-full;

      &-item {
        @apply flex-1;
        --el-border-radius-base: 12px;

        :deep(.el-radio-button__inner) {
          @apply w-full p-4 text-md leading-5;
          outline: none;
          background: var(--el-color-primary-light-9);
        }
      }
    }

    &__form {
      @apply mt-9 w-full;
      --el-form-label-font-size: var(--el-font-size-medium);

      :deep(.el-form-item) {
        @apply mb-6;
      }
    }

    &__input {
      @apply h-12;

      :deep(.el-input__wrapper) {
        @apply rounded-xl;

        .el-input__inner {
          @apply h-full;
        }
      }
    }

    &__button {
      @apply w-full h-12;
      border-radius: 12px;
    }
  }
}
</style>
