import { ref, reactive } from 'vue'
import { v4 } from 'uuid'
import { useLoginStore } from '@/stores'
import { initBaseData } from '@/business/common'
import eventBus from '@/services/bus'

export function useAuth() {
    const { userLogin } = useLoginStore()
    const loading = ref(false)
    const user = reactive<Proto.LoginReq>({
        LoginID: localStorage.getItem('thj_app_loginid') ?? '',
        LoginPWD: '',
        GUID: '',
        LoginType: 0,
        ClientType: 4,
        Version: '2.0.0.0',
        DeviceID: ''
    })

    // 用户登录
    const login = async () => {
        loading.value = true
        const catchError = (err: string) => {
            loading.value = false
            return Promise.reject(err)
        }

        await userLogin({ ...user, GUID: v4() }).then(() => {
            localStorage.setItem('thj_app_loginid', user.LoginID)
        }).catch((err) => catchError(err))

        await initBaseData().catch((err) => catchError(err))
    }

    // 用户登出
    const logout = () => {
        eventBus.$emit('LogoutNotify')
    }

    return {
        loading,
        user,
        login,
        logout,
    }
}