<template>
    <global-page :showNavbar="false">
        <view class="login-wrap">
            <view class="login-header">
                <image src="/static/mocp/image/login/Vector.png" />
                <view class="title">海航技术</view>
            </view>
            <view class="login-title">
                <view class="p">登录你的账户</view>
                <view class="txt">请输入账号密码登录</view>
            </view>
            <up-form ref="loginFormRef" labelWidth="auto" :model="loginForm" :rules="rules" label-position="top">
                <up-form-item label="账号" prop="username">
                    <up-input v-model="loginForm.username" placeholder="请输入账号" clearable />
                </up-form-item>
                <up-form-item label="密码" prop="password">
                    <up-input v-model="loginForm.password" placeholder="请输入密码" clearable type="password" />
                </up-form-item>
                <up-form-item label="验证码" prop="verifyCode">
                    <view class="verify-code">
                        <up-input v-model="loginForm.verifyCode" placeholder="请输入验证码" 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>
                </up-form-item>
            </up-form>
            <view class="login-btn">
                <global-button size="large" type="primary" @tap="handleLogin" :loading="loading">登录</global-button>
            </view>
        </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 'mocp/store/user'
import { loginApi } from 'mocp/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.$mocpMessage.error(res.message)
    }
}
</script>
<style lang="scss">
@import './constants/index.scss';
</style>
