import { login } from "@/api/login";
const useUserStore = defineStore("userStore", {
  state: () => {
    return {
      isLogin: false, //是否登录
      token: "", //登录token
      key: "", //密钥
      role: [], //用户权限
      temp: "", //账号
      other: "", //密码
      pwd: "",
      form: {
        name: "",
        password: "",
        captcha: "",
      },
    };
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: "user_store",
        paths: ["isLogin", "token", "temp", "other"],
        storage: sessionStorage,
      },
    ],
  },
  actions: {
    // 更改用户权限
    changeRole() {},
    // 获取用户信息
    getUserInfo() {},
    async submit() {
      const { name, password, captcha } = this.form;
      if (!name || !password) {
        ElMessage.error("账号或密码不能为空");
        return false;
      }
      // if (!captcha) {
      //   ElMessage.error("验证码不能为空");
      //   return false;
      // }

      const res = await login({ name, password, captcha });
      if (res && res.code === 0) {
        const tk = res?.data?.token || "";
        this.token = tk;
        this.isLogin = true;
        return true;
      } else {
        ElMessage.error(res?.message || "登录失败");
        return false;
      }
    },
    logout() {
      this.isLogin = false;
      this.token = "";
    },
  },
});

export default useUserStore;
