<template>
  <div class="login-container flx-center">
    <div>
      <h2 class="logo-text">ECO-BOOT-WEB</h2>
      <div class="login-form">
        <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large" label-position="top">
          <el-form-item prop="account" label="账号">
            <el-input v-model="loginForm.account" placeholder="账号： superadmin"> </el-input>
          </el-form-item>
          <el-form-item prop="password" style="margin-bottom: 0" label="密码">
            <el-input v-model="loginForm.password" type="password" placeholder="密码： admin123" autocomplete="new-password"> </el-input>
          </el-form-item>
        </el-form>
        <div class="login-btn">
          <el-button round size="large" @click="resetForm(loginFormRef)"> 重置 </el-button>
          <el-button round size="large" type="primary" :loading="loading" @click="submitForm(loginFormRef)"> 登录 </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage, type FormInstance } from 'element-plus'
import { useUserStore } from '@/stores'
import router from '@/router'
import { LocationQuery } from 'vue-router'
import { initDynamicRouter } from '@/router/modules/dynamicRouter'
const loginFormRef = ref<FormInstance>()
const loading = ref(false)
const route = useRoute()
const userStore = useUserStore()
const loginForm = reactive({
  account: 'superadmin',
  password: 'admin123',
  grantType: 'password',
  clientId: '7daa6e9b-8876-4918-8a12-b68cbfcdc680',
  tenantId: '1'
})

const loginRules = reactive({
  account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
})

/**
 * 提交表单
 *
 * @param formEl 表单
 */
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      userStore.userLogin({ ...loginForm }).then(async res => {
        if (res.code === 200) {
          await initDynamicRouter()
          const { path, queryParams } = parseRedirect()
          router.push({ path: path, query: queryParams })
          ElMessage.success('提交成功')
        }
      })
    } else {
    }
  })
}

/**
 * 重置表单
 *
 * @param formEl 表单
 */
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const parseRedirect = () => {
  const query: LocationQuery = route.query
  const redirect = (query.redirect as string) ?? '/home'
  const url = new URL(redirect, window.location.origin)
  const path = url.pathname
  const queryParams: Record<string, string> = {}
  url.searchParams.forEach((value, key) => {
    queryParams[key] = value
  })
  return { path, queryParams }
}
</script>
<style lang="scss">
@use './index';
</style>
