<template>
  <div @click="_closeMenu">
    <!--内容-->
    <div class="layout-content-padding marginLeft-10">
      <div class="layout-content-main tree-position">
        <div :style="treeStyleObj" v-show="isTree" class="position-left">
          <Card dis-hover class="card_tree">
            <p slot="title" style="width: 60%">文档管理列表</p>
            <p slot="title" style="width: 40%;text-align: right">
              <a @click="_refreshFloder">
                <Icon type="refresh" size="20"></Icon>
              </a>
            </p>
            <div>
              <FileTree ref="filetree" @on-result-change="_fileData" :keyword="keyword"></FileTree>
            </div>
          </Card>
        </div>
        <div @click="_treeHide" v-if="isTree" style="position: absolute;left: 196px;top: 50%;cursor:pointer">
          <div class="navbarImgShow"></div>
        </div>
        <div @click="_treeShow" v-else="isTree" style="position: absolute;left:0;top: 50%;cursor:pointer">
          <div class="navbarImgHide"></div>
        </div>
        <div :style="tableStyleObj" class="position-right">
          <!--菜单操作-->
          <Row>
            <Col span="24">
              <div class="btns-menu">
                <!--查看方式-->
                <Select @on-change="_view" v-model="selectValue" style="width:150px" placeholder="请选择查看方式">
                  <Option v-for="(item,index) in checkList" :key="index" :value="item.value">{{ item.name }}</Option>
                </Select>
                <!--一系列操作-->
                <label v-show="viewStyle == '2' || viewStyle == '3' ">
                  <Button v-for="item in menusList" :key="item.name" @click="_tableChange(item.value)"
                          type="ghost" style="margin-right: 5px">
                    <Icon :type="item.type"></Icon>&nbsp;{{item.name}}
                  </Button>
                </label>
                <!--查询条件-->
                <Input v-model="keyword" @on-enter="_searchFile" style="width:200px" placeholder="请输入文件名称"
                       clearable></Input>
                <Button @click="_searchFile" type="primary">搜索</Button>
              </div>
            </Col>

            <!-- 表格 -->
            <Col span="24" style="margin-bottom: 10px">
              <!--上级文件操作-->
              <div style="margin: 10px 0;width: 100px;">
                <a v-show="isUpLEevel" @click="_upLevel" style="font-size: 14px">
                  <Icon type="chevron-left"></Icon>&nbsp;返回
                </a>
                <p v-show="!isUpLEevel" style="font-size: 14px;height:20px">
                  <Icon type="ios-folder" color="#f5a623"></Icon>&nbsp;全部文件
                </p>
              </div>
              <!--默认是详细模式-->
              <div v-if="viewStyle == 1">
                <ElementTable ref="pageTable"
                              :tableHeight="tableHeight" :getPage="List" hide-page hide-checkbox>
                  <el-table-column
                    :prop="item.key"
                    :label="item.title"
                    :width="item.width"
                    :min-width="200"
                    :fixed="item.fixed?item.fixed:undefined"
                    v-for="item in pageColumns"
                    :key="item.key"
                    show-overflow-tooltip sortable>
                    <template slot-scope="scope">
                      <div v-if="item.date">
                        {{scope.row[item.key]?$dateformat(scope.row[item.key],'yyyy-mm-dd HH:MM'):''}}
                      </div>
                      <div v-else-if="item.name">
                        <div v-if="scope.row.type===undefined">
                           <span
                             :style="`background:url(${smallUrl}folder.png)no-repeat;`"
                             class="span_height">
                              <a @click="_nextLevel(scope.row.id,scope.row.pid)"
                                 style="display: inline-block;margin-left: 18px">{{scope.row.name}}</a>
                           </span>
                        </div>
                        <div v-else>
                         <span
                           :style="`background:url(${smallUrl}${$fileFormat(scope.row.type)}.png)no-repeat;`"
                           class="span_height">
                           <span style="display: inline-block;margin-left: 18px">{{scope.row[item.key]}}</span>
                         </span>
                        </div>
                      </div>
                      <div v-else-if="item.type">
                        {{scope.row.type===undefined?'文件夹':scope.row.type}}
                      </div>
                      <div v-else>{{scope.row[item.key]}}</div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    :width="80"
                    label="操作"
                    align="center"
                    fixed="right">
                    <template slot-scope="scope">
                      <Poptip placement="left-start" width="150" transfer popper-class="poptip-body_0">
                        <Icon v-if="scope.row.type" @click="_getFilePre(scope.row)" type="navicon-round" class="icons"
                              size=20></Icon>
                        <div slot="content">
                          <ul class="file_menu_list">
                            <li v-for="item in menuList" :key="item.name" @click="_iconClick(item.name,scope.row)">
                              {{item.name}}
                            </li>
                          </ul>
                        </div>
                      </Poptip>
                    </template>
                  </el-table-column>
                </ElementTable>
                <Page :total="List.total"
                      :current="List.current"
                      :page-size="rows"
                      @on-change="_pageChange"
                      placement="top"
                      show-total
                      style="margin-top: 10px;"></Page>
              </div>
              <!--缩略图 模式-->
              <div v-else-if="viewStyle == 2">
                <ul :style="{ 'height': tableHeight }" class="thumbnailStyle">
                  <CheckboxGroup @on-change="_chkThumbnailVal" v-model="thumbnailValue">
                    <li v-for="(item,index) in List.records" :key="index">
                      <div class="thumbnailStyleImg">
                        <Tooltip placement="top">
                          <img v-if="item.type == undefined" :src="folderUrl"/>
                          <img v-else :src="bigUrl+$fileFormat(item.type)+'.png' "/>
                          <div slot="content" style="white-space: normal">
                            <p>名称：{{item.name}}</p>
                            <p v-if="item.type == undefined ">类型：文件夹</p>
                            <p v-else>类型：{{item.type}}</p>
                          </div>
                        </Tooltip>
                      </div>
                      <div class="thumbnailStyleCheck">
                        <div v-if="item.type == undefined" class="file-undefined">
                                <span style="font-size: 12px">
                                  <a @click="_nextLevel(item.id,item.pid)">{{item.name}}</a>
                                </span>
                        </div>
                        <div v-else>
                          <Checkbox :label="item.id"><span class="inline-span">{{item.name}}</span></Checkbox>
                        </div>
                      </div>
                    </li>
                  </CheckboxGroup>
                </ul>
              </div>
              <!--列表 模式-->
              <div v-else="viewStyle == 3">
                <ul :style="{ 'height': tableHeight }" class="listStyle">
                  <CheckboxGroup @on-change="_chkThumbnailVal" v-model="listValue">
                    <li v-for="(item,index) in List.records" :key="index">
                      <div class="listStyleCheck">
                        <Tooltip placement="top">
                                    <span class="spanImg">
                                      <img v-if="item.type == undefined" :src=" smallUrl+'folder.png' "/>
                                      <img v-else :src="smallUrl+$fileFormat(item.type)+'.png' "/>
                                    </span>
                          <span v-if="item.type == undefined" style="font-size: 12px">
                                      <a @click="_nextLevel(item.id,item.pid)"> {{item.name}}</a>
                                    </span>
                          <span v-else>
                                      <Checkbox :label="item.id"><span> {{item.name}}</span></Checkbox>
                                    </span>
                          <div slot="content" style="white-space: normal">
                            <p v-if="item.type == undefined ">类型：文件夹</p>
                            <p v-else>类型：{{item.type}}</p>
                          </div>
                        </Tooltip>
                      </div>
                    </li>
                  </CheckboxGroup>
                </ul>
              </div>
            </Col>
          </Row>
        </div>

      </div>
    </div>
    <!--图片预览-->
    <Modal :title="imgName" v-model="visible">
      <img :src="imgUrl" v-if="visible" style="width:100%">
    </Modal>
    <!--历史版本-->
    <VersionFile ref="versionFile" @on-result-change="_versonData"></VersionFile>
    <!--更新文件-->
    <UploadFileUpdate ref="fileUpdateModal" @on-result-change="_refresh"/>
    <!--预览txt文件-->
    <TxtReadOnly ref="txtModal"/>
    <!--变更文件-->
    <UploadChangeFile ref="uploadChangeFile" @on-result-change="_refresh"></UploadChangeFile>
    <!--变更原因-->
    <Reason ref="reasonModal" @on-result-change="_reasonResult"></Reason>
  </div>
</template>
<script>
import global from '../../../api/config'
import FileTree from './FileTree.vue'
import VersionFile from './Version.vue'
import UploadFileUpdate from './UploadFileUpdate.vue'
import TxtReadOnly from './TxtReadOnly'
import UploadChangeFile from './UploadChangeFile.vue'
import Reason from './Reason'

export default {
  components: {
    Reason,
    FileTree,
    VersionFile,
    UploadFileUpdate,
    TxtReadOnly,
    UploadChangeFile
  },
  data() {
    return {
      viewModal: '',
      loading: true,
      imgName: '',
      imgUrl: '',
      visible: false,
      selectIds: [],
      smallUrl: global.staticURL + '/img/smallfile/',
      bigUrl: global.staticURL + '/img/bigfile/',
      folderUrl: global.staticURL + '/img/bigfile/folder.png',
      pageColumns: [
        { title: '文件名', key: 'name', name: true },
        { title: '类型', key: 'type', width: 100, type: true },
        { title: '创建人', key: 'realname', width: 100 },
        { title: '创建日期', key: 'ctime', width: 140, date: true },
        { title: '文件编号', key: 'code', width: 100, align: 'center' },
        { title: '版本', key: 'version', width: 100, align: 'center' },
        { title: '分发份数', key: 'copies', width: 100, align: 'center' },
        { title: '存档份数', key: 'save', width: 100, align: 'center' },
        { title: '备注', key: 'remark', width: 100, align: 'center' }
      ],
      // 文件权限
      version: { name: '版本' },
      upload: { name: '签入' },
      del: { name: '删除' },
      down: { name: '下载' },
      view: { name: '预览' },
      edit: { name: '编辑' },
      change: { name: '变更' },
      destruction: { name: '销毁' },
      // 文件权限
      menuList: [],
      selMenus: '',
      menusList: [
        { name: '全选', value: 'checkAll', type: 'checkmark-circled' },
        { name: '反选', value: 'unCheckAll', type: 'minus-circled' },
        { name: '批量删除', value: 'delete', type: 'trash-a' }
      ],
      checkList: [
        { name: '详细模式', value: '1' },
        { name: '缩略图模式', value: '2' },
        { name: '列表模式', value: '3' }
      ],
      viewStyle: '1',
      thumbnailValue: [],
      listValue: [],
      folderId: '', // 文件夹id
      allList: [], // 文件和文件夹总数据
      fileList: [],
      pageList: {},
      upLevelPid: '',
      isUpLEevel: false,
      treeStyleObj: {
        width: '210px',
        height: ''
      },
      tableStyleObj: {
        'margin-left': '215px'
      },
      isTree: true,
      getPage: {},
      // 查询条件
      keyword: '',
      selectValue: '1',
      // 每页的条数
      rows: 20,
      changeData: {},
      destructionId: ''
    }
  },
  computed: {
    List() {
      return {
        records: this.allList,
        total: this.getPage.total,
        current: this.getPage.current
      }
    },
    tableHeight: function() {
      return this.$newTableHeight('', 250)
    }
  },
  mounted() {
    this.selectValue = '1'
    this.keyword = ''
    // 获取文件夹
    this.$refs.filetree._Ztree()
    // 获取文件
    this._filetree()
    this._tableHeight(255)
  },
  methods: {
    // 重置所有数据(查所有的数据)
    _refreshFloder() {
      this.pageList.page = 1
      this.isUpLEevel = false
      this.$refs.filetree._getFolderList('', 1)
    },
    _iconClick(res, data) {
      switch (res) {
        case '版本':
          this._version(data)
          break
        case '签入':
          this._checkIn(data)
          break
        case '删除':
          this._deleteById(data.id, data.type)
          break
        case '下载':
          this._download(data.id)
          break
        case '预览':
          this._viewFile(data)
          break
        case '编辑':
          this._editFile(data)
          break
        case '变更':
          this._changeFile(data)
          break
        case '销毁':
          this._destructionFile(data.id)
          break
      }
    },
    _reasonResult(remark, title) {
      switch (title) {
        case '变更原因':
          this.changeData.remark = remark
          this.$refs.uploadChangeFile._open(this.changeData)
          break
        case '销毁原因':
          this.$store
            .dispatch('SysFileStatistics/destroyFile', {
              id: this.destructionId,
              remark: remark
            })
            .then(() => {
              // 销毁文件
              if (this.$store.state.SysFileStatistics.success) {
                this.$Message.success('提交成功！')
                this._refresh()
              }
            })
          break
      }
    },
    _changeFile(data) {
      this.changeData = data
      this.$Modal.confirm({
        title: '提示',
        content: '确定要变更文件？',
        onOk: () => {
          this.$refs.reasonModal._open('变更原因')
        }
      })
    },
    _destructionFile(id) {
      this.destructionId = id
      this.$Modal.confirm({
        title: '提示',
        content: '确定要销毁这个文件？',
        onOk: () => {
          this.$refs.reasonModal._open('销毁原因')
        }
      })
    },
    _tableHeight(val) {
      this.treeStyleObj.height =
        document.documentElement.clientHeight - 110 + 'px'
    },
    _pageChange(page) {
      this.pageList.page = page
      this._filetree()
    },
    // 搜索文件
    _searchFile() {
      if (this.keyword) {
        this.pageList.name = this.keyword
      } else {
        this.pageList.name = ''
      }
      this._filetree()
    },
    _searchParams() {
      const data = {}
      if (this.folderId) {
        data.folderId = this.folderId
      }
      if (this.keyword) {
        data.name = this.keyword
      }
      return this.$extend(data, this.pageList)
    },
    _selectRowChange(data) {
      const idList = []
      for (let i = 0; i < data.length; i++) {
        idList.push(data[i].id)
      }
      this.selectIds = idList
    },
    _selectAll: function(data) {
      this._selectRowChange(data)
    },
    _fileData(rel, ID, PID, fileList, current) {
      // ztree返回的数据
      const currentPage = current.currentPage
      if (currentPage) {
        // 重新发起一次请求,请求上一页的数据
        this.pageList.page = currentPage
        this._filetree()
      }
      // page 参数
      this.getPage = current.getPage
      this.pageList.page = this.getPage.page

      this.folderId = ID
      this.upLevelPid = PID
      this.allList = rel
      this.fileList = fileList // 文件夹数据

      this.thumbnailValue = []
      this.listValue = []
      this.selectIds = []
      // 【返回】键是否显示
      if (this.folderId) {
        this.isUpLEevel = true
      } else {
        this.isUpLEevel = false
      }
    },
    _closeMenu() {
      this.$refs.filetree._close()
    },
    _filetree() {
      this.$refs.filetree._getFolderList(
        this.folderId,
        this.pageList.page,
        this.upLevelPid
      )
    },
    _view(rel) {
      // 查看方式改变
      this.viewStyle = rel
      this._tableHeight(255)
      this.selectIds = []
      this.thumbnailValue = []
      this.listValue = []
    },
    _tableChange(rel) {
      // 一系列操作返回的值
      if (rel == 'checkAll') {
        // 全选

        if (this.viewStyle == '1') {
          this.$refs.selection.selectAll(true)
        } else if (this.viewStyle == '2') {
          this._thumbnailChkAll()
        } else if (this.viewStyle == '3') {
          this._listChkAll()
        }
      } else if (rel == 'unCheckAll') {
        // 反选
        this._unCheckAll()
      } else if (rel == 'delete') {
        // 删除
        this._deleteSelected()
      } else {
      }
    },
    _chkThumbnailVal(rel) {
      // 缩略图模式/列表模式选择其中一个
      this.selectIds = rel
    },
    _thumbnailChkAll() {
      // 缩略图模式全选
      const idList = []
      const rel = this.fileList
      for (let i = 0; i < rel.length; i++) {
        idList.push(rel[i].id)
      }
      this.selectIds = idList
      this.thumbnailValue = idList
    },
    _listChkAll() {
      // 列表模式全选
      const idList = []
      const rel = this.fileList
      for (let i = 0; i < rel.length; i++) {
        idList.push(rel[i].id)
      }
      this.selectIds = idList
      this.listValue = idList
    },
    _unCheckAll() {
      if (this.viewStyle == '1') {
        this.$refs.selection.selectAll(false)
      } else if (this.viewStyle == '2' || this.viewStyle == '3') {
        this.selectIds = []
        this.thumbnailValue = []
        this.listValue = []
      }
    },
    _deleteByIds(ids, type) {
      this.$Modal.confirm({
        title: '提示',
        content: '确定要删除这 ' + ids.length + ' 个文件？',
        onOk: () => {
          if (type !== undefined) {
            this.$store
              .dispatch('SysFileStatistics/deleteByIds', ids)
              .then(() => {
                // 删除文件
                if (this.$store.state.SysFileStatistics.success) {
                  this.$Message.success('删除成功！')
                  this._refresh()
                }
              })
          }
        }
      })
    },
    _deleteById(id, type) {
      // 删除一条记录
      this._deleteByIds([id], type)
    },
    _deleteSelected() {
      // 批量删除
      const ids = this.selectIds
      if (ids.length === 0) {
        this.$Message.warning('请选择一条或多条数据！')
      } else {
        this._deleteByIds(ids, '', '')
      }
    },
    _refresh() {
      // 根据分页及floderId,查询条件刷新
      this._filetree()
      this.thumbnailValue = []
      this.listValue = []
    },
    _download(id) {
      // 下载
      this.$Modal.confirm({
        title: '提示',
        content: '确定要下载？',
        onOk: () => {
          window.open(
            global.baseURL + '/statistics/v1/file/download/' + id,
            '_blank'
          )
        }
      })
    },
    _versonData() {
      this._filetree()
    },
    _version(rel) {
      // 历史版本
      this.$refs.versionFile._open(rel)
    },
    _checkIn(data) {
      // 签入
      this.$refs.fileUpdateModal._open(data)
    },
    _treeHide() {
      // 左侧树隐藏
      this.isTree = false
      this.tableStyleObj.marginLeft = '15px'
    },
    _treeShow() {
      this.isTree = true
      this.tableStyleObj.marginLeft = '215px'
    },
    /** ********************获取文件权限********************************/
    // 权限从小到大依次是 0,3,1,2
    _getMaxPre(result) {
      const list = result
      const index = list.findIndex(item => item === 3)
      if (index !== -1) {
        list.splice(index, 1)
        if (Math.max.apply(null, list) === 0) {
          return 3
        } else {
          return Math.max.apply(null, list)
        }
      } else {
        return Math.max.apply(null, list)
      }
    },
    _getFilePre(data) {
      this.menuList = []
      this.$store.dispatch('SysFileStatistics/authorize', data.id).then(() => {
        const result = this.$store.state.SysFileStatistics.model

        // 获取最大权限
        const max = this._getMaxPre(result)
        console.log(max, 'max')
        if (max === 0) {
          // 查看
          if (this.$fileFormat(data.type) === 'other') {
            // 其他格式
            this._noFileTip()
          } else {
            this.menuList = [this.view]
          }
        } else if (max === 1) {
          // 上传
          // txt格式不支持编辑，则按钮自动变为预览
          // 图片格式也自动变为预览
          if (this.$fileFormat(data.type) === 'other') {
            // 其他格式
            this.menuList = [this.down, this.version, this.upload]
          } else {
            let fileType = ''
            if (
              data.type.toLowerCase() === 'txt' ||
              this.$fileFormat(data.type, 'img')
            ) {
              fileType = this.view
            } else {
              fileType = this.edit
            }
            this.menuList = [
              fileType,
              this.down,
              this.version,
              this.upload,
              this.change
            ]
          }
        } else if (max === 2) {
          // 删除
          // txt格式不支持编辑，则按钮自动变为预览
          // 图片格式也自动变为预览
          if (this.$fileFormat(data.type) === 'other') {
            // 其他格式
            this.menuList = [this.down, this.version, this.upload, this.del]
          } else {
            let fileType = ''
            if (
              data.type.toLowerCase() === 'txt' ||
              this.$fileFormat(data.type, 'img')
            ) {
              fileType = this.view
            } else {
              fileType = this.edit
            }
            this.menuList = [
              fileType,
              this.down,
              this.version,
              this.upload,
              this.del,
              this.change,
              this.destruction
            ]
          }
        } else if (max === 3) {
          // 查看
          if (this.$fileFormat(data.type) === 'other') {
            // 其他格式
            this.menuList = [this.down]
          } else {
            this.menuList = [this.view, this.down]
          }
        } else {
          // 无任何权限
          this._noFileTip()
        }
      })
    },
    _noFileTip() {
      this.menuList = []
      this.$Notice.error({
        top: 50,
        duration: 10,
        title: '该文件暂无任何权限，请联系管理员!'
      })
    },
    /** ********************获取文件权限********************************/
    /** ********************查看上下级文件********************************/

    // 进入下级，查看下级文件
    _nextLevel(id, pid) {
      this.upLevelPid = pid
      this.folderId = id
      this._getPidList()
    },
    // 上一级文件
    _upLevel() {
      this.$store
        .dispatch('SysFolderStatistics/getById', this.upLevelPid)
        .then(() => {
          // 上级文件夹
          const list1 = this.$store.state.SysFolderStatistics.model
          if (list1 === undefined) {
            // 重置所有数据
            this._refreshFloder()
          } else {
            this.isUpLEevel = true
            this.upLevelPid = list1.pid // 存储pid到div中
            this.folderId = list1.id // 查List列表
            this._getPidList()
          }
        })
    },
    // 获取文件及文件夹(根据文件夹id)
    _getPidList() {
      // 进入文件夹中每次page都为1
      this.isUpLEevel = true
      this.pageList.page = 1
      this.pageList.rows = 20
      this._filetree()
    },
    /** ********************查看上下级文件********************************/
    /** *******************************文件的处理**********************************/
    _viewFile(rel) {
      // 预览文件
      const random = '?' + +'?' + Math.random()
      if (this.$fileFormat(rel.type, 'img')) {
        this.imgName = '预览---' + rel.name
        this.visible = true
        this.imgUrl =
          global.baseURL + '/statistics/v1/file/download/' + rel.id + random
      } else {
        this._optFile(rel, 5, false)
      }
    },
    _optFile(rel, isReport, isEdit) {
      if (rel.type.toLowerCase() === 'pdf') {
        // pdf 单独预览
        this.$pdfView(rel.objectKey)
      } else if (rel.type.toLowerCase() === 'txt') {
        // txt 单独预览
        this.$refs.txtModal._open(rel)
      } else {
        // pageoffice或officeOnline打开
        this.$openWindowModeless({
          objectKey: rel.objectKey,
          id: rel.id,
          isReport: isReport,
          noMark: true,
          isEdit: isEdit
        })
      }
    },
    _editFile(rel) {
      // 编辑文件
      this._optFile(rel, 4, true)
    }
    /** *******************************文件的处理**********************************/
  }
}
</script>
<style scoped>
.file_menu_list {
  overflow: hidden;
  margin-bottom: 0;
}

.file_menu_list li {
  float: left;
  padding: 10px 10px 10px 20px;
  width: 100%;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.file_menu_list li:hover {
  background: #eee;
  cursor: pointer;
}

.span_height {
  width: 16px;
  height: 16px;
  display: inline-block;
  line-height: 16px;
}
</style>
