import { defineStore } from 'pinia'
import { sessionStorage } from '@/plugins/storage'
import useFetch from '@/hooks/useFetch'
import { useRoute } from 'vue-router'

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
  markerPausedTimer: 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,
      markerPausedTimer: null,
    }
  },
  actions: {
    setMarkerPausedLimit(time: number) {
      if (time > 0 && this.markerPausedLimit == 0 && !this.markerPausedTimer) {
        this.markerPausedLimit = time
        this.markerPausedTimer = setInterval(() => {
          this.markerPausedLimit = this.markerPausedLimit - 50 < 0 ? 0 : this.markerPausedLimit - 50
          if (this.markerPausedLimit == 0) {
            this.markerPausedLimit = 0
            clearInterval(this.markerPausedTimer)
            this.markerPausedTimer = null
          }
        }, 50)
      }
    },
    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
      const route = useRoute()
      if (this.markerPausedLimit == 0 && route.name !== 'MarkingMark') {
        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
