<template>
  <el-container>
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="7" :xs="24" style="height: 90vh">
        <div class="head-container">
          <el-row :gutter="20">
            <el-col :span="20">
              <el-input
                v-model="deptName"
                placeholder="请输入文件夹名称"
                clearable
                size="small"
                prefix-icon="el-icon-search"
                style="margin-bottom: 20px"
              />
            </el-col>
            <el-col :span="4">
              <el-button type="primary" @click="() => append(0)"
                ><i class="el-icon-folder-add el-icon--left"></i>
              </el-button>
            </el-col>
          </el-row>
        </div>
        <div
          class="head-container"
          style="height: calc(100% - 210px); background: rgba(0, 222, 240, 0.2)"
        >
          <el-tree
            check-strictly
            check-on-click-node
            :data="categoryTree"
            :props="category"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
            >
            <!-- @check="treeCheck" -->
            <div slot-scope="{ node, data }" class="custom-tree-node">
              <el-tooltip
                class="item"
                effect="dark"
                :content="node.label"
                placement="top-start"
                :open-delay="700"
              >
                <div
                  style="
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    max-width: 1.2rem;
                  "
                >
                  {{ node.label }}
                </div>
              </el-tooltip>

              <span>
                <el-button type="text" size="mini" @click="() => append(data)">
                  添加子项
                </el-button>
                <el-button
                  v-if="data.id !== '0'"
                  type="text"
                  size="mini"
                  @click="() => remove(data)"
                >
                  删除
                </el-button>
                <el-button
                  v-else
                  type="text"
                  size="mini"
                  style="visibility: hidden"
                >
                  删除
                </el-button>
              </span>
            </div>
          </el-tree>
        </div>
      </el-col>
      <el-col :span="17" :xs="24" style="height: 90vh">
        <el-button
          style="margin-bottom: 10px"
          type="primary"
          @click="selectedBox()"
          >上传<i class="el-icon-upload el-icon--right"></i
        ></el-button>
        <el-table
          height="calc(100% - 200px)"
          :row-style="{ height: '0px' }"
          :header-cell-style="{ 'text-align': 'center', padding: '0px' }"
          :cell-style="{ 'text-align': 'center', padding: '2px' }"
          style="width: 100%"
          v-loading="loading"
          :data="documentList"
        >
          <el-table-column
            label="序号"
            type="index"
            width="80"
            :index="indexMethod"
          />
          <el-table-column
            label="名称"
            :show-overflow-tooltip="true"
            width="150"
          >
            <template slot-scope="scope">
              <i v-if="scope.row.type === 0" class="el-icon-folder-opened"></i>
              <i v-else class="el-icon-document"></i>
              <span>{{ scope.row.documentName }} </span>
            </template>
          </el-table-column>
          <el-table-column
            label="格式"
            prop="documentFormat"
            :show-overflow-tooltip="true"
            width="150"
          />
          <el-table-column label="大小" prop="documentSize" width="100" />
          <!-- <el-table-column
            label="修改人"
            align="center"
            prop="updateUserId"
            width="100"
          /> -->
          <el-table-column
            label="修改时间"
            align="center"
            prop="updateDate"
            width="180"
          >
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.type !== 1"
                size="mini"
                type="text"
                icon="el-icon-upload"
                @click="documentUplond(scope.row)"
                >上传
              </el-button>
              <el-button
                v-if="scope.row.type !== 0"
                size="mini"
                type="text"
                icon="el-icon-upload"
                @click="documentDownload(scope.row)"
                >下载
              </el-button>
              <el-button
                v-if="scope.row.type !== 0"
                size="mini"
                type="text"
                icon="el-icon-upload"
                @click="preview(scope.row)"
                >预览
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="documentUpdate(scope.row)"
                >修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="documentDel(scope.row)"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <!--文件夹添加 表单 -->
    <!--    <el-button type="text" @click="categoryFormVisible = true">打开嵌套表单的 Dialog</el-button>-->

    <el-dialog
      v-if="categoryFormVisible"
      title="添加文件夹"
      :visible.sync="categoryFormVisible"
      width="800px"
    >
      <el-form :model="categoryForm" ref="categoryFormRef" label-position="right" label-width="120px">
        <el-form-item
          label="文件夹名称"
          prop="categoryName"
          :rules="[{ required: true, message: '文件夹名称不能为空' }]"
        >
          <el-input
            v-model="categoryForm.categoryName"
            style="width: 600px;"
            autocomplete="off"
            placeholder="请填写文件夹名称(必填)"
          ></el-input>
        </el-form-item>
        <el-form-item label="文件夹名称">
          <el-input
            type="textarea"
            style="width: 600px;"
            v-model="categoryForm.remarkInfo"
            placeholder="请填写文件夹备注"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="categoryFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitCategory(categoryForm)"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      v-if="updataNameFormVisible"
      :title="isEdit"
      :visible.sync="updataNameFormVisible"
      width="600px"
    >
      <el-form :model="documentForm" ref="documentFormRef">
        <el-form-item
          label="名称"
          prop="documentName"
          :rules="[{ required: true, message: '文件夹名称不能为空' }]"
        >
          <el-input
            v-model="documentForm.documentName"
            style="width: 500px;"
            autocomplete="off"
            placeholder="请填写名称(必填)"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updataNameFormVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="
            submitCategoryAndDocument(documentForm)
            updataNameFormVisible = false
          "
          >确 定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      v-if="uploadFormVisible"
      title="上传"
      :visible.sync="uploadFormVisible"
    >
      <div>
        <el-upload
          class="upload-demo"
          drag
          action="#"
          :on-change="changePreview"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          :limit="3"
          :on-exceed="handleExceed"
          :file-list="fileList"
          :auto-upload="false"
          :http-request="handleChange"
          multiple
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <!--          <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>-->
        </el-upload>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadFormVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="
            uploadFormVisible = false
            uploadFileSubmit()
          "
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 文件预览 -->
    <el-dialog
      title="预览附件"
      :visible.sync="previewAnnex"
      :fullscreen="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
    >
      <div class="bbbbb">
        <preview-file
          :preview-url="previewUrl"
          :preview-type="previewType"
          @handleDownload="handleDownload"
        />
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import previewFile from '@/components/previewFile/previewFile.vue'

import {
  listDocument,
  catefoyTreeSelect,
  saveCategory,
  delCategory,
  resourceDownload,
  uploadFileHttp,
  saveDocument,
  delDocument,
  getBaseApi
} from '@/api/system/document'
import FileSaver from 'file-saver'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  components: {
    previewFile
  },
  data() {
    return {
      isEdit:'',
      loadFile:false,

      // 文件预览
      previewAnnex: false,
      previewUrl: '',
      previewType: '',
      filename: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文档列表数据
      documentList: null,
      // 弹出层标题
      title: '',
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      categoryFormVisible: false,
      uploadFormVisible: false,
      updataNameFormVisible: false,
      // 文件夹列表
      categoryTree: [],
      // 文件夹对象
      category: {
        children: 'categoryList',
        label: 'categoryName'
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        documentName: '',
        basicSafetyCategoryId: '0',
        companyCode: '',
        documentFormat: ''
      },
      // 文件夹表单
      categoryForm: {
        id: '',
        categoryName: '',
        categoryCode: '',
        categorySort: 0,
        parentId: '',
        companyCode: '',
        isDel: 0,
        createUserId: 0,
        createDate: '2023-08-15 22:01:01',
        updateUserId: 0,
        updateDate: '2023-08-15 22:01:01',
        remarkInfo: ''
      },

      documentForm: {
        id: '',
        documentSort: 0,
        documentName: '',
        basicSafetyCategoryId: '',
        uploadUrl: '',
        documentFormat: '',
        documentSize: '',
        companyCode: '',
        createUserId: 0,
        updateUserId: 0,
        remarkInfo: ''
      },
      documentFormList: [],
      deptName: '',
      fileList: [],
      basicSafetyCategoryId: ``,
      UNITS: ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
      STEP: 1024,
      formDataList: {},
      formDataTree: []
    }
  },
  watch: {
    // 根据名称筛选择文件夹树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getCatefoyTree()
    this.getList()
  },

  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true
      console.log(this.queryParams, 999)
      listDocument(this.queryParams).then((response) => {
        console.log(response, 888)
        this.documentList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // treeCheck(node, list) {
    //   //node 该节点所对应的对象、list 树目前的选中状态对象
    //   //选中事件在选中后执行，当lis中有两个选中时，使用setCheckedKeys方法，选中一个节点
    //   if (list.checkedKeys.length == 2) {
    //     //单选实现
    //     this.$refs.tree.setCheckedKeys([node.PHY_ID])
    //   }
    // },
    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 查询列表方法

    /**序號自增*/
    indexMethod(index) {
      return (
        (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1
      )
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 查询文件夹树 */
    getCatefoyTree() {
      console.log(
        this.queryParams.basicSafetyCategoryId,
        this.basicSafetyCategoryId
      )
      catefoyTreeSelect(
        this.queryParams.basicSafetyCategoryId ||
          this.basicSafetyCategoryId ||
          '0'
      ).then((response) => {
        this.categoryTree = response.data
        console.log(response.data)
        // if (this.queryParams.basicSafetyCategoryId !== `0`) {
        //   this.queryParams.basicSafetyCategoryId = this.categoryTree[0].id
        // }
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.categoryName.indexOf(value) !== -1
    },
    // 文件夹表单提交 http://localhost:8080/system/category/add
    submitCategory(categoryForm) {
      this.$refs.categoryFormRef.validate((va) => {
        if (va) {
          saveCategory(categoryForm).then((res) => {
            if (res.code === 200) {
              this.$modal.msgSuccess('保存成功')
              this.categoryFormVisible = false
              this.getCatefoyTree()
            } else {
              this.$modal.msgError('保存失败')
            }
          })
        } else {
          return false
        }
      })
    },
    async submitCategoryAndDocument(documentForm) {
      if (documentForm.type === 1) {
        let obj = {
          id: documentForm.id,
          documentName: documentForm.documentName
        }
        const res = await saveDocument(obj)
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
        } else {
          this.$modal.msgError(`操作失败！`)
        }
      } else {
        let obj = {
          id: documentForm.id,
          categoryName: documentForm.documentName
        }
        const res = await saveCategory(obj)
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
        } else {
          this.$modal.msgError(`操作失败！`)
        }
      }
      this.getCatefoyTree()
      this.getList()
    },
    // -- 文件上传
    handleRemove(file, fileList) {
      var _tmp = this.fileList
      for (var i = 0, len = _tmp.length; i < len; i++) {
        if ((_tmp[i].name = file.name)) {
          _tmp.splice(i, 1)
          break
        }
      }
      this.fileList = _tmp
    },
    changePreview(file, fileList) {
      this.fileList = fileList
    },
    startLoading() {
      this.loadFile = this.$loading({
        lock: true,
        text: "加载中,请稍候...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.4)"
      });
    },
    /** 关闭loading* */
    closeLoading() {
      this.loadFile.close();
    },
    preview(row) {
      this.startLoading();
      getBaseApi(row.uploadUrl).then((res) => {
        if (res.code !== 200) return this.$message.error(res.msg)
        let wj = encodeURIComponent(res.msg)
        wj = decodeURIComponent(wj)
        const myBlob = this.dataURLtoBlob(wj)
        this.previewUrl = myBlob
        this.previewType = row.documentFormat //this.iconByType(type.split(".")[type.split(".").length - 1]);
        let fileName = row.documentName
        if (!fileName.includes(row.documentFormat)) {
          fileName = row.documentName + `.` + row.documentFormat
        }
        this.filename = fileName
        this.previewAnnex = true
        this.closeLoading();
      })
    }, // 获取文件后缀名
    iconByType(filename) {
      return filename.substring(filename.lastIndexOf('.') + 1, filename.length)
    },
    handleDownload() {
      // 生成地址
      const myUrl = URL.createObjectURL(this.previewUrl)
      // 下载文件
      this.downloadFile(myUrl, this.filename)
    },
    dataURLtoBlob(dataurl) {
      const arr = dataurl.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      // eslint-disable-next-line no-plusplus
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    },
    downloadFile(url, name) {
      const a = document.createElement('a')
      a.setAttribute('href', url)
      a.setAttribute('download', name)
      a.setAttribute('target', '_blank')
      const clickEvent = document.createEvent('MouseEvents')
      clickEvent.initEvent('click', true, true)
      a.dispatchEvent(clickEvent)
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      )
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    // 组装上传内容
    handleChange(file, fileList) {},
    // 计算文件大小
    format: function format(value, power) {
      return (value / Math.pow(this.STEP, power)).toFixed(2) + this.UNITS[power]
    },
    readFileSizeUnit: function (value) {
      value = parseFloat(value, 10)
      for (var i = 0; i < this.UNITS.length; i++) {
        if (value < Math.pow(this.STEP, i)) {
          if (this.UNITS[i - 1]) {
            return this.format(value, i - 1)
          }
          return value + this.UNITS[i]
        }
      }
      return this.format(value, i - 1)
    },

    // 提交上传内容
    uploadFileSubmit() {
      // 创建新的数据对象
      let formData = new FormData()
      let map = new Map()
      this.fileList.forEach((x, index) => {
        formData.append(`files`, x.raw)
        map.set(x.name, this.readFileSizeUnit(x.size))
      })
      uploadFileHttp(formData)
        .then((res) => {
          this.formDataList = {}
          this.fileList = []
          this.documentFormList = []
          if (res.code === 200) {
            let fileUrlList = res.fileNames.split(`,`)
            let originalFilenames = res.originalFilenames.split(`,`)
            fileUrlList.forEach((item, index) => {
              let split = originalFilenames[index].split(`.`)
              this.documentForm = {}
              this.documentForm.documentName = originalFilenames[index]
              this.documentForm.uploadUrl = item
              this.documentForm.basicSafetyCategoryId =
                this.basicSafetyCategoryId
              this.documentForm.documentFormat = split[split.length - 1]
              this.documentForm.documentSize = map.get(originalFilenames[index])
              this.documentFormList.push(this.documentForm)
            })
            this.saveDocument(this.documentFormList)
            // 请求文档保存接口
          } else {
            this.$modal.msgError(`上传失败！`)
          }
        })
        .catch((err) => {
          this.getList()
          this.formDataList = {}
          this.fileList = []
          if (err.code === 500) {
            this.$modal.msgError(err.msg)
          } else {
            this.$modal.msgError(`上传失败！`)
          }
        })
      // }
    },
    documentUplond(data) {
      this.basicSafetyCategoryId = data.id
      this.uploadFormVisible = true
    },

    saveDocument(dataList) {
      let nameList = []
      dataList.forEach((t) => {
        saveDocument(t).then((res) => {
          if (res.code === 500) {
            nameList.push(data.documentName)
          } else {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.getCatefoyTree()
          }
        })
      })
      dataList = []
      if (nameList.length > 0) {
        this.$confirm('文件[' + nameList + ']添加失败。', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      }
      setTimeout(() => {
        this.getList()
      }, 500)
    },
    // 删除列表数据
    documentDel(data) {
      if (data.type === 0) {
        // 删除分类
        this.remove(data)
      } else {
        this.$confirm('此操作将永久删除该项, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            // 删除文件
            let obj = [data.id]
            if (data.type === 0) {
              delCategory(obj).then((res) => {
                if (res.code === 200) {
                  this.$message({
                    type: 'success',
                    message: '删除成功!'
                  })
                  this.queryParams.basicSafetyCategoryId =
                    data.basicSafetyCategoryId
                  this.getCatefoyTree()
                  this.getList()
                }
              })
            } else {
              delDocument(obj).then((res) => {
                if (res.code === 200) {
                  this.$message({
                    type: 'success',
                    message: '删除成功!'
                  })
                  this.queryParams.basicSafetyCategoryId =
                    data.basicSafetyCategoryId
                  this.getCatefoyTree()
                  this.getList()
                }
              })
            }
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      }
    },
    async documentUpdate(data) {
      this.isEdit = "修改名称"
      this.documentForm.id = data.id
      this.documentForm.type = data.type
      this.documentForm.documentName = data.documentName
      this.updataNameFormVisible = true
    },

    documentDownload(data) {
      resourceDownload(data.uploadUrl).then((res) => {
        const aBlob = new Blob([res])
        let fileName = data.documentName
        if (!fileName.includes(data.type)) {
          fileName = data.documentName + `.` + data.documentFormat
        }
        FileSaver.saveAs(aBlob, fileName)
      })
    },
    append(data) {
      // this.categoryForm.parentId=``
      this.categoryForm.categoryName = ``
      this.categoryForm.remarkInfo = ``
      if (data === 0) {
        this.categoryForm.parentId = '0'
        this.categoryFormVisible = true
      } else {
        this.categoryForm.parentId = data.id
        this.categoryFormVisible = true
      }
    },
    // 删除文件夹
    remove(data) {
      this.$confirm('此操作将永久删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 删除文件
          let obj = [data.id]
          delCategory(obj).then((res) => {
            if (res.code === 200) {
              this.$modal.msgSuccess('删除成功')
              // 刷新文件夹
              this.getCatefoyTree()
              this.getList()
            } else {
              this.$modal.msgError(res.msg)
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.basicSafetyCategoryId = data.id
      this.basicSafetyCategoryId = data.id
      this.getList()
    },
    selectedBox() {
      console.log(this.$refs.tree.getCheckedNodes());
      this.formDataTree = [this.$refs.tree.getCheckedNodes()[this.$refs.tree.getCheckedNodes().length-1]]
      if (this.formDataTree.length === 1) {
        this.uploadFormVisible = true
        this.formDataTree.forEach((item) => {
          this.queryParams.basicSafetyCategoryId = item.id
        })
      } else {
        this.$message({
          type: 'info',
          message: '请选择一个文件夹上传文件'
        })
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: '0',
        remark: undefined,
        postIds: [],
        roleIds: []
      }
      // this.resetForm("form");
    }
  }
}
</script>
<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background-color: #2d4965;
}

::v-deep .el-upload-dragger {
  border: 1px dashed #fff;
  width: 350px !important;
  height: 150px;
}

.flex_box {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
