<template>
    <ElContainer class="h-full bg-cover bg-center" @keyup.enter="login" :style="{ backgroundImage: `url(${bg})` }">
        <ElMain class="backdrop-blur1 dark:backdrop-brightness-50 !flex flex-col items-center justify-center">
            <span class="text-3xl font-[sh] text-white [text-shadow:_0_1px_0_rgb(0_0_0_/_40%)]">RCS</span>
            <ElCard class="w-full max-w-lg !rounded-xl mt-8 mb-16">
                <ElForm :model="model" :rules="rules" label-position="top" ref="form">
                    <ElFormItem prop="username" label="用户名">
                        <ElInput v-model="model.username"></ElInput>
                    </ElFormItem>
                    <ElFormItem prop="username" label="密码">
                        <ElInput type="password" v-model="model.password"></ElInput>
                    </ElFormItem>
                </ElForm>
                <el-button class="mt-8 w-full !block" type="primary" @click="login" :loading="loading">登录</el-button>
            </ElCard>
            <div class="fixed top-0 right-0 px-4 py-4">
                <DarkSwitch />
            </div>
        </ElMain>
    </ElContainer>
</template>
<script setup>
import { ref } from 'vue'
import DarkSwitch from '@/components/DarkSwitch.vue'
import { http } from '@/plugins/http'
import { useUserStore } from '@/stores/user'
import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import bg from '@/assets/2.jpg'

const router = useRouter()
const { user, setUser } = storeToRefs(useUserStore())
const model = ref({
    username: '',
    password: ''
})
const rules = {
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}
const form = ref(null)
const loading = ref(false)
function login() {
    form.value.validate().then(async () => {
        loading.value = true
        try {
            const res = await http.post(process.env.VITE_LOGIN_URL, model.value)
            http.setToken(res.access_token)
            router.replace({ name: 'home' })
            loading.value = false
        } catch (e) {
            loading.value = false
            ElMessage.error(e.message)
        }
    })
}
</script>
