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

/**全局遮罩信息类型 */
type MaskStateType = {
  /**锁屏类型 */
  type: 'none' | 'lock' | 'reload' | 'reset';
  /**lock 锁屏密码*/
  lockPasswd: string;
  /**lock 超时锁屏时间，秒*/
  lockTimeout: number;
};

const useMaskStore = defineStore('mask', {
  state: (): MaskStateType => ({
    type: (localGet(CACHE_LOCAL_MASK) || 'none') as MaskStateType['type'],
    lockPasswd: localGet(CACHE_LOCAL_LOCK_PASSWD) || '',
    lockTimeout: 0,
  }),
  getters: {},
  actions: {
    // 检查服务等待-轮询
    async checkServiceWait() {
      try {
        const res = await getSysConf();
        if (res.code === RESULT_CODE_SUCCESS && res.data) {
          // 延迟5秒
          setTimeout(() => {
            this.handleMaskType('none');
            window.location.reload();
          }, 2_000);
        } else {
          // 延迟5秒
          setTimeout(() => {
            this.checkServiceWait();
          }, 5_000);
        }
      } catch (error) {
        // 延迟5秒
        setTimeout(() => {
          this.checkServiceWait();
        }, 5_000);
      }
    },
    // 设置遮罩类型
    async handleMaskType(type: MaskStateType['type']) {
      this.type = type;
      localSet(CACHE_LOCAL_MASK, type);
      if (type === 'reload') {
        // 延迟5秒
        setTimeout(() => {
          this.checkServiceWait();
        }, 5_000);
      }
      if (type === 'lock') {
        localSet(CACHE_LOCAL_LOCK_PASSWD, this.lockPasswd);
      } else {
        localRemove(CACHE_LOCAL_LOCK_PASSWD);
      }
    },
  },
});

export default useMaskStore;
