<template>
  <div class="app-container">
    <!-- 新增编辑文件夹窗口 -->
    <el-dialog
      title="文件夹"
      :visible.sync="folderModal"
      :close-on-click-modal="false"
      width="500px"
    >
      <el-form
        ref="folderForm"
        label-width="120px"
        :model="folderForm"
        :rules="folderRules"
      >
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="folderForm.name"
            size="small"
            clearable
            placeholder="请输入名称"
            style="width: 200px"
            class="filter-item"
          />
        </el-form-item>
        <el-form-item label="顺序" prop="order" v-if="!folderForm.id">
          <el-input
            v-model="folderForm.order"
            size="small"
            clearable
            placeholder="请输入顺序"
            style="width: 200px"
            class="filter-item"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="folderModal = false">取消</el-button>
        <el-button type="primary" @click="confirmFolder" :loading="modalBtnLoad"
          >确定</el-button
        >
      </div>
    </el-dialog>
    <!-- 上传文件窗口 -->
    <el-dialog
      title="文件添加"
      :visible.sync="fileUploadModal"
      :close-on-click-modal="false"
    >
      <el-form ref="formInfo" label-width="120px">
        <el-form-item>
          <el-input
            v-model="fileType"
            size="small"
            clearable
            placeholder="请输入文件分类"
            style="width: 200px"
            class="filter-item"
          />
        </el-form-item>
        <el-form-item>
          <label
            class="import-file-dg"
            style="
              color: #1890ff;
              display: inline-block;
              border: 1px solid #1890ff;
            "
          >
            上传文件
            <input
              :ref="`addhdpic`"
              class="helloworld"
              type="file"
              accept1=".pdf"
              hidden
              @change="addhdPicChange"
            />
            
          </label>
          <!-- <span>仅支持pdf格式文件</span> -->
        </el-form-item>
        <el-form-item label="">
          <div v-for="(item, index) in uploadedFiles" :key="item.name + index">
            {{ item.name }}
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="fileUploadModal = false">取消</el-button>
        <el-button
          type="primary"
          @click="confirmUploadFile"
          :loading="modalBtnLoad"
          >确定</el-button
        >
      </div>
    </el-dialog>
    <el-row :gutter="15">
      <el-col :span="6" style="margin-bottom: 10px">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-button
              v-show="selectedFolderInfo.deleteWhether"
              size="mini"
              style="float: right; margin-left: 6px"
              type="danger"
              @click="delFolder"
            >
              删除</el-button
            >
            <el-button
              v-show="selectedFolderInfo.editWhether"
              size="mini"
              style="float: right"
              type="primary"
              @click="updateFolder"
            >
              修改</el-button
            >
            <el-button
              size="mini"
              style="float: right"
              type="primary"
              @click="addFolder"
            >
              添加</el-button
            >
          </div>
          <el-tree
            ref="menu"
            :data="menus"
            :props="defaultProps"
            check-strictly
            accordion
            show-checkbox1
            node-key="id"
            check="menuCheck"
            @node-click="menuClick"
          />
        </el-card>
      </el-col>

      <!--角色管理-->
      <el-col :span="16">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-button
              v-show="selectedFolderInfo.uploadWhether"
              type="primary"
              size="mini"
              @click="fileUploadModal = true"
              >上传文件</el-button
            >
            <el-input
              v-model="query.originallyName"
              size="small"
              clearable
              placeholder="查询文件名称"
              style="width: 200px"
              class="filter-item"
            />
            <date-range-picker v-model="query.time" type="datetimerange" class="date-item" />
            <el-input
              v-model="query.classification"
              size="small"
              clearable
              placeholder="查询文件分类"
              style="width: 200px"
              class="filter-item"
            />
            <el-button type="primary" size="mini" @click="search"
              >查询</el-button
            >
          </div>
          <el-table ref="table" style="width: 100%" :data="fileDataList">
            <el-table-column type="" width="55" />
            <el-table-column prop="originallyName" label="文件名称" />
            <el-table-column
              label="文件分类"
              prop="classification"
              width="100"
            />
            <el-table-column width="200px" prop="createTime" label="录入时间" />
            <el-table-column label="操作" width="230px" align="left">
              <template slot-scope="scope">
               
                <el-button
                  v-show="scope.row.downloadWhether"
                  type="primary"
                  size="mini"
                  @click="downFileById(scope.row)"
                  >下载</el-button
                >
                <el-button
                  v-show="scope.row.deleteWhether"
                  type="danger"
                  size="mini"
                  @click="delFileById(scope.row)"
                  >删除</el-button
                >
                <el-button
                  v-show="scope.row.downloadWhether && (scope.row.filePath.indexOf('.pdf')>-1)"
                  type="primary"
                  size="mini"
                  @click="viewFile(scope.row)"

                  >预览</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <el-pagination
            :current-page="page"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalElement"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
  
  <script>
import edocApi from "@/api/kd/edoc";
import DateRangePicker from "@/components/DateRangePicker";
import { getToken } from "@/utils/auth";
import axios from "axios";

export default {
  name: "Folder",
  components: {
    DateRangePicker,
  },
  data() {
    return {
      dialogVisible4:false,
      pdfSrc:'',
      modalBtnLoad: false,
      query: {
        originallyName: "",
        classification: "",
        time: "",
      },
      folderModal: false,
      folderForm: {
        name: "",
        order: 0,
      },
      fileType: "",
      fileUploadModal: false,
      uploadedFiles: [],
      selectedFolderId: "",
      selectedFolderId: "",
      selectedFolderInfo: {},
      fileDataList: [],
      totalElement: 0,
      page: 0,
      size: 10,
      defaultProps: { children: "children", label: "name", isLeaf: "leaf" },
      level: 3,
      currentId: 0,
      currentName: "",
      menuLoading: false,
      showButton: false,
      menus: [],
      menuIds: [],
      folderRules: {
        order: [{ required: true, message: "请输入顺序", trigger: "blur" }],
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
      },
    };
  },
  computed: {},
  mounted() {
    this.getDataList(); // 获取所有文件夹
  },
  created() {},
  methods: {
    viewFile(row){
      this.pdfSrc = process.env.VUE_APP_LOCAL_API+'/file'+row.filePath;
      const link = document.createElement('a');
      link.href = this.pdfSrc;
      link.target = '_blank';
      link.click();
    },
    // searchParamReset() {
    //   this.searchParam = {
    //     originallyName: "",
    //     classification: "",
    //     time: "",
    //   }
    //   this.page = 0
    //   this.size = 10
    //   this.getfileByFolderId()
    // },
    // 当前页的条数变化
    handleSizeChange(val) {
      this.size = val;
      this.getfileByFolderId();
    },
    // 当前第几页
    handleCurrentChange(val) {
      this.page = val;
      this.getfileByFolderId();
    },
    getDataList() {
      edocApi.getDataList({}).then((res) => {
        this.menus = res.body;
      });
    },
    confirmFolder() {
      this.$refs["folderForm"].validate((valid) => {
        if (valid) {
          if (this.modalBtnLoad) {
            return;
          }
          this.modalBtnLoad = true;
          if (this.folderForm.id) {
            // 修改
            edocApi
              .updateFolder({
                ...this.folderForm,
              })
              .then((res) => {
                this.folderModal = false;
                this.$message.success("操作成功");
                this.getDataList();
              });
          } else {
            // 新增
            edocApi
              .addFolder({
                ...this.folderForm,
                pid: this.selectedFolderId,
              })
              .then((res) => {
                this.folderModal = false;
                this.$message.success("操作成功");
                this.getDataList();
              });
          }
          this.modalBtnLoad = false;
        }
      });
    },

    addFolder() {
      // if (!this.selectedFolderId) {
      //   this.$message.warning("请选择文件夹");
      //   return;
      // }
      this.folderModal = true;
      this.folderForm = { name: "", order: "" };
    },
    delFolder() {
      if (!this.selectedFolderId) {
        this.$message.warning("请选择要操作的文件夹");
        return;
      }
      this.$confirm("确定要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(
        () => {
          edocApi.delFolder([this.selectedFolderId]).then((res) => {
            this.$message.success("操作成功");
            this.getDataList();
          });
        },
        () => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        }
      );
    },
    downFileById(row) {
      if (this.isExportLoading) {
        return;
      }
      this.isExportLoading = true;
      // 导出信息
      axios.defaults.headers.common["Authorization"] = getToken();
      const apiUrl = (
        process.env.VUE_APP_LOCAL_API + "/api/document/download"
      ).replaceAll("'", "");
      axios.interceptors.response.use(
        function (response) {
          // 对响应数据做点什么
          console.log("响应头", response);

          return response;
        },
        function (error) {
          // 对响应错误做点什么
          return Promise.reject(error);
        }
      );
      axios({
        url: apiUrl,
        responseType: "blob",
        method: "get",
        params: { id: row.id },
      }).then((res) => {
        console.log("export", res.headers["content-disposition"]);
        let data = res.data;
        let url = URL.createObjectURL(data);
        let dis = res.headers["content-disposition"];
        let fileName = dis.split("filename=")[1];
        this.down(url, fileName);
        this.isExportLoading = false;
      });
    },
    down(fileUrl, fileName) {
      // 下载模板
      fileName = decodeURIComponent(fileName);
      let a = document.createElement("a");
      a.setAttribute("href", fileUrl);
      a.setAttribute("download", fileName);
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    },
    delFileById(row) {
      this.$confirm("确定要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(
        () => {
          edocApi.delFileById([row.id]).then((res) => {
            this.$message.success("操作成功");
            this.getfileByFolderId(this.selectedFolderId);
          });
        },
        () => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        }
      );
    },
    updateFolder() {
      if (!this.selectedFolderId) {
        this.$message.warning("请选择文件夹");
        return;
      }
      this.folderModal = true;
      this.folderForm.name = this.selectedFolderInfo.name;
      this.folderForm.order = this.selectedFolderInfo.order;
      this.folderForm.id = this.selectedFolderInfo.id;
    },
    search() {
      this.getfileByFolderId();
    },
    getfileByFolderId() {
      edocApi
        .getfileByFolderId({
          catalogueId: this.selectedFolderId,
          page: this.page,
          size: this.size,
          ...this.query,
          time: this.query.time ? this.query.time.join(",") : "",
        })
        .then((res) => {
          this.fileDataList = res.body.results;
          this.totalElement = res.body.total;
        });
    },
    confirmUploadFile() {
      if (!this.selectedFolderId) {
        this.$message.warning("请选择文件夹");
        return;
      }
      if (!this.uploadedFiles.length) {
        this.$message.warning("请上传文件");
        return;
      }
      if (this.modalBtnLoad) {
        return;
      }
      this.modalBtnLoad = true;
      const formData = new FormData();
      // console.log(this.formInfo.hdstatus1, "haStatus");
      formData.append("fileList", this.uploadedFiles[0]);
      formData.append("catalogueId", this.selectedFolderId);
      formData.append("classification", this.fileType);

      edocApi.addFileByFolderId(formData).then((res) => {
        this.$message.success("操作成功");
        this.getfileByFolderId();
        this.fileUploadModal = false;
      });
      this.modalBtnLoad = false;
    },
    addhdPicChange(event) {
      // event.target 是触发事件的 input 元素
      const files = event.target.files; // 获取用户选择的文件列表

      // 检查是否有文件选择
      if (files.length > 0) {
        const file = files[0]; // 选择第一个文件
        console.log(`文件名: ${file.name}`);
        console.log(`文件大小: ${file.size} bytes`);
        console.log(`文件类型: ${file.type}`);
      }
      this.uploadedFiles = [files[0]];
    },
    menuClick(data, node, target) {
      console.log("menuClick", data, node, target);
      // 传递文件夹ID，获取对应文件夹下的文件数据
      this.selectedFolderId = data.id;
      // 下方著用于添加目录操作
      this.selectedFolderInfo = data;
      // this.selectedFolderId = data.id;
      this.getfileByFolderId();
    },
    // menuCheck(data, node, target) {
    //   console.log("menuCheck处理前", data, node, target);
    //   if(node.checkedKeys.length>1){
    //     const tempCheckey = node.checkedKeys[node.checkedKeys.length-1]
    //     this.$refs.menu.setCheckedKeys([tempCheckey]);

    //     // node.checkedKeys.splice(0, 1)
    //   console.log("menuCheck处理后", data, node, target);

    //   }
    //   this.selectedFolderInfo = node.checkedKeys.length ? data : {} // 勾选上则赋值当先选中节点。否则位空对象
    //   const menu = data;
    //   this.selectedFolderId = node.checkedKeys.length
    //     ? node.checkedKeys[0]
    //     : "";
    // },
  },
};
</script>
  
  <style rel="stylesheet/scss" lang="scss">
.role-span {
  font-weight: bold;
  color: #303133;
  font-size: 15px;
}
</style>
  
  <style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}
::v-deep .vue-treeselect__multi-value {
  margin-bottom: 0;
}
::v-deep .vue-treeselect__multi-value-item {
  border: 0;
  padding: 0;
}
</style>
  