<template>
  <login-layout v-if="user.isEnterprise() ? user.themeInfo : true" v-loading="loading">
    <LoginContainer subTitle="欢迎使用 快际新云 智能知识库">
      <el-form
          class="login-form"
          :rules="rules"
          :model="loginForm"
          ref="loginFormRef"
          @keyup.enter="login"
      >
        <el-form-item prop="username" class="mb-[30px]">
          <el-input
            size="large"
            class="input-item"
            v-model="loginForm.email"
            placeholder="请输入用户名"
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="password" class="mb-[30px]">
          <el-input
            type="password"
            size="large"
            class="input-item"
            v-model="loginForm.password"
            placeholder="请输入密码"
            show-password
          >
          </el-input>
        </el-form-item>
      </el-form>
      <el-button size="large" type="primary" class="w-full" @click="login">登录</el-button>
    </LoginContainer>
  </login-layout>
</template>
<script setup lang="ts">
import {ref, onBeforeMount} from 'vue'
import type {LoginRequest} from '@/api/type/user'
import {useRouter} from 'vue-router'
import type {FormInstance, FormRules} from 'element-plus'
import useStore from '@/stores'
import { loginPort, userInfo } from '@/utils/api'

const loading = ref<boolean>(false)
const {user} = useStore()
const router = useRouter()
const loginForm = ref<LoginRequest>({
  email: '',
  password: ''
})

const rules = ref<FormRules<LoginRequest>>({
  email: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    }
  ]
})
const loginFormRef = ref<FormInstance>()

const login = () => {
  loginFormRef.value?.validate().then(() => {
    loading.value = true
    loginPort(loginForm.value).then((res) => {
      res && userInfo().then(res => {
        sessionStorage.setItem("userInfo", JSON.stringify(res));
        const timer = setTimeout(() => {
          router.push({name: 'home'});
          loading.value = false;
          clearTimeout(timer);
        }, 300)
      })
    }).catch(() => {
      loading.value = false;
    })
  })
}

onBeforeMount(() => {
  if (user.isEnterprise()) {
    user.theme(loading)
  }
})
</script>
<style lang="scss" scoped>
.login-gradient-divider {
  position: relative;
  text-align: center;
  color: var(--el-color-info);

  ::before {
    content: '';
    width: 25%;
    height: 1px;
    background: linear-gradient(90deg, rgba(222, 224, 227, 0) 0%, #dee0e3 100%);
    position: absolute;
    left: 16px;
    top: 50%;
  }

  ::after {
    content: '';
    width: 25%;
    height: 1px;
    background: linear-gradient(90deg, #dee0e3 0%, rgba(222, 224, 227, 0) 100%);
    position: absolute;
    right: 16px;
    top: 50%;
  }
}

.login-button-circle {
  padding: 25px !important;
}
</style>
