<template>
  <login-container>
    <div class="login-form">
      <el-form ref="formRef" label-position="left" :model="form" :rules="rules" @submit.prevent>
        <div class="title">欢迎登录</div>
        <div class="title-tips">{{ translate(title) }}</div>
        <el-form-item prop="username">
          <el-input v-model.trim="form.username" v-focus clearable :placeholder="translate('请输入用户名')" type="text">
            <template #prefix>
              <vab-icon icon="user-line" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            ref="passwordRef"
            v-model.trim="form.password"
            clearable
            :placeholder="translate('请输入密码')"
            show-password
            :type="passwordType"
          >
            <template #prefix>
              <vab-icon icon="lock-line" />
            </template>
          </el-input>
        </el-form-item>
        <el-button v-throttle="handleLogin" class="login-btn" :loading="loading" type="primary">
          {{ translate('登录') }}
        </el-button>
      </el-form>
    </div>
  </login-container>
</template>

<script setup>
import { translate } from '/@/i18n'
import { useSettingsStore } from '/@/store/modules/settings'
import { useUserStore } from '/@/store/modules/user'
import { isPassword } from '/@/utils/validate'
import LoginContainer from './vabAutoComponents/LoginContainer.vue'

defineOptions({ name: 'Login' })

const route = useRoute()
const { query } = useRoute()
const router = useRouter()
const userStore = useUserStore()
const settingsStore = useSettingsStore()
const { title } = storeToRefs(settingsStore)
const login = (form) => userStore.login(form)
const bindLoginTap = (form) => userStore.bindLoginTap(form)
const loading = ref(false)
const passwordType = ref('password')
const redirect = ref(undefined)
let timer
const formRef = ref()
const passwordRef = ref()

const form = reactive({
  username: '',
  password: '',
})

const validateUsername = (rule, value, callback) => {
  if ('' === value) callback(new Error(translate('用户名不能为空')))
  else callback()
}
const validatePassword = (rule, value, callback) => {
  if (isPassword(value)) {
    callback()
  } else {
    callback(new Error(translate('密码不能少于6位')))
  }
}

const rules = reactive({
  username: [
    {
      required: true,
      trigger: 'blur',
      validator: validateUsername,
    },
  ],
  password: [
    {
      required: true,
      trigger: 'blur',
      validator: validatePassword,
    },
  ],
})

const handleRoute = () => {
  return redirect.value === '/404' || redirect.value === '/403' ? '/' : redirect.value
}

const handleLogin = async () => {
  if (formRef.value)
    formRef.value?.validate(async (valid) => {
      if (valid)
        try {
          loading.value = true
          await login(form).catch(() => {
            loading.value = false
          })
          await router.push(handleRoute())
        } finally {
          loading.value = false
        }
    })
}

onBeforeMount(async () => {
  if (query.code) {
    let code = query.code
    try {
      loading.value = true
      await bindLoginTap({ code: code }).catch(() => {
        loading.value = false
      })
      await router.push(handleRoute())
    } finally {
      loading.value = false
    }
  }
})

watchEffect(() => {
  redirect.value = (route.query && route.query.redirect) || '/'
})

onBeforeRouteLeave((to, from, next) => {
  try {
    if (timer) clearTimeout(timer)
  } catch {
    /* empty */
  }

  next()
})
</script>

<style lang="scss" scoped>
/* 移除不需要的样式 */
</style>
