<template>
  <div class="grid full login-view">
    <div class="login-modal">
      <div class="p-l-large login-modal-header">欢迎登录</div>
      <div class="login-modal-content">
        <base-form
          ref="formRef"
          :model="loginModel"
          :disabled="loading"
          :items="formItems"
          :rules="loginRules"
          size="large"
        >
          <el-button type="primary" class="full-w m-t-base" :loading="loading" @click="onSubmit"> 立即登录 </el-button>
        </base-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="Login">
import { reactive, shallowRef, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElButton } from 'element-plus'
import BaseForm from '@/components/element/BaseForm.vue'
import useMainStore from '@/store/main'
import useMainLayoutStore from '@/store/layout'
import useFetch from '@/hooks/useFetch'
import useForm from '@/hooks/useForm'
import { sessionStorage } from '@/plugins/storage'

import type { EpFormItem, EpFormRules } from 'global-type'
import type { ExtractApiParams, ExtractApiResponse } from 'api-type'

const { replace } = useRouter()

const mainStore = useMainStore()
const mainLayoutStore = useMainLayoutStore()

const { loading, fetch: login } = useFetch('userLogin')

const { formRef, elFormRef } = useForm()

const loginModel = reactive<ExtractApiParams<'userLogin'>>({ loginName: '', password: '' })

const loginRules: EpFormRules = {
  loginName: [{ required: true, message: '请输入登录账号' }],
  password: [{ required: true, message: '请输入登录密码' }],
}

const formItems = shallowRef<EpFormItem[]>([
  {
    slotType: 'input',
    prop: 'loginName',
    slot: {
      placeholder: '请输入登录账号',
    },
  },
  {
    slotType: 'input',
    prop: 'password',
    slot: {
      type: 'password',
      placeholder: '请输入登录密码',
      clearable: true,
      showPassword: true,
      onKeydown(event) {
        if ((event as KeyboardEvent).key === 'Enter') {
          onSubmit()
        }
      },
    },
  },
])

async function onSubmit() {
  if (!elFormRef?.value) {
    return
  }
  try {
    await elFormRef.value.validate()
    const loginResult = await login(loginModel)
    loginSuccess(loginResult)
  } catch (error) {
    console.log(error)
  }
}

function loginSuccess(loginInfo: ExtractApiResponse<'userLogin'>) {
  /** sessionStorage 缓存login result */
  sessionStorage.set('LOGIN_RESULT', loginInfo)
  /** pinia store 存储 login result */
  mainStore.loginInfo = loginInfo

  mainLayoutStore.getRenderMenuList()
  /**
   * 超级管理员每次登录完成之后需要选择考试批次
   * 其它角色如果是首次登录,需要去设置名称.
   * 否则大小组长进入监控首页, 评卷员进入评卷首页
   */
  if (loginInfo.role !== 'ADMIN') {
    if (loginInfo.name) {
      mainStore.getMyUserInfo()
    }
    replace({
      name: !loginInfo.name ? 'InitUserName' : loginInfo.role === 'MARKER' ? 'MarkingMark' : 'AnalysisMonitoring',
    })
  } else {
    replace({ name: 'CheckExam' })
  }
}
</script>

<style scoped lang="scss">
.login-view {
  place-items: center;
  .login-modal {
    width: 480px;
    height: 416px;
    background: $LoginModalBg;
    border-radius: $LoginModalRadius;
    overflow: hidden;
    .login-modal-header {
      height: $LoginModalHeaderHeight;
      line-height: $LoginModalHeaderHeight;
      background: $LoginModalHeaderBg;
      font-size: $LoginModalHeaderFontSize;
      font-weight: normal;
      color: $LoginModalHeaderFontColor;
    }
    .login-modal-content {
      height: 336px;
      padding: 52px 80px;
    }
  }
}
</style>
