<template>
    <custom-page>
        <view class="login-wrap">
            <view class="login-header">
                <image src="/static/image/login/Vector.png" />
                <view class="title">海航技术</view>
            </view>
            <view class="login-title">
                <view class="p">登录你的账户</view>
                <view class="txt">请输入账号密码登录</view>
            </view>
            <uni-forms ref="loginFormRef" :modelValue="loginForm" :rules="rules" label-position="top">
                <uni-forms-item label="账号" name="username">
                    <uni-easyinput v-model="loginForm.username" placeholder="请输入账号" type="text" />
                </uni-forms-item>
                <uni-forms-item label="密码" name="password">
                    <uni-easyinput v-model="loginForm.password" placeholder="请输入密码" type="password" />
                </uni-forms-item>
                <uni-forms-item label="验证码" name="verifyCode">
                    <view class="verify-code">
                        <uni-easyinput v-model="loginForm.verifyCode" placeholder="请输入验证码" type="text" style="flex: auto" />
                        <image class="verify-code-image" v-if="loginCode && loginForm.username" :src="loginCode" mode="scaleToFill" @tap="getGifCaptcha" />
                        <view class="verify-code-image" v-else></view>
                    </view>
                </uni-forms-item>
            </uni-forms>
            <custom-button class="login-btn" size="large" type="primary" @tap="handleLogin">登录</custom-button>
        </view>
    </custom-page>
</template>

<script setup>
import { ref, toRaw, watch } from 'vue'
import { loginApi } from '@/api/user'
import { debounce } from 'lodash'
import message from '@/utils/message'
import useUserStore from '@/store/modules/user'
import { loginCode, loginForm, rules } from './constants/index.compositions'
import { getGifCaptcha } from './constants/index.functionals'
import { onLoad } from '@dcloudio/uni-app'

watch(
    () => loginForm.username,
    debounce((value) => {
        if (value) {
            getGifCaptcha()
        }
    }, 500)
)
//登录
const userStore = useUserStore()
const loginFormRef = ref()
const handleLogin = async () => {
    await loginFormRef.value?.validate()
    const res = await loginApi(toRaw(loginForm), { loading: '登陆中...' })
    if (res.code == 200) {
        userStore.setUserInfo(res.data)
    } else {
        message.error({ title: res.message })
    }
}
onLoad(() => {
    getGifCaptcha()
})
</script>

<style lang="scss">
@import './constants/index.scss';
</style>
