<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 prop="code">
      <el-input v-model="loginForm.code" auto-complete="off" placeholder="请输入验证码" style="width: 65%"></el-input>
      <img :src="codeUrl" @click="getCode()" class="login-code-img" title="看不清？点击更换" />
    </el-form-item>
    <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
  </el-form>
  <div class="login-btn">
    <el-button icon="CircleClose" round size="large" @click="resetForm(loginFormRef)"> 重置 </el-button>
    <el-button icon="UserFilled" round size="large" type="primary" :loading="loading" @click.prevent="handleLogin(loginFormRef)"> 登录 </el-button>
  </div>
</template>

<script setup lang="ts">
import { HOME_URL } from '@/config'
import { getTimeState } from '@/utils'
import { LoginData } from '@/api/interface/login'
import { ElNotification } from 'element-plus'
import { getCodeImg } from '@/api/modules/login'
import { useUserStore } from '@/stores/modules/user'
import { useTabsStore } from '@/stores/modules/tabs'
import { useKeepAliveStore } from '@/stores/modules/keepAlive'
import { initDynamicRouter } from '@/routers/modules/dynamicRouter'
import type { ElForm } from 'element-plus'
// import md5 from 'md5'
import { lodashFunc } from '@/utils/common'
import Cookies from 'js-cookie'
import { encrypt, decrypt } from '@/utils/jsEncrypt'
const router = useRouter()
const userStore = useUserStore()
const tabsStore = useTabsStore()
const keepAliveStore = useKeepAliveStore()

type FormInstance = InstanceType<typeof ElForm>
const loginFormRef = ref<FormInstance>()
const loginRules = reactive({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
})
const codeUrl = ref<string>('')
const loading = ref(false)
const loginForm = reactive<LoginData>({
  username: 'superadmin',
  password: 'admin123',
  rememberMe: false,
  code: '',
  uuid: '',
  tenantId: '0',
  clientId: 'e5cd7e4891bf95d1d19206ce24a7b32e',
  grantType: 'password'
})
// 登录
const handleLogin = (formEl: FormInstance | undefined) => {
  loading.value = true
  if (!formEl) return
  formEl.validate(async valid => {
    if (!valid) return
    try {
      if (loginForm.rememberMe) {
        Cookies.set('username', loginForm.username, { expires: 30 })
        const enPwd = encrypt(loginForm.password)
        if (enPwd) {
          Cookies.set('password', enPwd, { expires: 30 })
        }
        if (loginForm.rememberMe) {
          Cookies.set('rememberMe', String(loginForm.rememberMe), { expires: 30 })
        }
      } else {
        Cookies.remove('username')
        Cookies.remove('password')
        Cookies.remove('rememberMe')
      }
      // 1.执行登录接口
      userStore
        .userLogin({ ...loginForm })
        .then(async () => {
          // 2.添加动态路由
          await initDynamicRouter()
          // 3.清空 tabs、keepAlive 数据
          tabsStore.setTabs([])
          keepAliveStore.setKeepAliveName([])

          // 4.跳转到首页
          router.push(HOME_URL)
          ElNotification({
            title: getTimeState(),
            message: `欢迎登录`,
            type: 'success',
            duration: 3000
          })
        })
        .catch(error => {
          console.log('登录失败', error)
          loading.value = false
          getCode()
          return
        })
    } finally {
      loading.value = false
    }
  })
}

// resetForm
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const getCodeBase64 = () => {
  getCodeImg().then((res: any) => {
    if (res.code === 200) {
      loginForm.uuid = res.data.uuid
      const img = res.data.img
      if (img.indexOf('data:image') > -1) {
        codeUrl.value = img
      } else {
        codeUrl.value = 'data:image/png;base64,' + img
      }
    }
  })
}

const getCode = lodashFunc(getCodeBase64, 10)
const getCookie = () => {
  const username = Cookies.get('username')
  const password = Cookies.get('password')
  const rememberMe = Cookies.get('rememberMe')
  // prettier-ignore
  loginForm.username = username === undefined ? loginForm.username : username;
  // prettier-ignore
  loginForm.password = password === undefined ? loginForm.password : decrypt(password) as string;
  // prettier-ignore
  loginForm.rememberMe = rememberMe === undefined ? false : Boolean(rememberMe);
}
getCookie()
getCode()

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

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