<style scoped>
@import url("./iconfont.css");
.matter-icon {
  font-size: 25px;
}
.matter-title {
  top: -5px;
  display: inline;
  margin-left: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  position: relative;
}
</style>

<template>
  <div style="height: 100%">
    <el-row>
      <el-button size="mini" type="success" @click="dialogVisible = true"
        >上传文件</el-button
      >
      <el-button size="mini" type="primary" @click="createFolder"
        >新建文件夹</el-button
      >
      <!-- <el-button size="mini" type="info">移动文件</el-button>
      <el-button size="mini" type="warning">下载文件</el-button> -->
      <el-button size="mini" type="danger" @click="removeFiles"
        >删除文件</el-button
      >
    </el-row>
    <div style="margin: 20px 0px">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item
          ><a @click.prevent="getAllFiles">全部文件</a></el-breadcrumb-item
        >
        <el-breadcrumb-item v-for="(item, index) in currentDirList" :key="index"
          ><a
            @click.prevent="viewFiles(item, index)"
            href="javascript:void(0)"
            >{{ item }}</a
          ></el-breadcrumb-item
        >
      </el-breadcrumb>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData"
      size="medium"
      stripe
      style="width: 100%"
      height="700px"
      tooltip-effect="dark"
      v-el-table-infinite-scroll="onScrollEnd"
      @selection-change="onSelectionChange"
    >
      <el-table-column
        type="selection"
        width="30"
        :selectable="onSelectable"
      ></el-table-column>
      <el-table-column label="文件">
        <template slot-scope="scope">
          <i
            v-if="scope.row.is_dir"
            class="matter-icon el-icon-folder"
            style="color: #ffc402"
          ></i>
          <i v-else :class="`iconfont matter-icon ${scope.row.icon}`"></i>
          <el-link
            :underline="false"
            class="matter-title"
            href="Javascript: void(0);"
          >
            <span @click="onNameClick(scope.row)">{{ scope.row.name }}</span>
          </el-link>
        </template>
      </el-table-column>
      <el-table-column
        prop="size"
        label="文件大小"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="create_at"
        label="创建日期"
        width="180"
      ></el-table-column>
      <el-table-column
        prop="create_by.username"
        label="创建者"
        width="150"
      ></el-table-column>
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button icon="el-icon-edit" type="text" @click="onRename(scope.row)">重命名</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="上传文件" :visible.sync="dialogVisible" width="30%">
      <el-upload
        drag
        name="binfile"
        :headers="uploadHeaders"
        :data="uploadData"
        :before-upload="onBeforeUpload"
        :on-success="onUploadSuccess"
        :action="`${window.location.protocol}//${window.location.host}/api/v1/evm_store/netdisc/add`"
        multiple
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">文件不超过100mb</div>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
import { download } from "@/utils/index";
import elTableInfiniteScroll from "el-table-infinite-scroll";
import { getFileList, addFile, updateFile, deleteFile } from "@/api/index";

export default {
  name: "Files",
  directives: {
    "el-table-infinite-scroll": elTableInfiniteScroll,
  },
  data() {
    return {
      loading: false,
      tableData: [],
      dialogVisible: false,
      selectList: [],
      currentDirList: [],
      currentDir: "/",
      uploadData: {
        parent_dir: "/",
        file_type: "",
      },
      uploadHeaders: {
        Authorization: this.$store.getters.token,
      },
      urlRoot: "",
    };
  },
  watch: {
    $route: "onRouteChange",
  },
  computed: {
    window: () => window,
  },
  methods: {
    getAllFiles() {
      this.currentDir = "/";
      this.currentDirList = [];
      this.getFileList();
    },
    onSelectionChange(selection) {
      this.selectList = selection;
    },
    onScrollEnd() {
      //   if (this.total != 0 && this.rows.length == this.total) {
      //     console.log("no more");
      //     return;
      //   }
      //   this.getFileList(this.offset, this.limit);
      console.log("to do nothing");
    },
    onSelectable(row) {
      if (row.is_dir !== 1) return true;
    },
    onRename(row) {
        console.log(row)
      this.$prompt("请输入名称", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: !/(\\|:)+/g,
        inputErrorMessage: "文件夹格式不正确",
      })
        .then(({ value }) => {
          this.updateFile(row.uuid, { name: value });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消动作",
          });
        });
    },
    removeFiles() {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
            this.deleteFile()
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    onRouteChange(newVal) {
      if (this.currentDir != newVal.query.dir) {
        this.currentDir = newVal.query.dir; // change the current direction when the route changed
      }

      this.getFileList();
    },
    isOfficeFile(type) {
      let officeTypes = [
        "application/msword",
        "application/vnd.ms-excel",
        "application/vnd.ms-powerpoint",
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "application/vnd.openxmlformats-officedocument.presentationml.presentation",
      ];
      return officeTypes.includes(type);
    },
    officeIcon(type) {
      let docTypes = [
        "application/msword",
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      ];
      let excelTypes = [
        "application/vnd.ms-excel",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      ];
      let pptTypes = [
        "application/vnd.ms-powerpoint",
        "application/vnd.openxmlformats-officedocument.presentationml.presentation",
      ];
      if (docTypes.includes(type)) {
        return "icon-doc";
      } else if (excelTypes.includes(type)) {
        return "icon-excel";
      } else if (pptTypes.includes(type)) {
        return "icon-ppt";
      }
    },
    type2icon(type) {
      let [t1, t2] = type.split("/");
      let mt = ["pdf", "html", "xml", "psd", "rtf"];
      if (mt.includes(t2)) {
        return `icon-${t2}`;
      }

      let codeTypes = ["json", "yaml", "x-yaml"];
      if (codeTypes.includes(t2)) {
        return "icon-html";
      }

      let compressedFileTypes = ["zip", "x-gzip", "tar", "gz", "rar"];
      if (compressedFileTypes.includes(t2)) {
        return "icon-compressed-file";
      }

      if (this.isOfficeFile(type)) {
        return this.officeIcon(type);
      }

      let gt = ["audio", "video", "image", "text"];
      if (gt.includes(t1)) {
        return `icon-${t1}`;
      }

      return "icon-file";
    },
    buildQuery(dir) {
      if (dir.startsWith(this.rootDir)) {
        dir = dir.replace(this.rootDir, "");
      }

      let query = !dir ? {} : { dir: dir };
      return { query: query };
    },
    onNameClick(item) {
      if (item.is_dir == 1) {
        this.currentDirList.push(item.name);
        this.currentDir = "/" + this.currentDirList.join("/");
        this.getFileList();
        return;
      }
      download(item.name, this.urlRoot + item.real_path);
    },
    convert(limit) {
      var size = "";
      if (limit < 0.1 * 1024) {
        //如果小于0.1KB转化成B
        size = limit.toFixed(2) + "B";
      } else if (limit < 0.1 * 1024 * 1024) {
        //如果小于0.1MB转化成KB
        size = (limit / 1024).toFixed(2) + "KB";
      } else if (limit < 0.1 * 1024 * 1024 * 1024) {
        //如果小于0.1GB转化成MB
        size = (limit / (1024 * 1024)).toFixed(2) + "MB";
      } else {
        //其他转化成GB
        size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";
      }

      var sizestr = size + "";
      var len = sizestr.indexOf(".");
      var dec = sizestr.substr(len + 1, 2);
      if (dec == "00") {
        //当小数点后为00时 去掉小数部分
        return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
      }
      return sizestr;
    },
    createFolder() {
      this.$prompt("请输入文件夹名称", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: !/(\\|:)+/g,
        inputErrorMessage: "文件夹格式不正确",
      })
        .then(({ value }) => {
          this.addFile(value);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消动作",
          });
        });
    },
    onBeforeUpload(file) {
      this.uploadData.file_type = file.type;
    },
    onUploadSuccess() {
      this.getFileList();
    },
    viewFiles(dir, idx) {
      let t = this.currentDirList.slice(0, idx).join("/");
      this.currentDirList = this.currentDirList.slice(0, idx + 1);
      if (t.startsWith("/")) this.currentDir = t + "/" + dir;
      else if (t.length) this.currentDir = "/" + t + "/" + dir;
      else this.currentDir = "/" + dir;
      this.getFileList();
    },
    getFileList() {
      this.loading = true;
      getFileList({ parent_dir: this.currentDir })
        .then((res) => {
          this.tableData = res.data.map((item) => {
            item.size = this.convert(item.size);
            item.icon = this.type2icon(item.file_type);
            return item;
          });
          this.urlRoot = res.url;
        })
        .catch((err) => {
          this.tableData = [];
          console.log(err);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    addFile(name) {
      addFile({ name: name, parent_dir: this.currentDir })
        .then((res) => {
          this.$message.success(res.message);
          this.getFileList();
        })
        .catch((err) => {
          this.$message.error(err.message);
        });
    },
    updateFile(id, params) {
      updateFile(id, params)
        .then((res) => {
          this.$message.success(res.message);
          this.getFileList();
        })
        .catch((err) => {
          this.$message.error(err.message);
        });
    },
    deleteFile() {
      deleteFile({ uuids: this.selectList.map(item => item.uuid) })
        .then((res) => {
          this.$message.success(res.message);
          this.getFileList();
        })
        .catch((err) => {
          this.$message.error(err.message);
        });
    },
  },
  mounted() {},
  created() {
    this.getFileList();
  },
};
</script>
