import { checkAdminPasswordApi, uploadApi } from '@/api/system/index'
import { findResourceApi } from '@/api/system/resource'
import { lst, getDistFile, getAcceptType } from '@/utils/index'

const store = {
  user: undefined,

  isOpenWin: location.hash.includes('win=1'),

  statistic_tab_active: 0,

  upload_dialog: { visible: false, form_data: undefined, tasks: [] },

  update_password_dialog: { visible: false },

  resource_preview_dialog: { visible: false, resource: null },

  class_notes_dialog: { visible: false },
  online_FAQ_Dialog: { visible: false },
  isFullscreen: false
}

const actions = {
  setUser (user) {
    if (!user) return
    lst.save('user', this.user = user)
  },
  setFullscreen (status) {
    this.$set(this, 'isFullscreen', status)
    this.isFullscreen = status
  },
  setToken (token) {
    if (!token) return
    lst.save('token', this.token = 'Bearer ' + token)
  },

  async logout (isShowTip) {
    if (isShowTip) await this.$confirm('将要退出登录，是否继续？', '退出提示', { type: 'warning' })
    lst.clear()
    window.location.reload()
  },

  showUpdatePasswordDialog () {
    this.update_password_dialog.visible = true
  },

  showUploadDialog (formData) {
    this.upload_dialog.visible = true
    this.upload_dialog.form_data = formData
  },

  showClassNotesDialog () {
    this.class_notes_dialog.visible = true
  },

  showOnlineFaqDialog () {
    this.online_FAQ_Dialog.visible = true
  },

  async showResourcePreviewDialog (resource) {
    if (!resource) return

    let res = resource.id ? resource : null
    if (!res) {
      const { data } = await findResourceApi(resource)
      res = data
    }
    this.resource_preview_dialog.resource = res
    this.resource_preview_dialog.visible = true
  },

  async upload () {
    const fs = await getDistFile()
    const tasks = []

    for (const file of fs) {
      const name = file.name
      if (file.size > 1024 * 1024 * 500) {
        return window.ELEMENT.Message.error(`文件【${file.name}】体积过大，上传失败`)
      }
      const type = getAcceptType(file.type)
      if (!type) {
        return window.ELEMENT.Message.error(`文件【${file.name}】的格式暂不支持`)
      }
      tasks.push({ name, file, size: file.size, status: 0, progress: 0, type })
    }

    Promise.allSettled(tasks.map(async (task, index) => {
      task.onUploadProgress = ({ loaded, total }) => {
        task.progress = loaded / total * 100 | 0
      }

      try {
        task.id = new Date().getTime() + Math.random().toString().substring(3, 8)
        this.upload_dialog.tasks.push(task)
        task.status = 1
        task.abortCtrl = new AbortController()
        await uploadApi(task.file, { data: this.upload_dialog.form_data, signal: task.abortCtrl.signal, onUploadProgress: task.onUploadProgress })
        task.status = 2
        this.$emit('onUploadSuccess', { task, index, tasks })
      } catch (err) {
        task.status = 3
        task.error = err
        this.$emit('onUploadError', task)
        throw err
      }
    })).then(() => {
      this.$emit('onUploadEnd', tasks)
    })
  },

  async inputCheckAdminPassword (title = '重要提示') {
    const { value } = await this.$prompt('请输入超级管理员密码', title, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputType: 'password',
      inputPattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,12}$/,
      inputPlaceholder: '请输入',
      inputErrorMessage: '密码输入不合法，若是初始密码请修改后再试'
    })

    return checkAdminPasswordApi(value)
  }
}

export default new window.Vue({
  data: store,
  methods: actions,
  created () {
    this.setUser(lst.get('user'))
  },

  computed: {
    ws () {
      if (!this.__WS__) {
        this.__WS__ = window.io(
          import.meta.env.VITE_APP_WS_URL,
          { transports: ['websocket'], auth: { token: lst.get('token') } }
        )
      }
      return this.__WS__
    }
  }
})
