<template>
  <div class="app-container">
    <div class="app-btn">
      <div class="btn-l">
        <el-button :disabled="isDisableAdd" class="filter-item" type="primary" icon="el-icon-edit" @click="form_add">新增</el-button>
        <el-upload
          style="display: inline-block;margin-left: 10px;"
          :headers="headers"
          :data="uploadData"
          :action="uploadExcelUrl"
          :show-file-list="false"
          :before-upload="beforeImportExcel"
          :on-success="handleImportExcelSuccess"
          :on-error="handleImportExcelErro"
        >
          <el-button v-if="true" v-waves :disabled="isDisableImport" class="filter-item" type="warning" icon="el-icon-upload2">上传</el-button>
        </el-upload>
        <!-- <el-button class="filter-item" :disabled="isDisableDownload" style="margin-left: 10px;" type="success" icon="el-icon-edit" @click="handleDownloadFolder">下载</el-button> -->
        <!-- 文件夹批量删除 -->
        <el-button v-if="isFolderDelate" class="filter-item" :disabled="isDisableDelate" style="margin-left: 10px;" type="danger" icon="el-icon-delete" @click="handleFolderDelate">删除</el-button>
        <!-- 多文件下载 -->
        <el-button v-if="isFileDownload" class="filter-item" style="margin-left: 10px;" type="success" icon="el-icon-download" @click="handleFileDownload">下载</el-button>
        <!-- 多文件删除 -->
        <el-button v-if="isFileDelate" class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-delete" @click="handleFileDelate">删除</el-button>
      </div>
      <div v-if="isFilter1" class="btn-r">
        <el-input v-model="getdataListAllParm.parammaps.docname" placeholder="文件名称" style="width: 140px;" class="filter-item" />
        <el-button v-if="isFilter1" class="filter-item" type="primary" icon="el-icon-search" @click="form_search">搜索</el-button>
      </div>
      <div v-if="isFilter2" class="btn-r">
        <el-input v-model="getdataListParmDetail.parammaps.docname" placeholder="文件名称" style="width: 140px;" class="filter-item" />
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="form_search2">搜索</el-button>
      </div>
    </div>
    <!-- 文件夹列表 -->
    <div v-if="fileList" class="app-list">
      <div v-for="(item, index) in list" :key="index" :body-style="{ padding: '5px' }" class="contentCard">
        <div class="contentCard-img">
          <svg-icon :icon-class="'file1'" class="contentCard-icon" @click="handlFile(item)" />
          <el-checkbox v-model="item.checkeds" name="type" class="contentCard-checkbox" />
        </div>
        <div class="contentCard-title">
          <span v-if="item.isDirectName" class="contentCard-title-name" @click="form_edit(item)">{{ item.direct }}</span>
          <input v-if="item.isDirectInput" id="direct" v-model="item.direct" class="contentCard-title-input" type="text" @blur="blurName(item)">
        </div>
      </div>
    </div>

    <!-- 文件详情列表 -->
    <div v-if="detailList" class="app-detailList">
      <div class="title">
        <a class="all-file" @click="goBack">全部文件</a>
        <span>&gt;{{ temp.direct }}</span>
      </div>
      <el-table
        v-loading="listLoadingDetail"
        element-loading-text="给我一点时间"
        :data="listDetail"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        class="elTable table-fixed"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" align="center" type="index" width="50px">
          <template slot-scope="scope">
            <span>{{ scope.$index + (pageNumDetail-1) * pageSizeDetail + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="文档名称" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.docname }}</span>
          </template>
        </el-table-column>
        <el-table-column label="文件大小" width="140px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.fileSize }}</span>
          </template>
        </el-table-column>
        <el-table-column label="上传时间" min-width="80px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.dtime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">
            <el-button type="success" size="mini" @click="handleDownloadRow(row)">下载</el-button>
            <el-button type="danger" size="mini" @click="handleDelateRow(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="totalDetail>0" :total="totalDetail" :page.sync="getdataListParmDetail.offset" :limit.sync="getdataListParmDetail.pagecount" @pagination="getListDetail" />
    </div>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="50%">
      <div class="app-content">
        <el-form
          ref="createTemp"
          :rules="rules"
          :model="createTemp"
          label-position="right"
          label-width="115px"
          style="width: 50%;margin:0 auto 30px"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="文件名称：" prop="direct">
                <el-input ref="direct" v-model="createTemp.direct" placeholder="请输入文件名称" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer" style="right:30px;position:absolute;bottom:5px">
          <el-button type="primary" :disabled="isokDisable" @click="dialogStatus==='create'?add_dialog_save():add_dialog_save()">保存并关闭</el-button>
          <el-button @click="dialogFormVisible = false; getList()">取消并关闭</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { GetDataByName, PostDataByName, failproccess, ExecDataByConfig } from '@/api/common'
import { getToken } from '@/utils/auth'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import axios from 'axios'
import { MessageBox } from 'element-ui'
export default {
  name: 'File',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      isDisableAdd: false,
      isDisableImport: true,
      // isDisableDownload: true,
      isDisableDelate: false,
      isokDisable: false,
      isDirectName: true,
      isDirectInput: false,
      isFilter1: true,
      isFilter2: false,
      rules: {
        direct: [{ required: true, message: '必填', trigger: 'blur' }]
      },
      checkeds: [],
      getdataListParm: {
        name: 'getDirectorylist',
        parammaps: {}
      },
      list: [],
      total: 0,
      pageNum: '',
      pageSize: '',
      listLoading: true,
      textMap: {
        create: '新增'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      createTemp: {
        direct: ''
      },
      requestParam: {},
      fileList: true,
      detailList: false,
      listDetail: [],
      listLoadingDetail: false,
      totalDetail: 0,
      getdataListParmDetail: {
        name: 'getFilelist',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {
          id: '',
          docname: ''
        }
      },
      getdataListAllParm: {
        name: 'searchFileList',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {
          docname: ''
        }
      },
      temp: {},
      postDataPramas: {},
      isFolderDelate: true,
      isFileDownload: false,
      isFileDelate: false,
      selectionList: []
    }
  },
  computed: {
    // 设置请求头
    headers() {
      return {
        optname: 'insertcustomdoc',
        id: 1,
        token: getToken()
      }
    },
    uploadData() {
      return {
        // name: 'importOilcard',
        // importParams: '文档名称,文件大小,上传时间',
        // sheetname: 'SheetJS'
      }
    },
    uploadExcelUrl() {
      // process.env.VUE_APP_BASE_API是服务器的路径，也是axios的基本路径
      return process.env.VUE_APP_BASE_API + 'authdata/upload' + '/' + this.temp.id + '/' + this.temp.direct
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      GetDataByName(this.getdataListParm).then(response => {
        console.log('list数据', response.data.list)
        if (response.data.list.length > 0) {
          for (var i = 0; i < response.data.list.length; i++) {
            if (response.data.list[i].checkeds == 'false') {
              response.data.list[i].checkeds = false
              response.data.list[i].isDirectName = true
              response.data.list[i].isDirectInput = false
            }
          }
        }
        this.list = response.data.list
        this.pageNum = response.data.pageNum
        this.pageSize = response.data.pageSize
        if (response.data.total) {
          this.total = response.data.total
        }
        setTimeout(() => {
          this.listLoading = false
        }, 100)
      })
    },
    form_search() {
      // 隐藏文件夹，显示文件
      this.fileList = false
      this.detailList = true
      console.log('点击了全局搜索')
      this.listLoadingDetail = true
      this.getdataListAllParm.offset = 1
      GetDataByName(this.getdataListAllParm).then(response => {
        console.log('list数据', response.data.list)
        this.listDetail = response.data.list
        this.pageNumDetail = response.data.pageNum
        this.pageSizeDetail = response.data.pageSize
        if (response.data.total) {
          this.totalDetail = response.data.total
        }
        setTimeout(() => {
          this.listLoadingDetail = false
        }, 100)
      })
    },
    form_search2() {
      console.log('点击了局部搜索')
      this.getdataListParmDetail.offset = 1
      this.getListDetail()
    },
    resetCreateTemp() {
      this.createTemp.direct = ''
    },
    // 新建文件
    form_add() {
      this.resetCreateTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    add_dialog_save() {
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.$refs['createTemp'].validate(valid => {
        if (valid) {
          this.requestParam.name = 'insertDirectory'
          this.requestParam.parammaps = {}
          this.requestParam.parammaps.direct = this.createTemp.direct
          PostDataByName(this.requestParam).then(response => {
            console.log('新增保存发送参数', this.requestParam)
            if (response.msg !== 'fail') {
              this.dialogFormVisible = false
              this.getList()
              this.$notify({
                title: '成功',
                message: '新增成功',
                type: 'success',
                duration: 2000
              })
            } else {
              failproccess(response, this.$notify)
            }
          })
        }
      })
    },
    // 点击文件名进行更新
    form_edit(item) {
      console.log('点击标题得到数据', item)
      for (var i = 0; i < this.list.length; i++) {
        if (this.list[i].id === item.id) {
          this.list[i].isDirectName = false
          this.list[i].isDirectInput = true
        }
      }
      this.$nextTick(() => {
        document.getElementById('direct').focus()
      })
    },
    blurName(item) {
      console.log('失去焦点得到的值', item)
      item.isDirectName = true
      item.isDirectInput = false
      this.requestParam.name = 'updateDirectory'
      this.requestParam.parammaps = {}
      this.requestParam.parammaps.id = item.id
      this.requestParam.parammaps.direct = item.direct
      PostDataByName(this.requestParam).then(response => {
        console.log('修改保存发送参数', this.requestParam)
        if (response.msg !== 'fail') {
          this.dialogFormVisible = false
          this.getList()
          this.$notify({
            title: '成功',
            message: '修改成功',
            type: 'success',
            duration: 2000
          })
        } else {
          failproccess(response, this.$notify)
        }
      })
    },
    // 点击文件夹
    handlFile(item) {
      // 隐藏多文件夹上传
      this.isFolderDelate = false
      // 隐藏多文件导出
      this.isFileDownload = true
      // 隐藏多文件删除
      this.isFileDelate = true

      console.log('点击了文件', item)
      this.temp = item
      this.fileList = false
      this.detailList = true
      this.isDisableAdd = true
      this.isDisableImport = false
      // this.isDisableDownload = false
      // this.isDisableDelate = false
      // 搜索1隐藏，搜索2显示
      this.isFilter1 = false
      this.isFilter2 = true
      this.getdataListParmDetail.parammaps.id = item.id
      this.getListDetail()
    },
    // 文件详情
    getListDetail() {
      this.listLoadingDetail = true
      GetDataByName(this.getdataListParmDetail).then(response => {
        console.log('list数据', response.data.list)
        console.log(response.data.pageNum, response.data.pageSize)
        if (response.data.list !== null || response.data !== null) {
          this.listDetail = response.data.list
          this.pageNumDetail = response.data.pageNum
          this.pageSizeDetail = response.data.pageSize
          if (response.data.total) {
            this.totalDetail = response.data.total
          }
        } else {
          this.listDetail = []
        }
        setTimeout(() => {
          this.listLoadingDetail = false
        }, 100)
      })
    },
    // 回到全部文件
    goBack() {
      this.fileList = true
      this.detailList = false
      this.isDisableAdd = false
      this.isDisableImport = true
      // this.isDisableDownload = false
      // this.isDisableDelate = false
      // 搜索1显示，搜索2隐藏
      this.isFilter1 = true
      this.isFilter2 = false
      // 文件夹批量删除
      this.isFolderDelate = true
      // 多文件导出
      this.isFileDownload = false
      // 多文件删除
      this.isFileDelate = false
    },
    // 多文件夹删除
    handleFolderDelate() {
      if (this.list.length > 0) {
        this.checkeds = []
        for (var i = 0; i < this.list.length; i++) {
          if (this.list[i].checkeds == true) {
            this.checkeds.push({ id: this.list[i].id })
          }
        }
        console.log(this.checkeds)
        if (this.checkeds.length > 0) {
          MessageBox.confirm('确认删除以下选中文件?', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.postDataPramas.common = { 'returnmap': '0' }
            this.postDataPramas.data = []
            this.postDataPramas.data[0] = { 'name': 'insertSpotList', 'resultmaps': { 'list': this.checkeds }}
            this.postDataPramas.data[0].children = []
            this.postDataPramas.data[0].children[0] = { 'name': 'deleteDirectory', 'type': 'e', 'parammaps': {
              id: '@insertSpotList.id'
            }}
            ExecDataByConfig(this.postDataPramas).then(response => {
              console.log('删除保存发送参数', this.postDataPramas)
              if (response.msg === 'fail') {
                this.$notify({
                  title: '删除失败',
                  message: response.data,
                  type: 'warning',
                  duration: 2000
                })
              } else {
                this.dialogFormVisible = false
                this.getList()
                this.$notify({
                  title: '',
                  message: '删除成功',
                  type: 'success',
                  duration: 2000
                })
              }
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
        } else {
          this.$message({
            type: 'warning',
            message: '请选择要删出的文件夹'
          })
        }
      } else {
        this.$message({
          type: 'warning',
          message: '无文件要删除'
        })
      }
    },

    // 文件上传
    beforeImportExcel(file) {
      const isLt100M = file.size / 1024 / 1024 < 100
      if (!isLt100M) {
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      return isLt100M
    },
    // 文件上传成功
    handleImportExcelSuccess(res, file) {
      if (res.execresult.RowsAffected > 0) {
        this.$message({
          title: '成功',
          message: '上传成功',
          type: 'success',
          duration: 2000
        })
        this.getListDetail()
      } else {
        this.$notify({
          title: '失败',
          message: '上传失败或文件名重复',
          type: 'danger',
          duration: 2000
        })
      }
    },
    // 文件上传失败
    handleImportExcelErro(err, file, fileList) {
      console.log(err.message)
      this.$message.error(err.message)
      // const message = new RegExp('不支持的文件类型')
      // if (message.test(err.message)) {
      //   this.$message.error('不支持的文件类型')
      // }
    },
    // 下载文件
    handleDownloadFolder() {
      console.log('点击了文件夹下载-接口待对', this.checkeds)
      this.checkeds = []
      for (var i = 0; i < this.list.length; i++) {
        if (this.list[i].checkeds == true) {
          console.log(this.list[i])
          this.checkeds.push(this.list[i].id)
        }
      }
      console.log(this.checkeds)
      if (this.checkeds.length > 0) {

      } else {
        console.log('请选择文件夹')
      }
    },
    // 多文件下载
    handleFileDownload() {
      if (this.listDetail.length > 0) {
        if (this.selectionList.length > 0) {
          console.log(this.selectionList)
          for (let i = 0; i < this.selectionList.length; i++) {
            const url = process.env.VUE_APP_BASE_API + 'authdata/downloadfile' + '/' + this.selectionList[i].id// 请求下载文件的地址
            axios.get(url, {
              headers: {
                token: getToken(),
                optname: 'insertcustomdoc'
              },
              responseType: 'blob'
            }).then(res => {
              if (!res) return
              const blob = new Blob([res.data], {
                type: 'application/octet-stream;charset=utf-8'
              })
              const url = window.URL.createObjectURL(blob)
              const aLink = document.createElement('a')
              aLink.style.display = 'none'
              aLink.href = url
              const docname = this.selectionList[i].docname
              aLink.setAttribute('download', docname) // 下载的文件
              document.body.appendChild(aLink)
              aLink.click()
              document.body.removeChild(aLink)
              window.URL.revokeObjectURL(url)
            }).catch(error => {
              this.$message.error(error)
            })
          }
        } else {
          this.$message({
            type: 'warning',
            message: '请选择要下载的文件'
          })
        }
      } else {
        this.$message({
          type: 'warning',
          message: '无文件要下载'
        })
      }
    },

    // 多文件删除
    handleFileDelate() {
      if (this.listDetail.length > 0) {
        if (this.selectionList.length > 0) {
          console.log(this.selectionList)
          MessageBox.confirm('确认删除此信息?', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            for (let i = 0; i < this.selectionList.length; i++) {
              const url = process.env.VUE_APP_BASE_API + 'authdata/removefile' + '/' + this.selectionList[i].id
              const token = getToken()
              axios.defaults.headers.common['Authorization'] = token
              axios.defaults.headers.common['token'] = token
              axios.post(url, {}).then(res => {
                console.log(res)
                if (res.data.msg == 'ok') {
                  this.$message({
                    title: '成功',
                    message: '删除成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.getListDetail()
                } else {
                  this.$notify({
                    title: '失败',
                    message: '删除失败',
                    type: 'danger',
                    duration: 2000
                  })
                }
              }).catch(error => {
                this.$message.error(error)
              })
            }
          })
        } else {
          this.$message({
            type: 'warning',
            message: '请选择要下载的文件'
          })
        }
      } else {
        this.$message({
          type: 'warning',
          message: '无文件要下载'
        })
      }
    },
    // 行内下载
    handleDownloadRow(row) {
      console.log('行内下载')
      const url = process.env.VUE_APP_BASE_API + 'authdata/downloadfile' + '/' + row.id// 请求下载文件的地址
      axios.get(url, {
        headers: {
          token: getToken(),
          optname: 'insertcustomdoc'
        },
        responseType: 'blob'
      }).then(res => {
        if (!res) return
        const blob = new Blob([res.data], {
          type: 'application/octet-stream;charset=utf-8'
        })
        const url = window.URL.createObjectURL(blob)
        const aLink = document.createElement('a')
        aLink.style.display = 'none'
        aLink.href = url
        console.log(row.docname)
        const docname = row.docname
        aLink.setAttribute('download', docname) // 下载的文件
        document.body.appendChild(aLink)
        aLink.click()
        document.body.removeChild(aLink)
        window.URL.revokeObjectURL(url)
      }).catch(error => {
        this.$message.error(error)
      })
    },
    // 行内删除
    handleDelateRow(row) {
      const url = process.env.VUE_APP_BASE_API + 'authdata/removefile' + '/' + row.id
      const token = getToken()
      axios.defaults.headers.common['Authorization'] = token
      axios.defaults.headers.common['token'] = token
      axios.post(url, {}).then(res => {
        console.log(res)
        if (res.data.msg == 'ok') {
          this.$message({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getListDetail()
        } else {
          this.$notify({
            title: '失败',
            message: '删除失败',
            type: 'danger',
            duration: 2000
          })
        }
      }).catch(error => {
        this.$message.error(error)
      })
    },
    handleSelectionChange(val) {
      console.log(val)
      this.selectionList = val
    }
  }
}
</script>
<style lang="scss" scoped>
  .time {
    font-size: 13px;
    color: #999;
  }

  .bottom {
    margin-top: 13px;
    line-height: 12px;
  }

  .button {
    padding: 0;
    float: right;
  }

  .image {
    width: 100%;
    display: block;
  }

  .clearfix:before,
  .clearfix:after {
      display: table;
      content: "";
  }

  .clearfix:after {
      clear: both
  }
  .app-btn{
    height: 50px;
    .btn-l{float: left;}
    .btn-r{
      float: right;
    }
  }
  .content{
    clear: both
  }
  .el-input input{
    width: 100px !important;
    height: 20px !important;
  }

  .contentCard{
    width: 10%;
    height: 150px;
    float: left;
    .contentCard-img{
      width: 10%;
      height: 100px;
      position: relative;
      left: 0;
      right: 0;
      margin: 0 auto;
      .contentCard-icon{
        position:absolute;
        width:100px;
        height:100px;
        left: 50%;
        margin-left: -50px;
        top: 50%;
        margin-top: -50px;
      }
      .contentCard-checkbox{
        position:absolute;
        right:-35px;
        bottom:10px;
      }
    }
    .contentCard-title{
      width:100px;
      margin:0 auto;
      text-align:center;
      line-height:20px;
      .contentCard-title-name{
        text-align: center;
      }
      .contentCard-title-input{
        width: 100px;
        outline:medium;
        border:none;
        border: 1px solid #DCDFE6;
        color: #606266;
      }
    }
  }
  .app-detailList{
    .title{
      height: 50px;
      line-height: 50px;
      .all-file{
        font-weight: 700;
      }
    }
  }
</style>

