<template>
  <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col-style="{ display: 'none' }"
      :wrapper-col-style="{ flex: 1 }"
      size="large"
      @submit="handleLogin"
  >
    <a-form-item field="cardNumber" hide-label>
      <a-input v-model="form.cardNumber" placeholder="请刷卡" allow-clear @keyup.enter="handleLogin" />
    </a-form-item>
    <a-form-item>
      <a-space direction="vertical" fill class="w-full">
        <a-button type="primary" :loading="loading" html-type="submit" size="large" long>立即登录</a-button>
      </a-space>
    </a-form-item>
  </a-form>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { type FormInstance, Message } from '@arco-design/web-vue'
import { useTabsStore, useUserStore } from '@/stores'

const formRef = ref<FormInstance>()
const form = reactive({
  cardNumber: '',
})

const rules: FormInstance['rules'] = {
  cardNumber: [
    { required: true, message: '请刷卡或输入卡号' },
  ],
}

const userStore = useUserStore()
const tabsStore = useTabsStore()
const router = useRouter()
const loading = ref(false)

// 登录
const handleLogin = async () => {
  const isInvalid = await formRef.value?.validate()
  if (isInvalid) return
  try {
    loading.value = true
    // 调用后端接口校验卡号
    await userStore.cardLogin(form)
    tabsStore.reset()
    const { redirect, ...othersQuery } = router.currentRoute.value.query
    await router.push({
      path: (redirect as string) || '/',
      query: {
        ...othersQuery,
      },
    })
    Message.success('欢迎使用')
  } catch (error) {
    // 登录失败处理
  } finally {
    loading.value = false
  }
}

// 监听键盘输入，实现自动识别卡号
onMounted(() => {
  // 监听全局键盘事件，用于识别刷卡输入
  document.addEventListener('keydown', (e) => {
    // 刷卡器通常会快速输入卡号并以Enter键结束
    if (e.key === 'Enter') {
      // 遇到Enter键，尝试登录
      if (form.cardNumber.trim()) {
        handleLogin()
      }
    } else if (e.key.length === 1 && !e.ctrlKey && !e.altKey && !e.metaKey) {
      // 只捕获单个字符的按键，忽略控制键和功能键
      form.cardNumber += e.key
    } else if (e.key === 'Backspace') {
      // 处理退格键
      form.cardNumber = form.cardNumber.slice(0, -1)
    }
  })
})
</script>

<style scoped lang="scss">
.arco-input-wrapper,
:deep(.arco-select-view-single) {
  height: 40px;
  border-radius: 4px;
  font-size: 13px;
}

.arco-input-wrapper.arco-input-error {
  background-color: rgb(var(--danger-1));
  border-color: rgb(var(--danger-3));
}
.arco-input-wrapper.arco-input-error:hover {
  background-color: rgb(var(--danger-1));
  border-color: rgb(var(--danger-6));
}

.arco-input-wrapper :deep(.arco-input) {
  font-size: 13px;
  color: var(--color-text-1);
}
.arco-input-wrapper:hover {
  border-color: rgb(var(--arcoblue-6));
}



.btn {
  height: 40px;
}
</style>