import { ref,getCurrentInstance } from "vue";
import { LoginParm } from "@/services/types/user/userModel";
import { store } from "@/store";
import { ElNotification } from 'element-plus';
import router from '@/router/index'
export default function useLogin(loginModel: LoginParm) {
    const { proxy } = getCurrentInstance() as any;
    //登录提交
    const login = async () => {
        //表单验证
        proxy.$refs.loginFormRef.validate(async (valid: boolean) => {
            if (valid) {
                loginState.value = true
                store.dispatch('user/login', loginModel).then((res: any) => {
                    loginState.value = false
                    if (res.code == 200) {
                        ElNotification({
                            title:'登录成功',
                            message:'欢迎回来',
                            type:'success',
                        })
                        //跳转到首页
                        setTimeout(()=> {
                            router.push({ path: '/' })
                        },1500)
                    } else {
                        ElNotification({
                            title:'登陆失败',
                            message:res.msg,
                            type:'error',
                        })
                    }
                }).catch((err) => {
                    loginState.value = false
                    ElNotification({
                        title:'登录失败',
                        message:err.message,
                        type:'error',
                    })
                })
            }
        })
    }
    //登录状态
    const loginState = ref(false)
    return {
        login,
        loginState
    }
}