import { getSysConf } from '@/api';
import { CACHE_LOCAL_LOCK } from '@/constants/cache-keys-constants';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import { localGet, localSet } from '@/utils/cache-local-utils';
import { defineStore } from 'pinia';

/**锁屏信息类型 */
type Locked = {
  /**锁屏类型 */
  type: 'none' | 'lock' | 'reload' | string;
  /**lock 超时锁屏时间，秒*/
  lockTimeout: number;
};

const useLockedStore = defineStore('locked', {
  state: (): Locked => ({
    type: localGet(CACHE_LOCAL_LOCK) || 'none',
    lockTimeout: 0,
  }),
  getters: {},
  actions: {
    // 重启等待-轮询
    async relaodWait() {
      try {
        const res = await getSysConf();
        if (res.code === RESULT_CODE_SUCCESS && res.data) {
          this.fnLock('none');
          window.location.reload();
        }
      } catch (error) {
        // 延迟5秒
        setTimeout(() => {
          this.relaodWait();
        }, 5_000);
      }
    },
    // 设置锁定
    async fnLock(type: 'none' | 'lock' | 'reload' | string) {
      this.type = type;
      localSet(CACHE_LOCAL_LOCK, type);
      if (type === 'reload') {
        // 延迟5秒
        setTimeout(() => {
          this.relaodWait();
        }, 2_000);
      }
    },
  },
});

export default useLockedStore;
