<template>
  <div class="layout-no-cols right-list-toolbar">
    <el-row type="flex" align="middle">
      <el-col :span="12">
        <el-toolbar v-if="sitePriv">
          <el-button :disabled="toolBarBtnDisabled.refresh" @click="refresh" priv="ContentCore.FileMenu">
            <i class="fa fa-refresh" aria-hidden="true"></i>刷新
          </el-button>
          <el-dropdown @command="addFileOrDir">
            <el-button priv="ContentCore.FileMenu.Add">
              <i class="fa fa-plus" aria-hidden="true"></i>新建
              <i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="File" priv="ContentCore.FileMenu.Add">
                <i class="fa fa-file" aria-hidden="true"></i>新建文件
              </el-dropdown-item>
              <el-dropdown-item command="Dir" priv="ContentCore.FileMenu.Add">
                <i class="fa fa-folder" aria-hidden="true"></i>新建目录
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button @click="uploadFile" :disabled="toolBarBtnDisabled.upload" priv="ContentCore.FileMenu.Upload">
            <i class="fa fa-arrow-up" aria-hidden="true"></i>上传
          </el-button>
        </el-toolbar>
      </el-col>
      <el-col :span="12" class="tar">
        <el-select v-model="currentPublishPlatform" placeholder="发布平台" style="width: 100px;" @change="changePlatform">
          <el-option v-for="item in publishPlatform" :key="item.ID" :label="item.name" :value="item.ID">
            <span style="float: left">
              <i class="fa fa-desktop" aria-hidden="true"></i>
            </span>
            <span style="float: left">{{ item.name }}</span>
          </el-option>
        </el-select>
      </el-col>
    </el-row>

    <div>
      <div class="bar">
        <div class="layout-data-search layout-data-search-3 layout-data-search-file">
          <el-tooltip class="item" effect="dark" content="返回上一级" placement="top-start">
            <el-button style="height:36px;" @click="onAddressClick(currentLevel-1)">
              <i class="fa fa-arrow-up f16 padding0" aria-hidden="true"></i>
            </el-button>
          </el-tooltip>
          <div class="layout-select">
            <a style='color:#1F2D3D' @click='onAddressClick(-1)'>
              <i class='fa fa-folder' aria-hidden='true'></i>
            </a> /
            <span v-for="item in currentPathArr" :key="item.name">
              <i class='fa fa-sort-desc' aria-hidden='true'></i>
              <a href='javascript:void(0)' style='color:#333' @click='onAddressClick(item.level)'> {{item.name}} </a>
            </span>
          </div>
          <el-col :span="6" class="tree-search-box">
            <el-input v-model="searchParam.name" @keyup.enter.native="searchFileOrDir" placeholder="请输入名称"></el-input>
            <span class="search-icon">
              <i class="fa fa-search" slot="append" @click="searchFileOrDir" title="查询"></i>
            </span>
          </el-col>
        </div>
      </div>

      <el-bigdata-table :data="fileListData" :data-read-url="getDataURL" tooltip-effect="dark" ref="fileListTable" style="width: 100%" @selection-change="fileListTableSelectionChange" @sort-change="sizeSortChange" v-once>
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="name" label="名称" sortable="custom" show-overflow-tooltip>
          <template slot-scope="scope">
            <a href="javascript:void(0)" @click.stop="openFileOrDir(scope.row)">
              <img v-if="scope.row.dirFlag === 'Y'" src="assets/images/framework/filetype/folder.gif" />
              <img v-else :src="scope.row.icon" />
              <span style="margin-left: 2px">{{ scope.row.name }}</span>
            </a>
          </template>
        </el-table-column>
        <el-table-column prop="size" label="大小" width="90" sortable="custom" show-overflow-tooltip></el-table-column>
        <el-table-column prop="type" label="类型" width="100" sortable="custom" show-overflow-tooltip></el-table-column>
        <el-table-column prop="lastModified" label="最后修改时间" width="160" sortable="custom">
          <template slot-scope="scope">
            {{scope.row.lastModified | fixDateTime}}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="right" width="160">
          <template slot-scope="scope" v-if="!scope.row.back">
            <el-button @click.stop="openFileOrDir(scope.row)" type="text" title="打开" priv="ContentCore.FileMenu.Edit">
              <i class="fa fa-search f16"></i>
            </el-button>
            <el-button @click.stop="renameFileOrDir(scope.row)" type="text" title="重命名" priv="ContentCore.FileMenu.Rename">
              <i class="fa fa-mail-forward f16"></i>
            </el-button>
            <el-button @click.stop="exportFileOrDir(scope.row)" type="text" title="导出" priv="ContentCore.FileMenu.Export">
              <i class="fa fa-arrow-down f16"></i>
            </el-button>
            <el-button @click.stop="deleteFileOrDir(scope.row)" type="text" title="删除"  priv="ContentCore.FileMenu.Delete">
              <i class="fa fa-remove f16"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-bigdata-table>
    </div>

    <!--创建文件/文件夹组件-->
    <file-create-dialog ref="fileCreateDialog" @success="refresh()"></file-create-dialog>

    <!--编辑文件Dialog组件-->
    <file-edit-dialog ref="fileEditDialog" @success="refresh()"></file-edit-dialog>

    <!--文件上传Dialog组件-->
    <file-upload-dialog ref="fileUploadDialog" @success="refresh()"></file-upload-dialog>

    <!--图片预览组件-->
    <image-viewer ref="imageViewer" :images="imageViewerData"></image-viewer>

    <!-- pdf查看器 -->
    <pdf-viewer ref="pdfViewer"></pdf-viewer>

  </div>
</template>

<script>
import util from '@src/common/util.js'
import FileCreateDialog from './components/FileCreateDialog.vue'
import FileEditDialog from './components/FileEditDialog.vue'
import FileUploadDialog from './components/FileUploadDialog.vue'
import ImageViewer from './components/ImageViewer.vue'
import PDFViewer from './components/PDFViewer.vue'

export default {
  filters: {
    fixDateTime: function(val) {
      return util.formatDate(val, 'yyyy-MM-dd HH:mm')
    }
  },
  data() {
    return {
      sitePriv: false, // 站点权限
      treeParam: {
        siteID: '',
        platformID: '',
        parentID: ''
      }, // 属性菜单参数
      selectedRows: [], // 当前选中的数据行
      currentFileListData: {}, // 选中的文件表格数据
      currentPath: '<a  style="color:#1F2D3D"><i class="fa fa-folder " aria-hidden="true"></i></a> /', // 当前路径
      currentPathArr: [], // 当前路径数组  用于地址条
      currentLevel: -1,
      currentPublishPlatform: '', // 发布平台
      publishPlatform: [], // 发布平台
      treeDataLoading: false, // 文件树加载状态
      fileTreeData: [], // 文件树数据
      fileTreeProps: {
        children: 'children',
        label: 'name',
        key: 'ID',
        isLeaf: 'isLeaf'
      }, // 文件树属性配置
      toolBarBtnDisabled: {
        refresh: false,
        createFile: false,
        createFloder: false,
        rename: true,
        open: true,
        delete: true,
        upload: false,
        export: true
      }, // 工具栏按钮禁用状态
      fileListData: [],
      initParam: {
        defaultplatform: 'pc',
        siteID: null
      }, // 文件目录树初始化参数
      initfileList: {
        platformID: null,
        siteID: null,
        platformPath: ''
      }, // 文件列表初始化参数
      dialogTitle: '', // Dialog标题
      fileOrDir: 'file', // 文件还是目录 file/dir
      currentAddFileFormData: {
        parentName: '',
        name: ''
      }, // 当前新建文件临时数据
      addOrRename: 'add', // 新建还是重命名 add/rename
      currentFilePath: '', // 当前文件路径
      searchParam: {
        name: '',
        platformID: null
      }, // 查询参数
      imageViewerData: [],
      sortField: '',
      direction: '',
      currentRoutes: this.$route.path,
      lastOpenDirTime: false // 上一次打开文件夹的时间
    }
  },
  watch: {
    '$route': 'closeImage'
  },
  methods: {
    sizeSortChange(val) {
      this.sortField = val.prop || ''
      this.direction = val.order ? val.order.substring(0, val.order.indexOf('ending')) : ''
      this.loadFileList()
    },
    handleCommand(method) {
      if (method && typeof this[method] === 'function') {
        this[method]()
      } else {
        console.warn(`未找到改菜单对应的方法:${method}`)
      }
    },
    initData() {
      let init = axios.get('/ui/core/file/init').then(res => res.data)
      let loadUsedPublishPlatformData = axios.get('/ui/publishplatform/usedpublishplatforms').then(res => res.data)
      let all = [init, loadUsedPublishPlatformData]

      this.treeDataLoading = true
      Promise.all(all).then(datas => {
        datas[0].status === 1 && Object.assign(this.initParam, datas[0].data)
        datas[1].status === 1 && Object.assign(this.publishPlatform, datas[1].data)

        this.currentPublishPlatform = this.initParam.defaultPlatform
        this.treeParam.platformID = this.initParam.defaultPlatform
        this.treeParam.siteID = this.initParam.siteID

        this.initfileList.platformID = this.currentPublishPlatform
        this.initfileList.siteID = this.initParam.siteID
        this.initfileList.platformPath = this.currentFilePath

        this.loadFileList()

        let params = { siteID: this.initParam.siteID }
        axios.get('/ui/core/file/initlist', { params }).then(res => {
          let data = res.data
          this.sitePriv = data.data.sitePriv
        })
      })
    },

    // 加载发布平台数据
    async loadUsedPublishPlatformData() {
      let res = await axios.get('/ui/publishplatform/usedpublishplatforms')
      if (res.data.status === 1) {
        this.publishPlatform = res.data.data
      }
    },

    // 加载文件列表树子节点
    async loadSubNode(node, resolve) {
      if (!this.treeParam.siteID || !this.treeParam.platformID) {
        return
      }
      let id = !node.data.ID ? 0 : node.data.ID
      this.treeParam.parentID = id

      let res = await axios.get(`/ui/core/file/tree`, { params: this.treeParam })
      let data = res.data
      if (data.status === 1) {
        let subNode = this.formatTreeData(data.data)
        resolve(subNode)
      }
    },

    formatTreeData(arr) {
      if (!!arr && arr.length > 0) {
        for (let item of arr) {
          if (!item.hasOwnProperty('children') || !(item['children'] instanceof Array) || !item['children'].length) {
            item['isLeaf'] = true
          }
        }
      }
      return arr
    },

    // 搜索文件或目录
    searchFileOrDir() {
      this.loadFileList()
    },

    // 文件列表数据行选中事件
    fileListTableSelectionChange(selection) {
      this.selectedRows = selection
      this.currentFileListData = this.selectedRows.length ? Object.assign({}, this.selectedRows[0]) : {}
      if (selection) {
        this.toolBarBtnDisabled.rename = !(selection.length === 1)
        this.toolBarBtnDisabled.open = !(selection.length === 1)
        this.toolBarBtnDisabled.delete = !(selection.length > 0)
        this.toolBarBtnDisabled.export = !(selection.length > 0)
      } else {
        this.toolBarBtnDisabled.rename = true
        this.toolBarBtnDisabled.open = true
        this.toolBarBtnDisabled.delete = true
        this.toolBarBtnDisabled.export = true
      }
    },

    // 文件树渲染函数
    renderContent(createElement, { node, data, store }) {
      let iconClass = !data.ID ? 'fa fa-desktop' : 'fa fa-folder'
      let icon = createElement('i', { attrs: { class: iconClass } })
      let label = createElement('span', ' ' + node.label)
      return createElement('span', [icon, label])
    },

    // 文件树点击事件
    onTreeClick(nodeData, nodeObj) {
      let id = nodeData.ID
      let platformID = this.currentPublishPlatform
      this.currentAddFileFormData.parentName = id
      this.currentFilePath = id
      this.changeDir(id, platformID)
    },

    // 改变路径
    changeDir(path, platformID) {
      // 更改地址栏
      this.currentPathArr = []
      this.currentPath = path
      let arr = this.currentPath.split('/')

      for (var i = 0; i < arr.length; i++) {
        var name = arr[i]
        if (name === '') {
          continue
        }
        name = name === 'root' ? '' : name
        this.currentLevel = i
        this.currentPathArr.push({ name: name, level: i })
      }

      this.currentFilePath = this.currentFilePath !== path ? path : this.currentFilePath
      this.initfileList.platformID = platformID
      this.initfileList.platformPath = path
      this.initfileList.siteID = this.initParam.siteID

      this.loadFileList()
    },

    // 地址栏点击事件
    onAddressClick(level) {
      let arr = this.currentPath.split('/')
      let sb = []
      for (var i = 0; i <= level; i++) {
        sb.push(arr[i])
      }
      let path = sb.join('/')
      if (level === -1) {
        path = ''
      } else {
        path = path + '/'
      }

      this.changeDir(path, this.currentPublishPlatform)
    },

    // 重命名文件或目录
    async renameFileOrDir(row) {
      !!row && row.name && Object.assign(this.currentFileListData, row)
      let params = {
        addOrRename: 'rename',
        fileOrDir: this.currentFileListData.dirFlag === 'N' ? 'File' : 'Dir',
        dialogTitle: '重命名',
        oldName: this.currentFileListData.name
      }

      Object.assign(params, this.initfileList, { parentName: this.currentFilePath })
      this.$refs.fileCreateDialog.initDialog(params)
    },

    // 打开文件或目录
    openFileOrDir(row) {
      // 限制500ms内只触发一次
      let currentTime = Date.now()
      if (currentTime - this.lastOpenDirTime < 500) {
        return
      }
      this.lastOpenDirTime = currentTime

      !!row && row.name && Object.assign(this.currentFileListData, row)
      let name = this.currentFileListData.name
      let dirFlag = this.currentFileListData.dirFlag
      if (dirFlag === 'Y') {
        this.changeDir((this.currentFilePath === 'root' ? '' : this.currentFilePath) + name + '/', this.initfileList.platformID)
      } else {
        if (name.indexOf('.') < 0) {
          this.$alert('不支持该文件类型！', '提示', {
            type: 'info'
          })
          return
        }
        let ext = name.substring(name.lastIndexOf('.') + 1).toLowerCase()
        let param = {
          path: encodeURIComponent(this.currentFilePath),
          name: name,
          platformID: this.initfileList.platformID,
          siteID: this.initfileList.siteID,
          src: row.imageSrc
        }
        if ('html,htm,shtml,txt,js,json,css,xml,md'.split(',').includes(ext)) {
          if (ext.includes('htm')) {
            this.editorMode = 'htmlmixed'
          } else if (ext === 'js' || ext === 'json') {
            this.editorMode = 'javascript'
          } else if (ext === 'css') {
            this.editorMode = 'css'
          } else if (ext === 'xml') {
            this.editorMode = 'xml'
          } else if (ext === 'md') {
            this.editorMode = 'markdown'
          }

          let eConfig = {
            editorMode: this.editorMode,
            editorConfig: this.editorConfig
          }

          Object.assign(param, eConfig)
          this.$refs.fileEditDialog.initDialog(param)
        } else if (['jpeg', 'jpg', 'bmp', 'gif', 'png'].includes(ext)) {
          this.$refs.imageViewer.openImg(param.name)
        } else if (ext === 'pdf') {
          this.$refs.pdfViewer.init(param)
        } else {
          this.$alert('不支持该文件类型！', '提示', {
            type: 'info'
          })
        }
      }
    },

    // 删除文件或目录
    async deleteFileOrDir(row) {
      let names = []
      if (row && row.name) {
        names = Array.of(row.name)
      } else {
        for (let row of this.selectedRows) {
          names.push(row.name)
        }
      }

      if (!names.length) {
        this.$alert('请选择要删除的数据 ！')
        return
      }

      let param = {
        path: encodeURIComponent(this.currentFilePath),
        siteID: this.initfileList.siteID,
        platformID: this.currentPublishPlatform
      }
      try {
        await this.$confirm('确认删除文件或者文件夹 ？', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let res = await axios.delete(`/ui/core/file/${names.join()}`, { params: param })
        if (res.data.status === 1) {
          this.selectedRows = []
          this.currentFileListData = {}
          this.refresh()
        } else {
          util.showResponseMessage(res.data)
        }
      } catch (e) {

      }
    },

    // 上传文件
    async uploadFile() {
      let params = Object.assign({}, this.initfileList, { currentFilePath: encodeURIComponent(this.currentFilePath), platformID: this.currentPublishPlatform })
      this.$refs.fileUploadDialog.initDialog(params)
    },

    // 导出文件或目录
    exportFileOrDir(row) {
      let names = []
      if (row && row.name) {
        names = Array.of(row.name)
      } else {
        for (let row of this.selectedRows) {
          names.push(row.name)
        }
      }

      if (!names.length) {
        this.$alert('请选择要导出的数据 ！')
        return
      }
      let param = {
        base: !this.currentFilePath ? '' : this.currentFilePath,
        files: names.join(),
        platformID: this.initfileList.platformID,
        siteID: this.initfileList.siteID
      }

      window.location.href = `ui/contentcore/file/export?base=${param.base}&files=${param.files}&platformID=${
        param.platformID
      }&siteID=${param.siteID}`
      // this.MsgPop("正在导出 ，请等待 ！");
    },

    // 刷新
    refresh() {
      this.loadFileList()
    },

    // 新建文件/目录
    addFileOrDir(type) {
      let params = {
        addOrRename: 'add',
        fileOrDir: type,
        dialogTitle: type === 'File' ? '新建文件' : '新建目录'
      }
      Object.assign(params, this.initfileList, { parentName: this.currentFilePath, platformID: this.currentPublishPlatform })
      this.$refs.fileCreateDialog.initDialog(params)
    },

    getDataURL() {
      return [
        '/ui/core/file/bindgrid',
        {
          params: {
            path: encodeURIComponent(this.initfileList.platformPath),
            platformID: this.currentPublishPlatform,
            siteID: this.initfileList.siteID,
            sortField: this.sortField,
            direction: this.direction,
            name: encodeURIComponent(this.searchParam.name)
          }
        }
      ]
    },
    // 加载文件列表
    async loadFileList() {
      await this.$refs.fileListTable.getData()
      for (let item of this.fileListData) {
        if (item.icon) {
          item.icon = `assets/images/framework/filetype${item.icon.substring(item.icon.lastIndexOf('/'))}`
        }
      }
      this.imageViewerData = [...this.fileListData]
    },
    closeImage() {
      this.$refs.imageViewer.close()
    },
    changePlatform(){
      this.changeDir('', this.currentPublishPlatform)
    }
  },
  created() {
    this.initData()
  },
  components: {
    'file-create-dialog': FileCreateDialog,
    'file-edit-dialog': FileEditDialog,
    'file-upload-dialog': FileUploadDialog,
    'image-viewer': ImageViewer,
    'pdf-viewer': PDFViewer
  }
}
</script>

<style scoped>
.padding-top-bottom .search-bar {
  padding-bottom: 5px;
}

.tabs-wrap {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
}

.info-form-wrap {
  margin-top: 10px;
  padding: 10px 0;
  width: 560px;
}

.pointer {
  cursor: pointer;
}
</style>
<style scoped>
.small-toolbar {
  min-height: 40px;
}

.el-tree > :first-child .el-tree-node__content .el-tree-node__expand-icon {
  display: none;
}

input[type='file'] {
  display: none !important;
}

.el-upload__input {
  display: none !important;
}

.layout-data-search {
  padding-left: 0;
}

.layout-data-search-file {
  /* max-width: 900px; */
  padding-bottom: 10px;
}

.layout-data-search-file .layout-select {
  background: #fff;
  border: solid 0.5px #ccc;
  width: 100%;
  height: 36px;
  line-height: 36px;
  padding-left: 5px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  border-radius: 5px;
}

.layout-data-search-file .el-input {
  padding-left: 5px;
  max-width: 200px;
}
</style>
