import { defineStore } from 'pinia'
import { sessionStorage } from '@/plugins/storage'
import useFetch from '@/hooks/useFetch'
import PauseIntervalWorker from '@/utils/pauseInterval.worker?worker'

import type { ExtractApiResponse } from '@/api/api'
interface MainStoreState {
  bootstrapTime: number
  loginSuccessTime: number
  serverTime: number
  diffTime: number
  loginInfo?: ExtractApiResponse<'userLogin'>
  myUserInfo?: ExtractApiResponse<'getMyUserInfo'>
  userMarkConfig: ExtractApiResponse<'getUserMarkConfig'>
  newMsgs: { newCount: number; messages: any[] }
  online: boolean
  lockScreenStatus: boolean
  keepAliveViews: any[]
  globalLoading: boolean
  paneSizeConfig: any
  showRowNextBottomDialog: boolean
  markerPausedLimit: number
  markerPausedWorker: any
}

interface MainStoreActions {
  getMyUserInfo: () => Promise<ExtractApiResponse<'getMyUserInfo'> | undefined>
  getUserMarkConfig: () => Promise<ExtractApiResponse<'getUserMarkConfig'> | undefined>
  setUserMarkConfig: (config: ExtractApiResponse<'getUserMarkConfig'>) => void
  setNewMsgs: (msgData: { newCount: number; messages: any[]; markerPausedLimit?: number }) => void
  setOnline: (bool: boolean) => void
  setLockScreen: (bool: boolean) => void
  setKeepAliveViews: (name: string) => void
  cutKeepAliveViews: (name: string) => void
  setGlobalLoading: (name: boolean) => void
  setPaneSizeConfig: (path: string, size: number) => void
  setRowNextBottomDialogStatus: (bool: boolean) => void
  setMarkerPausedLimit: (time: number) => void
}
const useMainStore = defineStore<'main', MainStoreState, Record<string, any>, MainStoreActions>('main', {
  state() {
    return {
      /** 进入系统的时间 */
      bootstrapTime: Date.now(),
      /** 登录成功时间 */
      loginSuccessTime: Date.now(),
      /** 服务器时间 */
      serverTime: Date.now(),
      /** 时间差 */
      diffTime: 0,
      /** 用户登录信息 */
      loginInfo: (sessionStorage.get('LOGIN_RESULT') as ExtractApiResponse<'userLogin'>) ?? void 0,
      /** 当前用户信息 */
      myUserInfo: void 0,
      /** 用户配置信息 */
      userMarkConfig: {},
      newMsgs: { newCount: 0, messages: [] },
      online: true,
      lockScreenStatus: sessionStorage.get('lockScreenStatus') == '1' ? true : false,
      keepAliveViews: ['MainLayout'],
      globalLoading: false,
      paneSizeConfig: localStorage.getItem('paneSizeConfig')
        ? JSON.parse(localStorage.getItem('paneSizeConfig') as string)
        : {},
      showRowNextBottomDialog: false,
      markerPausedLimit: 0,
      markerPausedWorker: null,
    }
  },
  actions: {
    setMarkerPausedLimit(time: number) {
      if (time > 0 && this.markerPausedLimit == 0 && !this.markerPausedWorker) {
        this.markerPausedLimit = time
        //开启worker线程执行定时器操作，不然的话，浏览器最小化或切换tab时，窗口的非活跃状态会导致setInterval或setTimeout等定时器休眠！
        this.markerPausedWorker = new PauseIntervalWorker()
        this.markerPausedWorker.postMessage(time)
        this.markerPausedWorker.onmessage = (e: any) => {
          const data = e.data
          this.markerPausedLimit = data
          if (data == 0) {
            //暂停时间结束时，页面解锁，同时销毁worker
            this.markerPausedWorker && this.markerPausedWorker.terminate()
          }
        }
      }
    },
    setRowNextBottomDialogStatus(bool: boolean) {
      this.showRowNextBottomDialog = bool
    },
    setPaneSizeConfig(path: string, size: number) {
      this.paneSizeConfig[path] = size
      localStorage.setItem('paneSizeConfig', JSON.stringify(this.paneSizeConfig))
    },
    setGlobalLoading(bool) {
      this.globalLoading = bool
    },
    setKeepAliveViews(name) {
      if (!this.keepAliveViews.includes(name)) {
        this.keepAliveViews.push(name)
      }
    },
    cutKeepAliveViews(name) {
      const index = this.keepAliveViews.indexOf(name)
      if (index > -1) {
        this.keepAliveViews.splice(index, 1)
      }
    },
    setLockScreen(bool: boolean) {
      this.lockScreenStatus = !!bool
      sessionStorage.set('lockScreenStatus', bool ? '1' : '0')
    },
    setOnline(bool: boolean) {
      this.online = !!bool
    },
    setNewMsgs(msgData) {
      this.newMsgs = msgData
      if (this.markerPausedLimit == 0 && location.pathname !== '/marking/mark') {
        this.setMarkerPausedLimit(msgData.markerPausedLimit || 0)
      }
    },
    async getMyUserInfo() {
      try {
        this.myUserInfo = await useFetch('getMyUserInfo').fetch()
        return this.myUserInfo
      } catch (error) {
        console.warn(error)
      }
    },
    async getUserMarkConfig() {
      try {
        this.userMarkConfig = await useFetch('getUserMarkConfig').fetch()
        return this.userMarkConfig
      } catch (error) {
        console.warn(error)
      }
    },
    async setUserMarkConfig(config: ExtractApiResponse<'getUserMarkConfig'>) {
      try {
        this.userMarkConfig = Object.assign({}, this.userMarkConfig, config)
        await useFetch('setUserMarkConfig').fetch({ config: JSON.stringify(this.userMarkConfig) })
      } catch (error) {
        console.warn(error)
      }
    },
  },
})

export default useMainStore
