<template>
  <sign-layout class="user-login" :title="t('auth.login.title')">
    <el-form ref="formRef" :model="formData" :rules="formRules">
      <el-form-item prop="accountCode">
        <el-input :placeholder="t('auth.login.accountCode')" v-model="formData.accountCode"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password" :placeholder="t('auth.login.password')" v-model="formData.password">
        </el-input>
      </el-form-item>
      <el-form-item prop="verifyCode">
        <el-input :placeholder="t('auth.login.verifyCode')" v-model="formData.verifyCode">
          <template #append>
            <img :src="verifyImage" />
          </template>
        </el-input>
      </el-form-item>
      <!-- <el-form-item>
        <el-checkbox label="记住账号" v-model="remember"></el-checkbox>
      </el-form-item> -->
      <el-form-item>
        <el-button class="submit" type="primary" :loading="loading" @click="formSubmit">
          <span v-if="loading">{{ t('auth.login.loading') }}</span>
          <span v-else>{{ t('operation.login') }}</span>
        </el-button>
        <!-- <el-button>注册</el-button> -->
      </el-form-item>
    </el-form>
  </sign-layout>
</template>

<script lang="ts" setup>
import { shallowRef } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { verifyCode } from '@/services/api/user'
import { useLogin } from '@/business/login'
import { useRouterStore, i18n } from '@/stores'
import service from '@/services'
import SignLayout from '../components/layout/index.vue'

const { formData, userLogin } = useLogin()
const route = useRoute()
const router = useRouter()
const menuStore = useRouterStore()
const formRef = shallowRef<FormInstance>()
const loading = shallowRef(false)
//const remember = shallowRef(false) // 记住账号
const verifyImage = shallowRef('') // 验证码图片

const { global: { t } } = i18n

const formRules: FormRules = {
  accountCode: [
    { required: true, max: 20, message: t('common.pleaseenter'), trigger: 'blur' }
  ],
  password: [
    { required: true, max: 32, message: t('common.pleaseenter'), trigger: 'blur' }
  ]
}

const formSubmit = () => {
  loading.value = true
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        await userLogin()
        await menuStore.getUserRoutes()
        const redirect = route.query.redirect
        if (redirect) {
          router.replace(redirect.toString())
        } else {
          router.replace('/')
        }
      } catch (err) {
        loading.value = false
        ElMessage.error(err as string)
      }
    }
  })
}

service.onReady().then(() => {
  verifyCode().then(({ data }) => {
    formData.key = data.key
    verifyImage.value = data.img
  })
})
</script>

<style lang="less" scoped>
@import './index.less';
</style>