import type { OverviewInfo } from '/#/store';

import { defineStore } from 'pinia';

import { LOCK_INFO_KEY } from '/@/enums/cacheEnum';
import { Persistent } from '/@/utils/cache/persistent';
import { useUserStore } from './user';

interface LockState {
  overviewInfo: Nullable<OverviewInfo> | {};
}

export const otherInfoStore = defineStore({
  id: 'other-info',
  state: (): LockState => ({
    overviewInfo:  {},
  }),
  getters: {
    getOverviewInfo(): OverviewInfo | null {
      if(JSON.stringify(this.overviewInfo) == "{}"){
        let jsonInfo = sessionStorage.getItem('overviewInfo')
        return jsonInfo?JSON.parse(jsonInfo):{}
      }else{
        return this.overviewInfo
      }
    },
  },
  actions: {
    setOverviewInfo(info: OverviewInfo) {
      this.overviewInfo = info;
      console.log('getOverviewInfo',this.overviewInfo,info)
      sessionStorage.setItem('overviewInfo',JSON.stringify(this.overviewInfo))
    },
    resetLockInfo() {
      Persistent.removeLocal(LOCK_INFO_KEY, true);
      this.overviewInfo = null;
    },
    async updateOverviewInfo(){
      if(this.getOverviewInfo.id){
        const overviewInfo = await this.getUserInfoAction();
        this.setOverviewInfo({
          ...overviewInfo,
        })
      }
    },
    // Unlock
    async unLock(password?: string) {
      const userStore = useUserStore();
      if (this.overviewInfo?.pwd === password) {
        this.resetLockInfo();
        return true;
      }
      const tryLogin = async () => {
        try {
          const username = userStore.getUserInfo?.username;
          const res = await userStore.login({
            username,
            password: password!,
            goHome: false,
            mode: 'none',
          });
          if (res) {
            this.resetLockInfo();
          }
          return res;
        } catch (error) {
          return false;
        }
      };
      return await tryLogin();
    },
  },
});
