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 num = ref(0);
  //登录提交
  const login = async () => {
    //表单验证
    proxy.$refs.loginFormRef.validate(async (valid: boolean) => {
      if (valid) {
        loginState.value = true;
        store
          .dispatch("user/login", loginModel)
          .then((res: any) => {
            if (res.code == 200) {
              ElNotification({
                title: "登录成功",
                message: "欢迎回来",
                type: "success",
              });
              //跳转到首页
              setTimeout(() => {
                router.push({ path: "/" });
                loginState.value = false;
              }, 1000);
            } else {
              loginState.value = false;
              num.value++;
              ElNotification({
                title: "登录失败",
                message: res.msg,
                type: "error",
              });
            }
          })
          .finally(() => {
            loginState.value = false;
          });
      }
    });
  };
  //登录状态
  const loginState = ref(false);
  return {
    login,
    num,
    loginState,
  };
}
