// import type { LockInfo } from '#/store';
import type { Nullable } from "@/typings/global";

import { defineStore } from "pinia";

import { LOCK_INFO_KEY } from "@/enums/cacheEnum";
import { useUserStore } from "./user";
import piniaPersistConfig from "@/config/piniaPersist";
import { Login } from "@/api/interface";

interface LockState {
  lockInfo: Nullable<LockInfo>;
}

// Lock screen information
interface LockInfo {
  // Password required
  psw?: string | undefined;
  // Is it locked?
  isLock?: boolean;
  /**
   * @description 是否仅需要重新登录
   */
  isLogin?: boolean;
}

export const useLockStore = defineStore({
  id: "app-lock",
  state: (): LockState => ({
    lockInfo: null
  }),
  getters: {
    getLockInfo(state): Nullable<LockInfo> {
      return state.lockInfo;
    }
  },
  actions: {
    setLockInfo(info: LockInfo) {
      this.lockInfo = Object.assign({}, this.lockInfo, info);
      console.log("this.lockInfo :>> ", this.lockInfo);
      // this.lockInfo = Object.assign({}, this.lockInfo, info);
      // Persistent.setLocal(LOCK_INFO_KEY, this.lockInfo, true);
    },
    resetLockInfo() {
      // Persistent.removeLocal(LOCK_INFO_KEY, true);
      this.lockInfo = null;
    },
    // Unlock
    async unLock(password: string, refresh?: boolean) {
      const userStore = useUserStore();
      // if (this.lockInfo?.psw === password) {
      //   this.resetLockInfo();
      //   return true;
      // }
      const tryLogin = async () => {
        try {
          const { userInfo, currentAccount } = userStore;
          const loginForm: Login.ReqLoginForm = {
            usercode: userInfo.usercode!,
            psw: password
            // account: currentAccount,
            // userid: userInfo.usercode!,
            // password: password,
            // clientType: 30,
            // typeName: "Website"
          };
          return await userStore.login(loginForm, null, false).then(
            res => {
              if (res) {
                this.resetLockInfo();
              }
              return Promise.resolve(res);
            },
            error => {
              return Promise.reject(error);
            }
          );
        } catch (error) {
          return Promise.reject(error);
        }
      };
      return await tryLogin();
    }
  },
  persist: piniaPersistConfig("app-lock")
});
