import { defineStore } from 'pinia'
import piniaPersistConfig from '../helper/piniaPersist'
import { downloadProgress, reductionProgress } from '@/api'

export const useBackupStore = defineStore('backup', {
  // 相当于data
  state: () => {
    return {
      backup: {
        status: false,
        progress: undefined
      } as any,
      downloadBackup: {
        status: false,
        progress: 0
      },
      reductionBackup: {
        // 上传状态
        status: false,
        // 还原状态
        reductionStatus: false,
        // 上传进度
        progress: 0,
        // 还原进度
        reductionProgress: undefined
      } as any
    }
  },
  // 相当于计算属性
  getters: {
    getBackup: (state) => state.backup,
    getDownloadBackup: (state) => state.downloadBackup,
    getReductionBackup: (state) => state.reductionBackup
  },
  actions: {
    async setDownloadProgress(tenantId: string) {
      const progress: any = await downloadProgress({ tenantId })
      if (progress != 100 && progress != 0) {
        this.backup.status = true
      } else {
        this.backup.status = false
      }
      this.backup.progress = parseFloat(progress.toFixed(2))
    },
    async setReductionProgress(tenantId: string) {
      let progress: any = await reductionProgress({ tenantId })
      if (progress == 0) progress = undefined
      if (progress < 100 && progress != undefined) {
        this.reductionBackup.reductionStatus = true
      } else {
        this.reductionBackup.reductionStatus = false
      }
      if (progress != undefined)
        this.reductionBackup.reductionProgress = parseFloat(progress.toFixed(2))
    },
    setDownloadBackupProgress(progress: number) {
      this.downloadBackup.progress = progress
    },
    setDownloadBackupStatus(status: boolean) {
      this.downloadBackup.status = status
    },
    setReductionBackupProgress(progress: any, type: number = 1) {
      // type 0 上传 1 还原
      if (type) this.reductionBackup.progress = progress
      else this.reductionBackup.reductionProgress = progress
    },
    setReductionBackupStatus(status: boolean, type: number = 1) {
      // type 0 上传 1 还原
      if (type) this.reductionBackup.status = status
      else this.reductionBackup.reductionStatus = status
    }
  },
  persist: piniaPersistConfig('backup')
})
