<template>
  <div class="grid full login-view">
    <div class="login-modal">
      <div class="p-l-large p-r-large login-modal-header">
        <span>欢迎登录</span>
        <span class="version">版本号：V{{ version }}</span>
      </div>
      <div class="login-modal-content">
        <base-form
          ref="formRef"
          :model="loginModel"
          :disabled="loading"
          :items="formItems"
          :rules="loginRules"
          size="large"
        >
          <template #form-item-password>
            <el-input
              ref="pwdRef"
              v-model="loginModel.password"
              type="password"
              clearable
              placeholder="请输入登录密码"
              show-password
              @keydown="pwdKeyDown"
            ></el-input>
          </template>
          <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, ElInput } 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, localStorage } from '@/plugins/storage'
import { initConfigModelData } from '@/utils/common'

import type { EpFormItem, EpFormRules } from 'global-type'
import type { ExtractApiParams, ExtractApiResponse } from '@/api/api'
const pwdRef = ref(null)
const { replace } = useRouter()

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

const { loading, fetch: login } = useFetch('userLogin')
const { result: version, fetch: fetchVersion } = useFetch('getVersion', 'get')
fetchVersion()

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: '请输入登录账号',
      onKeydown(event: any) {
        if (event.keyCode == 13) {
          if (loginModel.password.length > 0) {
            onSubmit()
          } else {
            ;(pwdRef.value as any).ref.focus()
          }
        }
      },
    },
  },
  {
    prop: 'password',
    slotName: 'password',
  },
])
const pwdKeyDown = (e: any) => {
  if (e.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.error(error)
  }
}

function loginSuccess(loginInfo: ExtractApiResponse<'userLogin'>) {
  mainStore.setMarkerPausedLimit(loginInfo.markerPausedLimit || 0)
  /** sessionStorage 缓存login result */
  sessionStorage.set('LOGIN_RESULT', loginInfo)
  let config: any = localStorage.get('USER_CONFIG')
  if (!config) {
    localStorage.set('USER_CONFIG', { [loginInfo.id]: initConfigModelData() })
  } else {
    if (!config[loginInfo.id]) {
      config[loginInfo.id] = initConfigModelData()
      localStorage.set('USER_CONFIG', config)
    }
  }
  /** pinia store 存储 login result */
  mainStore.loginInfo = loginInfo

  mainStore.loginSuccessTime = Date.now()

  mainStore.getUserMarkConfig()

  mainLayoutStore.getRenderMenuList().then((renderMenus: any) => {
    let path = '/analysis'
    let find = renderMenus.find((item: any) => item.index === 'analysis')
    if (find && (find.children || []).find((v: any) => v.index === 'analysis-monitoring')) {
      path = '/analysis/monitoring'
    }
    /**
     * 超级管理员每次登录完成之后需要选择考试批次
     * 其它角色如果是首次登录,需要去设置名称.
     * 否则大小组长进入监控首页, 评卷员进入评卷首页
     */
    if (loginInfo.role !== 'ADMIN') {
      if (!loginInfo.needRealName) {
        mainStore.getMyUserInfo()
      }
      let next =
        loginInfo.needRealName || loginInfo.needRealEmployer
          ? { name: 'InitUserName' }
          : loginInfo.role === 'MARKER'
          ? { name: 'MarkingMark' }
          : { path: path }
      // : { path: renderMenus[0].path || '/' }

      replace(next)
      // replace({
      //   name: loginInfo.needRealName
      //     ? 'InitUserName'
      //     : loginInfo.role === 'MARKER'
      //     ? 'MarkingMark'
      //     : 'AnalysisMonitoring',
      // })
    } else {
      replace({ name: 'CheckExam' })
    }
  })
}

function initLogin() {
  const dialogModeBeforeSubmit = sessionStorage.get('dialogModeBeforeSubmit')
  const lockScreenStatus = sessionStorage.get('lockScreenStatus')
  sessionStorage.clear()
  dialogModeBeforeSubmit && sessionStorage.set('dialogModeBeforeSubmit', dialogModeBeforeSubmit)
  lockScreenStatus && sessionStorage.set('lockScreenStatus', lockScreenStatus)
  mainStore.$reset()
}

initLogin()
</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;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .version {
        color: #ccf2ff;
        font-size: 16px;
      }
    }
    .login-modal-content {
      height: 336px;
      padding: 52px 80px;
      position: relative;
    }
  }
}
</style>
