import {
  createFolderApi,
  createResourceApi,
  deleteResourceApi,
  findAllFolderApi,
  updateResourceClassifyIdsApi,
  updateResourceNameApi,
  updateResourcePathApi
} from '@/api/system/resource'
import { download } from '@/utils/index'

export default {
  data: () => ({ contextmenu_position: null }),

  methods: {
    /**
     * 显示资源上下文菜单
     *
     * @param {Event} e
     * @param {Object} row
     */
    showResContextmenu (e, row, isSharePage = false) {
      this.contextmenu_data = row
      if (!isSharePage) {
        this.showContextmenu(e, [
          { label: '预览', action: 'toPreview' },
          { label: '重命名', action: 'toRename' }
        ]
          .concat(
            row.type === 'folder'
              ? []
              : [{ label: '复制', action: 'toCopy' }, { label: '剪切', action: 'toCut' }]
          )
          .concat([{ label: '删除', action: 'toDelete' }, { label: '下载', action: 'toDownload' }])
        , isSharePage)
      } else {
        this.showContextmenu(e, [
          { label: '预览', action: 'toPreview' }
        ]
          .concat(row.creator === this.$store.user.id ? [{ label: '重命名', action: 'toRename' }, { label: '删除', action: 'toDelete' }, { label: '下载', action: 'toDownload' }] : [])
        , isSharePage)
      }
    },

    /**
     * 显示上下文菜单
     *
     * @param {Event} e
     * @param {Object} menus
     */
    showContextmenu (e, menus = [], isSharePage = false) {
      if (this._pasteData_) {
        menus.unshift({ label: '粘贴', action: 'onPasteRes' })
      }
      if (this.find_params.path !== '/') {
        menus.push(
          { label: '返回根目录', action: 'toBackRoot' },
          { label: '返回上一级', action: 'toUpperLevel' }
        )
      }

      if (this.active_resources.length) {
        menus.push(
          { label: '取消选择', action: 'toCancelActiveResources' }
        )
      }

      this.contextmenu = [
        ...menus,
        { label: '上传文件', action: 'toUpload' },
        !isSharePage && { label: '新建文件夹', action: 'toCreateFolder' }
      ]

      this.contextmenu_position = `left:${e.pageX}px;top:${e.pageY}px`
    },

    /**
     * 取消选中
     */
    toCancelActiveResources () {
      this.active_resources = []
    },

    /**
     * 查找文件夹
     */
    async findAllFolder () {
      const { data } = await findAllFolderApi()

      const map = { '/': {} }

      for (const v of data) {
        v.key = (v.path + '/' + v.name).replace('//', '/')
        map[v.key] = v
      }

      for (const v of data) {
        if (!map[v.path].children) map[v.path].children = []
        map[v.path].children.push(v)
      }

      this.folderData = { map, tree: [{ key: '/', name: '/', path: '' }, ...map['/'].children] }
    },

    /**
     * 复制资源
     */
    toCopy (row) {
      const ids = [].concat(this.active_resources.length ? this.active_resources : row?.id || [])
      const data = []
      for (const v of this.res_list) {
        if (!ids.includes(v.id)) continue
        data.push({
          name: v.name + ' - 副本',
          ext: v.ext,
          diskname: v.diskname,
          type: v.type,
          mimetype: v.mimetype,
          size: v.size,
          classifyId: v.classifyId
        })
      }
      this._pasteData_ = { type: 'copy', path: this.find_params.path, data }
      this.$message.success(this._pasteData_.data.length + '个文件复制成功')
    },

    /**
     * 剪切资源
     */
    toCut (row) {
      this._pasteData_ = {
        type: 'cut',
        path: this.find_params.path,
        data: [].concat(this.active_resources.length ? this.active_resources : row?.id || [])
      }
      this.$message.success(this._pasteData_.data.length + '个文件剪切成功')
    },

    /**
     * 粘贴资源文件
     */
    onPasteRes () {
      return {
        cut: async () => {
          await updateResourcePathApi(this._pasteData_.data, this.find_params.path)
          this._pasteData_ = null
          this.findAllResource()
        },
        copy: async () => {
          for (const v of this._pasteData_.data) {
            v.path = this.find_params.path
          }
          await createResourceApi(this._pasteData_.data)
          this._pasteData_ = null
          this.pageInfo.current = 1
          this.findAllResource()
        }
      }[this._pasteData_.type]()
    },

    /**
     * 移动到文件夹
     *
     * @returns
     */
    async toMoveFolder () {
      const ids = [...this.active_resources]
      if (!ids.length) return this.$message.error('请选择资源文件')

      if (!this.folderData) await this.findAllFolder()
      this.moveFolder = []
      const h = this.$createElement
      await this.$msgbox({
        title: '请选择文件夹',
        message: h('el-cascader', {
          style: 'width:100%',
          props: {
            value: this.moveFolder,
            options: this.folderData.tree,
            props: { label: 'name', value: 'key', checkStrictly: true }
          },
          on: {
            change: (v) => (this.moveFolder = v)
          }
        }),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })

      if (!this.moveFolder.length) return

      await updateResourcePathApi(ids, this.moveFolder[this.moveFolder.length - 1])
      this.findAllResource()
    },

    /**
     * 移动到分类
     *
     * @returns
     */
    async toMoveClassify () {
      const ids = [...this.active_resources]
      if (!ids.length) return this.$message.error('请选择资源文件')

      this.moveClassify = []

      const h = this.$createElement
      await this.$msgbox({
        title: '请选择资源分类',
        message: h('el-cascader', {
          style: 'width:100%',
          props: {
            value: this.moveClassify,
            options: this.tree_list,
            props: { label: 'name', value: 'id', checkStrictly: true }
          },
          on: {
            change: (v) => (this.moveClassify = v)
          }
        }),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })

      if (!this.moveClassify.length) return

      await updateResourceClassifyIdsApi(ids, this.moveClassify)
      this.findAllResource()
    },

    /**
     * 删除资源
     *
     * @param {Object} row
     * @returns
     */
    async toDelete (row) {
      let ids = [].concat(this.active_resources.length ? this.active_resources : row?.id || [])

      if (!ids.length) return this.$message.error('请选择资源文件')
      if (!this.isSharePage) {
        await this.$store.inputCheckAdminPassword(`删除资源文件：${ids.length}个`)
      } else {
        if (this.res_list === undefined) return
        // 过滤自己的文件，才能删除
        ids = ids.filter(id => {
          const itemRes = this.res_list.find(item => item.id === id)
          return itemRes.creator === this.$store.user.id
        })
        if (ids.length === 0) return this.$message.error('请选择您上传的资源文件')
        await this.$confirm(`本次操作将会删除${ids.length}个资源文件`, '请确认')
      }

      await deleteResourceApi(ids)
      this.findAllResource()
    },

    /**
     * 创建文件夹
     */
    async toCreateFolder () {
      const filename = await this.showInputPrompt('请输入文件夹名称', {
        inputPattern: /^((?!\\|\/|:|\*|\?|<|>|\||\.).)+$/,
        inputErrorMessage: '文件夹名不能为空，且不能包含 \\ / : * ? < > | .'
      })
      await createFolderApi({ name: filename.trim(), path: this.find_params.path })
      this.folderData = null
      this.findAllResource()
    },

    /**
     * 重命名资源
     *
     * @param {Object} row
     * @returns
     */
    async toRename (row) {
      const filename = await this.showInputPrompt('请编辑文件名称', {
        inputValue: row.name,
        inputPattern: /^((?!\\|\/|:|\*|\?|<|>|\||\.).)+$/,
        inputErrorMessage: '文件夹名不能为空，且不能包含 \\ / : * ? < > | .'
      })

      if (row.name === filename) return

      await updateResourceNameApi(row.id, filename)
      this.findAllResource()
    },

    /**
     * 预览资源
     *
     * @param {Object} row
     * @returns
     */
    toPreview (row) {
      if (row.type === 'folder') {
        this.toCancelActiveResources()
        this.find_params.path = `${row.path}/${row.name}`.replace('//', '/')
        return
      }

      this.$store.showResourcePreviewDialog(row)
    },

    /**
     * 返回根目录
     */
    toBackRoot () {
      this.find_params.path = '/'
    },

    /**
     * 返回上一层
     */
    toUpperLevel () {
      this.find_params.path = this.find_params.path.replace(/(.*)\/.+$/g, '$1') || '/'
    },

    /**
     * 跳转到某一层目录
     *
     * @param {number} index
     */
    toChangePath (index) {
      this.find_params.path = this.find_params.path.split('/').slice(0, index + 2).join('/')
    },

    /**
     * 关闭上下文菜单
     */
    closeContextmenu () {
      this.contextmenu_position = null
      this.contextmenu_data = null
    },

    /**
     * 当上下文菜单被点击时
     * @param {Object} menu
     */
    onContextmenuClick (menu) {
      this[menu.action]?.(this.contextmenu_data)
      this.closeContextmenu()
    },

    /**
     * 资源下载
     */
    toDownload () {
      download(
        this.contextmenu_data.diskname.fileLinkTransfer(),
        `${this.contextmenu_data.name}.${this.contextmenu_data.ext}`
      ).catch((err) => {
        this.$message.error(err.message)
      })
    }
  }
}
