<template>
    <global-page :showNavbar="false">
        <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>
            <global-button class="login-btn" size="large" type="primary" @tap="handleLogin" :loading="loading">登录</global-button>
        </view>
    </global-page>
</template>

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

watch(
    () => loginForm.username,
    debounce((value) => {
        if (value) {
            getGifCaptcha()
        }
    }, 500)
)
onLoad(() => {
    loginForm.verifyCode = ''
    getGifCaptcha()
})

//登录
const loading = ref(false)
const userStore = useUserStore()
const handleLogin = async () => {
    await loginFormRef.value?.validate()
    loading.value = true
    const res = await loginApi(toRaw(loginForm), { loading: '登陆中...' })
    loading.value = false
    if (res.code == 200) {
        userStore.setUserInfo(res.data)
    } else {
        uni.$message.showToast(res.message)
    }
}
</script>

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