<template>
  <div class="f_box">
    <div class="f_box_top">
      <div class="f_box_top_left">
        <div class="f_box_top_title">
          所有文件夹
        </div>
      </div>
      <div class="f_box_top_right">
        <div class="btn" @click="openAdd">
          新建文件夹
        </div>
        <div class="btn delBtn" @click="deleteFolder">
          删除
        </div>
      </div>
    </div>
    <div class="f_box_top">
      <div class="f_box_top_left">
        <el-select
          style="margin-right: 10px; width: 100px;"
          v-loading="tagLoading1"
          v-model="check1"
          placeholder="学科"
          clearable
          filterable
          collapse-tags
          @change="serchFile()"
        >
          <el-option
            v-for="(item, index) in tagData1"
            :key="index"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
        <el-select
          style="width: 100px;"
          v-loading="tagLoading2"
          v-model="check2"
          placeholder="年级"
          clearable
          filterable
          @change="serchFile()"
        >
          <el-option
            v-for="(item, index) in tagData2"
            :key="index"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </div>
      <div class="f_box_top_right">
        <div class="input">
          <input
            type="text"
            v-model="fileName"
            placeholder="请输入你需要搜索的文件夹名字"
            @input="debouncedSearch"
          />
          <div class="serch"></div>
        </div>
      </div>
    </div>
    <div class="none_box" v-if="fileArray.length == 0">
      暂无文件夹
    </div>
    <div
      class="f_box_file_list"
      v-else-if="stype == '2' && fileArray.length"
      v-loading.body="isLoading"
    >
      <div class="list_file_box">
        <el-table
          ref="myTable"
          :data="fileArray"
          border
          stripe
          style="width: 100%"
          @selection-change="handleSelectionChange"
          :row-key="row => row.id"
        >
          <el-table-column
            type="selection"
            width="50px"
            :reserve-selection="true"
            :selectable="isSelectable"
          ></el-table-column>
          <el-table-column
            prop="name"
            label="文件夹名字"
            show-overflow-tooltip
            min-width="15"
          ></el-table-column>
          <el-table-column
            prop="detail"
            label="描述"
            show-overflow-tooltip
            min-width="20"
          ></el-table-column>
          <el-table-column
            prop="fileCount"
            label="文件数"
            width="80px"
          ></el-table-column>
          <el-table-column
            prop="username"
            label="拥有者"
            show-overflow-tooltip
            min-width="10"
          ></el-table-column>
          <el-table-column label="标签" show-overflow-tooltip min-width="10">
            <template slot-scope="scope">
              {{ getTag(scope.row) }}
            </template>
          </el-table-column>
          <el-table-column label="公开权限" width="80px">
            <template slot-scope="scope">
              {{ getJuri(scope.row.juri) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="time"
            label="编辑时间"
            min-width="15"
          ></el-table-column>
          <el-table-column label="操作" width="200px">
            <template slot-scope="scope">
              <div>
                <el-button
                  @click="editFile(scope.row.id, scope.row.folderid)"
                  type="primary"
                  size="small"
                  >查看</el-button
                >
                <el-button
                  @click="deleteFile(scope.row.id, scope.row.folderid)"
                  type="danger"
                  size="small"
                  v-if="scope.row.userid == userid && scope.row.isMo == '2'"
                  >删除</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        style="margin-top: 10px;"
        background
        layout="prev, pager, next"
        :page-size="10"
        :total="total"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
    <el-dialog
      title="新建文件夹"
      :visible.sync="moveBox"
      width="550px"
      @close="moveBox = false"
      class="dialog"
    >
      <div>
        <el-input
          v-model="folderName"
          placeholder="请输入知识库名称"
        ></el-input>
        <el-input
          v-model="folderDescription"
          type="textarea"
          rows="4"
          resize="none"
          placeholder="请输入知识库描述"
          style="margin-top: 10px;"
        ></el-input>
      </div>
      <span slot="footer">
        <el-button @click="moveBox = false">取 消</el-button>
        <el-button type="primary" @click="createFolder(2)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import officeImg from "../../../assets/icon/sourceFile/office.png";
import pdfImg from "../../../assets/icon/sourceFile/pdf.png";
import videoImg from "../../../assets/icon/sourceFile/video.png";
import otherImg from "../../../assets/icon/sourceFile/other.png";
import checkImg from "../../../assets/icon/sourceFile/check.png";
import checkIsImg from "../../../assets/icon/sourceFile/check_is.png";

import wVideo from "../test/file/wVideo.vue";
import wpdf from "../test/file/wPdf2.vue";
import wOffice from "../test/file/wOffice.vue";

import JSZip from "jszip";
import FileSaver from "file-saver";

const getFile = url => {
  return new Promise((resolve, reject) => {
    var credentials = {
      accessKeyId: "AKIATLPEDU37QV5CHLMH",
      secretAccessKey: "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"
    }; //秘钥形式的登录上传
    window.AWS.config.update(credentials);
    window.AWS.config.region = "cn-northwest-1"; //设置区域
    let url2 = url;
    let _url2 = "";
    if (
      url2.indexOf("https://view.officeapps.live.com/op/view.aspx?src=") != -1
    ) {
      _url2 = url2.split(
        "https://view.officeapps.live.com/op/view.aspx?src="
      )[1];
    } else {
      _url2 = url2;
    }
    var s3 = new window.AWS.S3({ params: { Bucket: "ccrb" } });
    let name = decodeURIComponent(
      _url2
        .split("https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/")[1]
        .replace(/\+/g, " ")
    );
    var params = {
      Bucket: "ccrb",
      Key: name
    };
    s3.getObject(params, function(err, data) {
      if (err) {
        console.log(err, err.stack);
        resolve({ data: 1 });
      } else {
        resolve({ data: data.Body });
        console.log(data);
      } // sxuccessful response
    });
    // axios({
  });
};
export default {
  components: {
    wVideo,
    wpdf,
    wOffice
  },
  props: {
    userid: {
      type: String
    },
    typeArray: {
      type: Array
    },
    pid: {
      type: String
    },
    type: {
      type: String
    }
  },
  watch: {
    pid: {
      immediate: true,
      deep: true,
      handler(newValue, oldValue) {
        this.fileArray = [];
        this.checkArray = [];
        this.fileName = "";
        this.page = 1;
        this.getData();
        this.getTagArray(1);
        this.getTagArray(2);
      }
    }
  },
  data() {
    return {
      isLoading: false,
      proVisible: false,
      stype: 2,
      fileArray: [],
      officeImg: officeImg,
      pdfImg: pdfImg,
      videoImg: videoImg,
      otherImg: otherImg,
      checkImg: checkImg,
      checkIsImg: checkIsImg,
      checkArray: [],
      checkArray2: [],
      dialogVisiblePdf: false,
      dialogVisibleVideo: false,
      dialogVisibleOffice: false,
      wurl: "",
      moveBox: false,
      checkTypeArray: [],
      moveChild: "",
      fileName: "",
      folderName: "",
      folderDescription: "",
      page: 1,
      total: 0,
      tagLoading1: false,
      tagLoading2: false,
      tagData1: [],
      tagData2: [],
      check1: [],
      check2: []
    };
  },
  computed: {
    retrunType() {
      return function(item) {
        if (item.type == 1) {
          return "OFFICE文件";
        } else if (item.type == 2) {
          return "视频文件";
        } else if (item.type == 3) {
          return "图片";
        } else if (item.type == 4) {
          return "PDF文件";
        } else if (item.type == 5) {
          return "其他文件";
        }
      };
    },
    getJuri() {
      return function(juri) {
        if (juri == 1) {
          return "私有";
        } else if (juri == 2) {
          return "组织内";
        } else if (juri == 3) {
          return "全部";
        }
      };
    },
    getTag() {
      return function(row) {
        const tags = [row.classTagName, row.subTagName, row.tag]
          .filter(tag => tag) // 过滤掉空值
          .flatMap(tag => tag.split(",")); // 展开并分割
        return tags.length ? tags.join(",") : "-";
      };
    }
  },
  methods: {
    getTagArray(type) {
      const tagLoadings = [
        this.tagLoading1,
        this.tagLoading2,
        this.tagLoading3
      ];
      tagLoadings[type - 1] = true;

      let params = {
        type: type,
        uid: this.userid
      };
      this.ajax
        .post(this.$store.state.api + "getKnowledgeTag", [params])
        .then(res => {
          tagLoadings[type - 1] = false;
          this[`tagData${type}`] = res.data[0];
          const checkKey = `check${type}`;
          // this[checkKey] = this[checkKey].filter(tag =>
          //   this[`tagData${type}`].some(item => item.id === tag)
          // );
        })
        .catch(err => {
          tagLoadings[type - 1] = false;
          console.error(err);
        });
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getData();
    },
    getData() {
      let type = this.pid.split("/");
      let id = "";
      if (type[0] == "0") {
        id = this.userid;
      }
      this.isLoading = true;
      let params = {
        uid: id,
        sub: this.check1,
        class: this.check2,
        page: this.page,
        num: 10
      };
      this.ajax
        .post(this.$store.state.api + "getFolderPage", [params])
        .then(res => {
          this.isLoading = false;
          this.total = res.data[0].length ? res.data[0][0].num : 0;
          this.fileArray = res.data[0];
          if (
            res.data[0].length == 0 &&
            this.check1 == "" &&
            this.check2 == ""
          ) {
            this.folderName = "默认文件夹";
            this.folderDescription = "默认文件夹";
            this.createFolder(1);
          }
          this.$parent.getData();
          this.$forceUpdate();
        })
        .catch(err => {
          this.isLoading = false;
          console.error(err);
        });
    },
    debouncedSearch() {
      clearTimeout(this.debounceTimeout);
      this.debounceTimeout = setTimeout(() => {
        this.serchFile();
      }, 300);
    },
    serchFile() {
      this.page = 1;
      this.getData();
    },
    handleSelectionChange(selectedRows) {
      this.checkArray = selectedRows.map(row => row.id);
      this.checkArray2 = selectedRows.map(row => ({
        id: row.id,
        folderid: row.folderid
      }));
    },
    deleteFile(id, folderid) {
      this.$confirm("确定删除文件夹吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let params = [{ ids: id, folderids: folderid }];
          this.ajax
            .post(this.$store.state.fileApi + "deleteFolder", params)
            .then(res => {
              this.$message({
                message: "删除成功",
                type: "success"
              });
              this.checkArray = [];
              this.checkArray2 = [];
              this.$refs.myTable.clearSelection();
              this.getData();
            })
            .catch(err => {
              this.$message.error("删除失败");
              console.error(err);
            });
        })
        .catch(() => {});
    },
    deleteFolder() {
      if (!this.checkArray.length) {
        this.$message.warning("请选择要删除的文件夹");
        return;
      }
      let array = this.checkArray2.map(item => item.id);
      let array2 = this.checkArray2.map(item => item.folderid);
      this.deleteFile(array.join(","), array2.join(","));
    },
    checkMoveChild(item) {
      this.moveChild = item;
    },
    openAdd() {
      this.folderName = "";
      this.folderDescription = "";
      this.moveBox = true;
    },
    createFolder(im) {
      if (!this.folderName) {
        this.$message.error("文件夹名字必填");
        return;
      }
      let params = [
        {
          n: this.folderName,
          fd: this.folderDescription,
          uid: this.userid,
          im: im ? im : 2
        }
      ];
      this.ajax
        .post(this.$store.state.fileApi + "addFolder", params)
        .then(res => {
          this.$message({
            message: "创建成功",
            type: "success"
          });
          this.moveBox = false;
          this.getData();
        })
        .catch(err => {
          this.$message.error("删除失败");
          console.error(err);
        });
    },
    editFile(id, folderid) {
      console.log(id);

      let array = [this.pid.split("/")[0], id];
      this.$emit("checkType", array.join("/"), folderid);
    },
    isSelectable(row) {
      return row.isMo == "2";
    }
  },
  mounted() {
    // this.getData();
  }
};
</script>

<style scoped>
.f_box {
  width: 100%;
  /* height: 100%; */
  position: relative;
}

.f_box_top {
  display: flex;
  align-items: center;
  padding: 10px;
  width: 100%;
  box-sizing: border-box;
}

.f_box_top_left {
  display: flex;
  align-items: center;
}

.f_box_top_title {
  font-size: 16px;
  /* font-weight: bold; */
}

.f_box_top .btn {
  display: flex;
  cursor: pointer;
  align-items: center;
  height: 30px;
  padding: 0 8px;
  background: rgb(0, 97, 255);
  color: #fff;
  box-sizing: border-box;
  border-radius: 4px;
  font-size: 14px;
  align-items: center;
}

.f_box_top .btn2 {
  display: flex;
  cursor: pointer;
  align-items: center;
  height: 30px;
  padding: 0 8px;
  background: #fff;
  color: rgb(0, 97, 255);
  border: 1px solid rgb(0, 97, 255);
  box-sizing: border-box;
  border-radius: 4px;
  font-size: 14px;
  align-items: center;
}

.f_box_top .delBtn {
  background: rgb(255, 0, 13);
}

.f_box_top .btn + .btn2,
.f_box_top .btn + .btn,
.f_box_top .btn2 + .btn2,
.f_box_top .btn2 + .delBtn {
  margin-left: 15px;
}

.f_box_top_right {
  margin-left: auto;
  max-width: calc(100% - 280px);
  overflow: hidden;
  display: flex;
  align-items: center;
}

.f_box_top_right > .input {
  position: relative;
  width: 250px;
  height: 35px;
}

.f_box_top_right > .input > input {
  width: 100%;
  height: 100%;
  border: 1px solid #d9d9d9;
  border-radius: 5px;
  padding: 0 45px 0 10px;
  box-sizing: border-box;
  font-size: 12px;
  outline: none;
}

.f_box_top_right > .input > .serch {
  content: "";
  display: block;
  width: 20px;
  height: 20px;
  background-image: url("../../../assets/icon/sourceFile/search.png");
  background-size: 100% 100%;
  position: absolute;
  right: 13px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
}

.f_box_top_right > .tab {
  height: 30px;
  width: 80px;
  margin-left: 15px;
  background: #e7e7e7;
  border: 2px solid #d9d9d9;
  border-radius: 5px;
  box-sizing: border-box;
  overflow: hidden;
  display: flex;
  align-items: center;
}

.f_box_top_right > .tab > .table,
.f_box_top_right > .tab > .list {
  width: 50%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.f_box_top_right > .tab > .list::before {
  content: "";
  display: block;
  width: 20px;
  height: 20px;
  background-image: url("../../../assets/icon/sourceFile/list.png");
  background-size: 100% 100%;
}

.f_box_top_right > .tab > .list.active,
.f_box_top_right > .tab > .table.active {
  background: #fff;
}

.f_box_top_right > .tab > .table::before {
  content: "";
  display: block;
  width: 20px;
  height: 20px;
  background-image: url("../../../assets/icon/sourceFile/table.png");
  background-size: 100% 100%;
}

.mask {
  background-color: rgb(0 0 0 / 30%);
  /* position: fixed; */
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 90;
  display: flex;
  align-items: center;
  justify-content: center;
}

.progressBox {
  width: 300px;
  height: 150px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 0 6px 1px #bfbfbf;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  position: relative;
  color: #6c6c6c;
}

.progressBox >>> .el-progress-bar__outer {
  background-color: #d1dfff !important;
}

.progressBox .lbox {
  height: 50px;
  font-size: 19px;
  display: flex;
  align-items: center;
  color: #747474;
}

.progressBox .lbox img {
  width: 40px;
  margin-right: 20px;
}

.closeCss {
  position: absolute;
  top: 8px;
  right: 8px;
  cursor: pointer;
  width: 20px;
  height: 20px;
}

.closeCss > img {
  width: 100%;
  height: 100%;
}

.f_box_file_square {
  height: calc(100% - 55px);
  overflow: auto;
  width: 100%;
  padding: 55px;
  box-sizing: border-box;
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
  position: relative;
}

.f_box_file_square > .f_box_file {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 160px;
  height: 160px;
  cursor: pointer;
  margin: 0 36px 36px 0;
  border-radius: 20px;
  position: relative;
}

.f_box_file_square > .f_box_file:hover {
  background: #f0f2f5;
}

.f_box_file_square > .f_box_file:hover > .check {
  display: block;
}

.f_box_file_square > .f_box_file.check {
  background: #e0eafb;
}

.f_box_file_square > .f_box_file.check > .check {
  display: block;
}

.f_box_file_square > .f_box_file > .check {
  position: absolute;
  left: 15px;
  top: 15px;
  width: 16px;
  height: 16px;
  background-size: 100%;
  display: none;
}

.f_box_file_square > .f_box_file > .check > img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.f_box_file_square > .f_box_file > img {
  width: 90px;
  height: 90px;
  object-fit: cover;
}

.f_box_file_square > .f_box_file > .name {
  white-space: nowrap;
  font-size: 14px;
  max-width: 80%;
  overflow: hidden;
  margin: 4px auto 0;
  text-overflow: ellipsis;
  text-align: center;
}

.f_box_file_list {
  /* height: calc(100% - 55px); */
  /* overflow: auto; */
  width: 100%;
  padding: 10px;
  box-sizing: border-box;
}

.f_box_file_list > .f_box_file {
}

.f_box_file_allCheck {
  display: flex;
  align-items: center;
  position: absolute;
  font-size: 14px;
  top: 20px;
  left: 10px;
  cursor: pointer;
}

.f_box_file_allCheck > img {
  width: 16px;
  height: 16px;
  object-fit: cover;
  margin-right: 5px;
}

.dialog >>> .el-dialog__body {
  padding: 10px 20px;
}

.type_nav_box {
}

.type_nav_box > .nav {
  height: 40px;
  border-radius: 5px;
  cursor: pointer;
  display: flex;
  align-items: center;
  width: 100%;
  padding: 0 10px;
  box-sizing: border-box;
  margin-bottom: 10px;
  font-size: 16px;
  color: #000;
}

.type_nav_box > .nav > .down {
  min-width: 14px;
  height: 14px;
  background-image: url("../../../assets/icon/sourceFile/icon_arrow.png");
  background-size: 100% 100%;
  margin-right: 10px;
  transition: all 0.3s;
  transform: rotate(-90deg);
}

.type_nav_box > .nav.active > .down {
  transform: rotate(0deg);
}

.type_nav_box > .nav > .file {
  min-width: 18px;
  height: 18px;
  background-image: url("../../../assets/icon/sourceFile/file.png");
  background-size: 100% 100%;
  margin-right: 10px;
}

.type_nav_box > .nav > .name {
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.type_nav_box > .child {
}

.type_nav_box > .child > .nav {
  height: 40px;
  border-radius: 5px;
  cursor: pointer;
  display: flex;
  align-items: center;
  width: 100%;
  padding: 0 10px 0 50px;
  box-sizing: border-box;
  margin-bottom: 10px;
  font-size: 16px;
  color: #000;
}

.type_nav_box > .child > .nav.active {
  background: #e0eafb;
}

.type_nav_box > .child > .nav > .file {
  min-width: 18px;
  height: 18px;
  background-image: url("../../../assets/icon/sourceFile/file.png");
  background-size: 100% 100%;
  margin-right: 10px;
}

.type_nav_box > .child > .nav > .name {
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.none_box {
  height: calc(100% - 55px);
  overflow: auto;
  width: 100%;
  padding: 10px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
}

.list_file_box {
  width: 100%;
}
</style>
