<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item prop="username">
      <el-input v-model="loginForm.username" placeholder="用户名">
        <template #prefix>
          <el-icon class="el-input__icon">
            <User />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="loginForm.password"
        type="password"
        placeholder="密码"
        show-password
        autocomplete="new-password"
      >
        <template #prefix>
          <el-icon class="el-input__icon">
            <Lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item v-if="captchaOnOff" prop="code" class="login-code">
      <el-input v-model="loginForm.code" placeholder="验证码">
        <template #prefix>
          <el-icon class="el-input__icon">
            <CircleCheck />
          </el-icon>
        </template>
      </el-input>
      <img :src="captchaImg" @click="getCaptchaImage" alt="" />
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <el-button
      :icon="UserFilled"
      round
      size="large"
      type="primary"
      :loading="loading"
      @click="login(loginFormRef)"
    >
      登录
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { useUserStore } from '@/stores/modules/user'
import { useTabsStore } from '@/stores/modules/tabs'
import { useKeepAliveStore } from '@/stores/modules/keepAlive'
import { initDynamicRouter } from '@/router/modules/dynamicRouter'
import { CircleCheck, Lock, User, UserFilled } from '@element-plus/icons-vue'
import { getCaptchaImageApi, loginApi } from '@/api/system/auth'
import { setToken } from '@/utils'

const HOME_URL = import.meta.env.VITE_HOME_URL

const router = useRouter()
const userStore = useUserStore()
const tabsStore = useTabsStore()
const keepAliveStore = useKeepAliveStore()

const loginFormRef = ref()
const loginRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const captchaOnOff = ref(true)
const captchaImg = ref('')

const loading = ref(false)
const loginForm = ref({
  username: '',
  password: '',
  code: '',
  uuid: ''
})

onMounted(() => {
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    if (e.code === 'Enter' || e.code === 'enter' || e.code === 'NumpadEnter') {
      if (loading.value) return
      login(loginFormRef.value)
    }
  }
})

onBeforeUnmount(() => {
  document.onkeydown = null
})

onBeforeMount(() => {
  getCaptchaImage()
})

function getCaptchaImage() {
  loading.value = true
  getCaptchaImageApi()
    .then((resp) => {
      captchaOnOff.value = resp.captchaOnOff
      captchaImg.value = 'data:image/gif;base64,' + resp.img
      loginForm.value.uuid = resp.uuid
    })
    .finally(() => {
      loading.value = false
    })
}

function login(formEl: any) {
  if (!formEl) return
  formEl.validate(async (valid: boolean) => {
    if (!valid) return
    loading.value = true
    try {
      // 执行登录接口
      const data = await loginApi(loginForm.value)

      // 缓存token
      setToken(data.token)

      // 清空 tabs、keepAlive 数据
      await tabsStore.setTabs([])
      await keepAliveStore.setKeepAliveName([])

      // 添加动态路由
      await initDynamicRouter(data)

      // 跳转到首页
      await router.push(HOME_URL)

      ElNotification({
        title: getTimeState(),
        message: `欢迎登录 ${userStore.nickname}`,
        type: 'success',
        duration: 3000
      })
    } catch {
      if (captchaOnOff.value) {
        getCaptchaImage()
      }
    } finally {
      loading.value = false
    }
  })
}

// 获取当前时间对应的提示语
function getTimeState(): '早上好 ⛅' | '中午好 🌞' | '下午好 🌞' | '晚上好 🌛' | '凌晨好 🌛' {
  const hours = new Date().getHours()
  if (hours >= 6 && hours <= 10) return `早上好 ⛅`
  if (hours >= 10 && hours <= 14) return `中午好 🌞`
  if (hours >= 14 && hours <= 18) return `下午好 🌞`
  if (hours >= 18 && hours <= 24) return `晚上好 🌛`
  return `凌晨好 🌛`
}
</script>

<style scoped lang="scss">
@import '../index.scss';
</style>
