<template>
  <ui-page
    class="bi-disk-manage-list"
    :query-method="handleQueryData"
  >
    <template slot="head-left">
      <div class="bi-disk-manage-list__position">
        <div class="bi-disk-manage-list__position-breadcrumb">
          <ui-breadcrumb
            size="large"
          >
            <ui-breadcrumb-item
              :to="`${rootPath}/${category}`"
              @click.native="handleBreadcrumbRootClick"
            >{{ categoryText }}</ui-breadcrumb-item>
            <ui-breadcrumb-item
              v-for="item in breadcrumbData"
              :key="item.id"
              :to="`${rootPath}/${category}/${item.id}`"
            >{{item.name}}</ui-breadcrumb-item>
          </ui-breadcrumb>
        </div>
        <div v-if="foldering" class="bi-disk-manage-list__position-loading">
          <ui-loading :visible="true" size="mini"></ui-loading>
        </div>
      </div>
    </template>
    <div class="bi-disk-manage-list__addon" slot="addon">
      <div class="bi-disk-manage-list__filter">
        <ui-search v-model="gridFilters.queryParam" size="small" placeholder="搜索当前文件夹" @search="handleSearch"></ui-search>
      </div>
      <div class="bi-disk-manage-list__toolbar">
        <ui-toolbar>
          <ui-toolbar-item>
            <ui-button size="small" @click="handleAddFolderClick">添加文件夹</ui-button>
          </ui-toolbar-item>
          <ui-toolbar-item>
            <disk-manage-upload
              :create-disk-file-method="createDiskFileMethod"
              :parent-path-id="folderId"
              @success="handleUploadFileSuccess"
            ></disk-manage-upload>
          </ui-toolbar-item>
        </ui-toolbar>
      </div>
    </div>
    <div class="bi-disk-manage-list__main" :class="{'is-show-file-detail': showFileDetail}">
      <div class="bi-disk-manage-list__grid">
        <ui-grid
          ref="grid"
          :multiple="true"
          :query-method="handleQueryGridData"
          :show-pagination="false"
          :row-toolbar="gridRowToolbarItems"
        >
          <ui-grid-batch-toolbar :items="gridBatchToolbarItems"></ui-grid-batch-toolbar>
          <ui-grid-column label="文件名" prop="filePath" min-width="240px">
            <template slot-scope="{ row }">
              <ui-file-portray
                :type="row.fileType === 2 ? 'folder' : 'file'"
                :label="row.fileType === 2 ? row.filePath : row.fileName"
                :name="row.fileExtension"
                size="small"
                @click.native.stop="handleDistFileClick(row)"
              ></ui-file-portray>
            </template>
          </ui-grid-column>
          <ui-grid-column label="创建人" prop="createName" width="120px"></ui-grid-column>
          <ui-grid-column label="最后更新" prop="updateTime" width="180px"></ui-grid-column>
          <ui-grid-column label="文件大小" prop="fileSize" width="120px">
            <template slot-scope="{ row }">
              {{ handleFormatFileSize(row.fileSize) }}
            </template>
          </ui-grid-column>
        </ui-grid>
      </div>
      <div class="bi-disk-manage-list__detail" @click.stop>
        <div class="bi-disk-manage-list__detail-inner">
          <disk-manage-detail
            :data="currentRow"
          ></disk-manage-detail>
        </div>
      </div>
    </div>
    <ui-dialog
      title="新增文件夹"
      v-model="showAddFolderDialog"
    >
      <disk-manage-folder
        :parent-path-id="folderId"
        :create-disk-folder-method="createDiskFolderMethod"
        @success="handleAddFolderSuccess"
      ></disk-manage-folder>
    </ui-dialog>
    <ui-dialog
      title="重命名"
      v-model="showRenameDialog"
    >
      <disk-manage-rename
        :id="currentRow && currentRow.id"
        :name="currentRow && (currentRow.fileType === 2 ? currentRow.filePath : currentRow.fileName)"
        :type="currentRow && (currentRow.fileType === 2 ? 'folder' : 'file')"
        :rename-disk-file-name-method="renameDiskFileNameMethod"
        :rename-disk-folder-name-method="renameDiskFolderNameMethod"
        @success="handleRenameSuccess"
      ></disk-manage-rename>
    </ui-dialog>
    <ui-dialog
      title="移动到"
      v-model="showMoveDialog"
    >
      <disk-manage-folder-select
        :confirm-method="handleMoveFileConfirm"
        :load-disk-folder-data-method="loadDiskFolderDataMethod"
      ></disk-manage-folder-select>
    </ui-dialog>
    <ui-dialog
      title="复制到"
      v-model="showCopyDialog"
    >
      <disk-manage-folder-select
        :confirm-method="handleCopyFileConfirm"
        :load-disk-folder-data-method="loadDiskFolderDataMethod"
      ></disk-manage-folder-select>
    </ui-dialog>
  </ui-page>
</template>
<script>
import { formatFileSize, downloadFile } from './util'
import DiskManageFolder from './disk-manage-folder/disk-manage-folder'
import DiskManageDetail from './disk-manage-detail/disk-manage-detail'
import DiskManageUpload from './disk-manage-upload/disk-manage-upload'
import DiskManageRename from './disk-manage-rename/disk-manage-rename'
import DiskManageFolderSelect from './disk-manage-folder-select/disk-manage-folder-select'

export default {
  name: 'BiDiskManageList',
  components: {
    DiskManageDetail,
    DiskManageFolder,
    DiskManageUpload,
    DiskManageRename,
    DiskManageFolderSelect
  },
  props: {
    category: {
      type: String,
      validator(value) {
        return ['all', 'lately', 'star', 'recycle'].includes(value)
      }
    },
    rootPath: {
      type: String,
      default: ''
    },
    loadDiskDataMethod: {
      type: Function,
      default: null
    },
    loadDiskRecentDataMethod: {
      type: Function,
      default: null
    },
    loadDiskStarMarkDataMethod: {
      type: Function,
      default: null
    },
    loadDiskRecycleDataMethod: {
      type: Function,
      default: null
    },
    deleteDiskFolderMethod: {
      type: Function,
      default: null
    },
    downloadDiskFileMethod: {
      type: Function,
      default: null
    },
    confirmDiskFileStarMethod: {
      type: Function,
      default: null
    },
    cancelDiskFileStarMethod: {
      type: Function,
      default: null
    },
    resumeDiskFileMethod: {
      type: Function,
      default: null
    },
    resumeDiskFolderMethod: {
      type: Function,
      default: null
    },
    thoroughDeleteDiskFileMethod: {
      type: Function,
      default: null
    },
    thoroughDeleteDiskFolderMethod: {
      type: Function,
      default: null
    },
    getFolderParentsMethod: {
      type: Function,
      default: null
    },
    moveDiskFileMethod: {
      type: Function,
      default: null
    },
    copyDiskFileMethod: {
      type: Function,
      default: null
    },
    createDiskFolderMethod: {
      type: Function,
      default: null
    },
    createDiskFileMethod: {
      type: Function,
      default: null
    },
    renameDiskFileNameMethod: {
      type: Function,
      default: null
    },
    renameDiskFolderNameMethod: {
      type: Function,
      default: null
    },
    loadDiskFolderDataMethod: {
      type: Function,
      default: null
    }
  },
  data() {
    return {
      currentRow: null,
      showFileDetail: false,
      showAddFolderDialog: false,
      showRenameDialog: false,
      showCopyDialog: false,
      showMoveDialog: false,
      foldering: false,
      gridFilters: {
        queryParam: ''
      },
      breadcrumbData: []
    }
  },
  computed: {
    folderId() {
      return this.$route.params.folderId
    },
    categoryText() {
      const map = {
        all: '全部文档',
        lately: '最近文档',
        star: '星标文档',
        recycle: '回收站'
      }
      return map[this.category]
    },
    gridBatchToolbarItems() {
      return [{
        label: '下载'
      }, {
        label: '移动到'
      }, {
        label: '复制到'
      }]
    },
    gridRowToolbarItems() {
      if (this.category === 'recycle') {
        return [{
          label: '恢复到原处',
          more: true,
          click: this.handleRecoveryClick
        }, {
          label: '彻底删除',
          more: true,
          type: 'danger',
          click: this.handleThoroughClick
        }]
      } else {
        return [{
          label: '重命名',
          more: true,
          click: this.handleRenameClick
        }, {
          label: '下载',
          more: true,
          visible({ row }) {
            return row.fileType === 1
          },
          click: this.handleDownloadClick
        }, {
          label: '删除',
          more: true,
          type: 'danger',
          click: this.handleDeleteClick
        }, {
          label: '移动到',
          more: true,
          divided: true,
          click: this.handleMoveClick
        }, {
          label: '复制到',
          more: true,
          click: this.handleCopyClick
        }, {
          label: '标星',
          more: true,
          click: this.handleConfirmStarClick,
          visible({ row }) {
            return row.fileType === 1 && row.starMark !== '1'
          }
        }, {
          label: '取消标星',
          more: true,
          click: this.handleCancelStarClick,
          visible({ row }) {
            return row.fileType === 1 && row.starMark === '1'
          }
        }]
      }
    }
  },
  watch: {
    category() {
      this.showFileDetail = false
      this.$refs.grid && this.$refs.grid.reload()
    },
    folderId() {
      this.showFileDetail = false
      if (!this.folderId) {
        this.breadcrumbData = []
      }
      this.$refs.grid && this.$refs.grid.reload()
    }
  },
  mounted() {
    window.document.addEventListener('click', this.handleDocumentClick)
  },
  beforeDestroy() {
    window.document.removeEventListener('click', this.handleDocumentClick)
  },
  methods: {
    handleSearch() {
      this.$refs.grid.reload()
    },
    handleQueryData() {
      if (!this.folderId || this.category !== 'all') {
        this.inited = true
        return Promise.resolve()
      }
      this.foldering = true
      return this.getFolderParentsMethod(this.folderId).then((rs) => {
        this.breadcrumbData = rs
        this.inited = true
      }).finally(() => {
        this.foldering = false
      })
    },
    handleBreadcrumbRootClick() {
      this.breadcrumbData = []
    },
    handleMoveClick({ row }) {
      this.showMoveDialog = true
      this.currentRow = row
    },
    handleCopyClick({ row }) {
      this.showCopyDialog = true
      this.currentRow = row
    },
    handleAddFolderSuccess() {
      this.$refs.grid.loadData()
    },
    handleFormatFileSize(fileSize) {
      return formatFileSize(fileSize)
    },
    handleRenameClick({ row }) {
      this.currentRow = row
      this.showRenameDialog = true
    },
    handleDocumentClick() {
      this.showFileDetail = false
    },
    handleUploadFileSuccess() {
      this.$refs.grid.loadData()
    },
    handleMoveFileConfirm({ targetId }) {
      if (!targetId) {
        this.$error('请选择要移动到的目标文件夹')
        return Promise.reject()
      }
      return this.moveDiskFileMethod({
        id: this.currentRow.id,
        desPathId: targetId === 'all' ? '' : targetId
      }).then(() => {
        this.$success('操作成功')
        this.$refs.grid.reload()
      })
    },
    handleCopyFileConfirm({ targetId }) {
      if (!targetId) {
        this.$error('请选择复制到的目标文件夹')
        return Promise.reject()
      }
      return this.copyDiskFileMethod({
        id: this.currentRow.id,
        desPathId: targetId === 'all' ? '' : targetId
      }).then(() => {
        this.$success('操作成功')
        this.$refs.grid.reload()
      })
    },
    handleThoroughClick({ row }) {
      this.$confirm('确定', '确定要彻底删除吗？').then(() => {
        if (row.fileType === 2) {
          return this.thoroughDeleteDiskFolderMethod({
            ids: row.id
          }).then(() => {
            this.$success('操作成功')
            this.$refs.grid.loadData()
          })
        } else {
          return this.thoroughDeleteDiskFileMethod({
            ids: row.id
          }).then(() => {
            this.$success('操作成功')
            this.$refs.grid.loadData()
          })
        }
      })
    },
    handleRecoveryClick({ row }) {
      this.$confirm('确定', '确定要恢复到原处吗？').then(() => {
        if (row.fileType === 2) {
          return this.resumeDiskFolderMethod({
            ids: row.id
          }).then(() => {
            this.$success('操作成功')
            this.$refs.grid.loadData()
          })
        } else {
          return this.resumeDiskFileMethod({
            ids: row.id
          }).then(() => {
            this.$success('操作成功')
            this.$refs.grid.loadData()
          })
        }
      })
    },
    handleConfirmStarClick({ row }) {
      return this.confirmDiskFileStarMethod(row.id).then(() => {
        this.$success('操作成功')
        this.$refs.grid.loadData()
      })
    },
    handleCancelStarClick({ row }) {
      return this.cancelDiskFileStarMethod(row.id).then(() => {
        this.$success('操作成功')
        this.$refs.grid.loadData()
      })
    },
    handleDownloadClick({ row }) {
      return this.downloadDiskFileMethod({
        fileName: row.fileName
      }).then(() => {
        downloadFile(row.absolutelyPath)
      })
    },
    handleDeleteClick({ row }) {
      this.$confirm('确定', '将该文件放至回收站, 是否继续?').then(() => {
        return this.deleteDiskFolderMethod({
          id: row.id
        }).then(() => {
          this.$success('删除成功')
          this.$refs.grid.loadData()
        })
      })
    },
    handleDistFileClick(row) {
      if (row.fileType === 2) {
        if (this.category === 'all') {
          this.$router.push({
            path: `${this.rootPath}/${this.category}/${row.id}`
          })
        }
      } else {
        this.showFileDetail = true
        this.currentRow = row
      }
    },
    handleAddFolderClick() {
      this.showAddFolderDialog = true
    },
    handleRenameSuccess() {
      this.$refs.grid.loadData()
    },
    handleQueryGridData() {
      const loadFn = {
        all: this.loadDiskDataMethod,
        lately: this.loadDiskRecentDataMethod,
        star: this.loadDiskStarMarkDataMethod,
        recycle: this.loadDiskRecycleDataMethod
      }[this.category]
      const ps = [
        loadFn(Object.assign({
          parentPathId: this.folderId
        }, this.gridFilters))
      ]
      if (this.inited && this.folderId && this.category === 'all') {
        ps.push(
          this.getFolderParentsMethod(this.folderId).then((rs) => {
            this.breadcrumbData = rs
          })
        )
      }
      return Promise.all(ps).then(rs => rs[0])
    }
  }
}
</script>
<style lang="less">
.bi-disk-manage-list__addon{
  display: flex;
  flex-direction: row;
  align-items: center;
}
.bi-disk-manage-list__toolbar{
  margin-left: 32px;
}
.bi-disk-manage-list__main{
  height: 100%;
  display: flex;
  flex-direction: row;
  &.is-show-file-detail {
    .bi-disk-manage-list__detail {
      width: 270px;
    }
  }
}
.bi-disk-manage-list__grid {
  flex: 1;
  min-width: 0;
}
.bi-disk-manage-list__detail{
  width: 0;
  overflow: hidden;
  transition: all .25s;
  border-left: 1px solid #D5D8DC;
}
.bi-disk-manage-list__detail-inner{
  width: 270px;
  min-width: 270px;
}
.bi-disk-manage-list__position{
  display: flex;
  flex-direction: row;
  align-items: center;
}
.bi-disk-manage-list__position-loading{
  padding-left: 12px;
}
</style>
