<template>
  <div class="login">
    <!-- 登录框 -->
    <div class="login-box">
      <!-- 顶部区域，包含logo -->
      <div class="top">
        <div class="logo">
          <img src="~@/assets/img/login-logo.png" alt="Logo">
        </div>
      </div>
      <!-- 中间区域，包含登录表单 -->
      <div class="mid">
        <el-form
          ref="dataFormRef"
          :model="dataForm"
          :rules="dataRule"
          status-icon
          @keyup.enter="dataFormSubmit()"
        >
          <!-- 用户名输入框 -->
          <el-form-item prop="userName">
            <el-input
              v-model="dataForm.userName"
              class="info"
              placeholder="帐号"
            />
          </el-form-item>
          <!-- 密码输入框 -->
          <el-form-item prop="password">
            <el-input
              v-model="dataForm.password"
              class="info"
              type="password"
              placeholder="密码"
            />
          </el-form-item>
          <!-- 登录按钮 -->
          <el-form-item>
            <div class="item-btn">
              <input
                type="button"
                value="登录"
                @click="dataFormSubmit()"
              >
            </div>
          </el-form-item>
        </el-form>
      </div>
      <!-- 底部版权信息 -->
      <div class="bottom">
        Copyright © 2019 广州市蓝海创新科技有限公司
      </div>
    </div>
    <!-- 验证组件，用于显示图形验证码 -->
    <Verify
      ref="verifyRef"
      :captcha-type="'blockPuzzle'"
      :img-size="{width:'400px',height:'200px'}"
      @success="login"
    />
  </div>
</template>

<script setup>
import { encrypt } from '@/utils/crypto' // 加密工具函数
import { getUUID } from '@/utils' // 获取唯一标识符的工具函数
import Verify from '@/components/verifition/Verify.vue' // 验证组件
import cookie from 'vue-cookies' // cookies操作库
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import http from '@/api/http'

// 定义表单数据对象
const dataForm = ref({
  userName: '',
  password: '',
  uuid: '',
  captcha: ''
})

// 定义表单验证规则
const dataRule = {
  userName: [
    { required: true, message: '帐号不能为空', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '验证码不能为空', trigger: 'blur' }
  ]
}

// 生命周期钩子：在组件卸载前移除全局事件监听器
onBeforeUnmount(() => {
  document.removeEventListener('keyup', handerKeyup)
})

// 生命周期钩子：组件挂载后初始化
onMounted(() => {
  getCaptcha()
  document.addEventListener('keyup', handerKeyup)
})

// 处理键盘事件，实现回车键提交表单
const handerKeyup = (e) => {
  const keycode = e.which || e.keyCode
  if (keycode === 13) {
    dataFormSubmit()
  }
}

// 验证组件引用
const verifyRef = ref(null)
// 表单引用
const dataFormRef = ref(null)
let isSubmit = false

/**
 * 提交表单
 */
const dataFormSubmit = () => {
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      verifyRef.value?.show() // 显示验证码组件
    }
  })
}

// 路由实例
const router = useRouter()

/**
 * 登录逻辑处理
 * @param {Object} verifyResult - 验证成功后的结果
 */
const login = (verifyResult) => {
  if (isSubmit) return
  isSubmit = true
  http({
    url: http.adornUrl('/adminLogin'),
    method: 'post',
    data: http.adornData({
      userName: dataForm.value.userName,
      passWord: encrypt(dataForm.value.password),
      captchaVerification: verifyResult.captchaVerification
    })
  }).then(({ data }) => {
    cookie.set('Authorization', data.accessToken) // 设置授权令牌到cookie
    router.replace({ name: 'home' }) // 跳转到首页
  }).catch(() => {
    isSubmit = false
  })
}

/**
 * 获取验证码
 */
const getCaptcha = () => {
  dataForm.value.uuid = getUUID() // 生成并设置uuid
}
</script>

<style lang="scss" scoped>
.login {
  width: 100%;
  height: 100%;
  background: url('../../../assets/img/login-bg.png') no-repeat;
  background-size: cover;
  position: fixed;

  .login-box {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    height: 100%;
    padding-top: 10%;

    .top {
      margin-bottom: 30px;
      text-align: center;

      .logo {
        font-size: 0;
        max-width: 50%;
        margin: 0 auto;
      }

      &:deep(.company) {
        font-size: 16px;
        margin-top: 10px;
      }
    }

    .mid {
      font-size: 14px;

      .item-btn {
        width: 410px;
        margin-top: 20px;

        input {
          border: 0;
          width: 100%;
          height: 40px;
          background: #1f87e8;
          color: #fff;
          border-radius: 3px;
        }
      }
    }

    .bottom {
      position: absolute;
      bottom: 10%;
      width: 100%;
      color: #999;
      font-size: 12px;
      text-align: center;
    }
  }
}

.info {
  width: 410px;
}

:deep(.login-captcha) {
  height: 40px;
}
</style>
