<template>
    <up-loading-page :loading="showLoad" loading-text="跳转中,请耐心等待..." font-size="14"></up-loading-page>
    <global-page :showNavbar="false" v-if="!showLoad">
        <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, showLoad } 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'
import { getConfigDataApi, getSeatPermissionApi, getUserSeatListApi } from 'mocp/api/system'

watch(
    () => loginForm.username,
    debounce((value) => {
        if (value) {
            getGifCaptcha()
        }
    }, 500)
)
const userStore = useUserStore()
onLoad(() => {
    userStore.resetUserInfo()
    loginForm.verifyCode = ''
    getGifCaptcha()
    loginAmms()
})

//登录
const loading = ref(false)
const handleLogin = async () => {
    await loginFormRef.value?.validate()
    try {
        uni.showLoading({
            title: '登陆中...',
            mask: true
        })
        loading.value = true
        await login()
        if (userStore.token) {
            //加入席位权限
            await getUserSeatList()
            if (userStore.seatId) {
                await Promise.all([getSeatPermission(), getConfigData()])
            } else {
                userStore.setState('seatPermission', [])
            }
            //跳转工作台
            uni.$mocpJump.redirectTo('/tab/index')
        }
    } catch (error) {
        uni.$mocpMessage.error('登录失败')
    } finally {
        uni.hideLoading()
        loading.value = false
    }
}
//获取登录信息
const login = async () => {
    const res = await loginApi(toRaw(loginForm))
    if (res.code == 200) {
        userStore.setUserInfo(res.data)
    } else {
        uni.$mocpMessage.error(res.message)
    }
}
//获取席位信息
const getUserSeatList = async () => {
    const res = await getUserSeatListApi({ seatScene: '2' })
    if (res.code == 200) {
        if (res.data?.list?.length > 0) {
            userStore.setState('seatId', res.data.list[0].id)
        }
    }
}
//获取操作权限
const getSeatPermission = async () => {
    const res = await getSeatPermissionApi({ seatId: userStore.seatId })
    if (res.code == 200) {
        userStore.setState('seatPermission', res.data)
    }
}
//获取数据权限
const getConfigData = async () => {
    const res = await getConfigDataApi({ seatId: userStore.seatId })
    if (res.code == 200) {
        userStore.setState('configData', res.data)
    }
}
//接入amms
const loginAmms = () => {
    const ammsToken = uni.getStorageSync('access_token')
    if (ammsToken) {
        showLoad.value = true
        uni.request({
            url: `http://10.72.63.191:8080/mroapi/auth/oauth/check_token?token=${ammsToken}`,
            method: 'GET',
            header: {
                Authorization: 'Basic YXBwOmVraW5n'
            }
        })
            .then(function (res) {
                if (res.username) {
                    loginForm.username = res.data.username
                    loginForm.verifyCode = 'Mocp_DebuG_9527_8341'
                    loginForm.password = 'Ifar2016_0525'
                    handleLogin()
                }
            })
            .catch(function (reason) {
                console.log('AMMS跳转登录出现错误', reason)
            })
            .finally(() => {
                showLoad.value = false
            })
    }
}
</script>
<style lang="scss">
@import './constants/index.scss';
</style>
