<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">
          <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">确定</el-button>
      </div>
    </el-dialog>

    <el-row :gutter="15">
      <!-- 用户列表 -->
      <el-col :span="10">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-input v-model="query.blurry" size="small" clearable placeholder="公司名称" style="width: 200px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
            <el-input v-model="query.blurry" size="small" clearable placeholder="用户名称" style="width: 200px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
            <el-button  type="primary" size="mini">查询</el-button>
          </div>
          <el-table ref="table" style="width: 100%" :data="fileDataList">
            <el-table-column
              prop="originallyName"
              label="企业公司"
              align="center"
            />
            <el-table-column
              prop="originallyName"
              label="用户名"
              align="center"
            />
          </el-table>
          <!--分页组件-->
          <el-pagination
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="currenetPageDegree"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalElement"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-card>
      </el-col>
      <!-- 文件夹授权 -->
      <el-col :span="12" style="margin-bottom: 10px">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-button type="primary" @click="saveMenu">保存</el-button>
          </div>
          <el-tree
            ref="menu"
            :data="menus"
            :props="defaultProps"
            check-strictly
            accordion
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
          >
            <div class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ node.label }}</span>
              <el-button
                :type="`${data.editWhether ? 'primary' : 'default'}`"
                icon="el-icon-edit"
                circle
                size="mini"
                style="margin-left: 40px"
                @click="data.editWhether = true"
              ></el-button>
              <el-button
                :type="`${data.deleteWhether ? 'primary' : 'default'}`"
                icon="el-icon-delete"
                circle
                size="mini"
                @click="data.deleteWhether = true"
              ></el-button>
              <el-button
                :type="`${data.uploadWhether ? 'primary' : 'default'}`"
                icon="el-icon-upload2"
                circle
                size="mini"
                @click="data.uploadWhether = true"
              ></el-button>
              <el-button
                :type="`${data.downloadWhether ? 'primary' : 'default'}`"
                icon="el-icon-download"
                circle
                size="mini"
                @click="data.downloadWhether = true"
              ></el-button>

              <!-- <span>
                
                <el-checkbox v-model="checked" >上传</el-checkbox>
                <el-checkbox v-model="checked">修改</el-checkbox>
                <el-checkbox v-model="checked">删除</el-checkbox>
                <el-checkbox v-model="checked">下载</el-checkbox>
                
              </span> -->
            </div>
          </el-tree>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
  
  <script>
import crudRoles from "@/api/system/role";
// import edoc{ getfileByFolderId, getFolderList, addFileByFolderId, delfileById } from '@/api/kd/edoc'
import edocApi from "@/api/kd/edoc";

import { getMenusTree, getChild } from "@/api/system/menu";
import CRUD, { presenter, header, form, crud } from "@crud/crud";
import rrOperation from "@crud/RR.operation";
import crudOperation from "@crud/CRUD.operation";
import udOperation from "@crud/UD.operation";
import pagination from "@crud/Pagination";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { LOAD_CHILDREN_OPTIONS } from "@riophae/vue-treeselect";
import DateRangePicker from "@/components/DateRangePicker";
import { mapGetters } from "vuex";
import { getToken } from "@/utils/auth";

const defaultForm = {
  id: null,
  name: null,
  depts: [],
  description: null,
  dataScope: "全部",
  level: 3,
};
export default {
  name: "Folder",
  components: {
    Treeselect,
    pagination,
    crudOperation,
    rrOperation,
    udOperation,
    DateRangePicker,
  },
  cruds() {
    return CRUD({
      title: "角色",
      url: "api/roles",
      sort: "level,asc",
      crudMethod: { ...crudRoles },
    });
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  data() {
    return {
      folderModal: false,
      folderForm: {
        name: "",
        order: 0,
      },
      fileType: "",
      fileUploadModal: false,
      addEnterhdPics: [],
      currentFolderId: "",
      currentCheckedFolderId: "",
      fileDataList: [],
      totalElement: 0,
      currentPage: 0,
      currenetPageDegree: 10,
      dateScopes: ["全部", "本级及以下", "自定义"],
      defaultProps: { children: "children", label: "name", isLeaf: "leaf" },
      level: 3,
      currentId: 0,
      currentName: "",
      menuLoading: false,
      showButton: false,
      menus: [],
      menuIds: [],
      depts: [],
      deptDatas: [], // 多选时使用
      permission: {
        add: ["admin", "roles:add"],
        edit: ["admin", "roles:edit"],
        del: ["admin", "roles:del"],
      },
      folderRules: {
        order: [{ required: true, message: "请输入顺序", trigger: "blur" }],
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
      },
    };
  },
  computed: {},
  mounted() {
    this.getDataList(); // 获取所有文件夹
  },
  created() {
    // crudRoles.getLevel().then(data => {
    //   this.level = data.level
    // })
  },
  methods: {
    // 当前页的条数变化
    handleSizeChange(val) {
      this.currenetPageDegree = val;
      this.getfileByFolderId();
    },
    // 当前第几页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getfileByFolderId();
    },
    getDataList() {
      edocApi.getDataList({}).then((res) => {
        this.menus = res.body;
      });
    },
    confirmFolder() {
      if (!this.currentFolderId) {
        this.$message.warning("请选择文件夹");
        return;
      }
      this.$refs["folderForm"].validate((valid) => {
        if (valid) {
          edocApi
            .addFolder({
              ...this.folderForm,
              pid: this.currentFolderId,
            })
            .then((res) => {
              this.$message.success("操作成功");
              this.getDataList();
            });
        }
      });
    },

    addFolder() {
      this.folderModal = true;
      this.folderForm = { name: "", order: "" };
    },
    delFolder() {
      if (!this.currentCheckedFolderId) {
        this.$message.warning("请勾选要操作的文件夹");
        return;
      }
      this.$confirm("确定要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(
        () => {
          edocApi.delFolder([this.currentCheckedFolderId]).then((res) => {
            this.$message.success("操作成功");
            this.getDataList();
          });
        },
        () => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        }
      );
    },
    downFileById(row) {
      this.isExportLoading = true;
      // 导出信息
      axios.defaults.headers.common["Authorization"] = getToken();
      axios({
        url: process.env.VUE_APP_BASE_API + "/api/thCompany/export",
        responseType: "blob",
        method: "get",
        params: { county: localStorage.getItem("county") },
      }).then((res) => {
        console.log(res, "export");
        let data = res.data;
        let dis = res.headers["content-disposition"];
        let url = URL.createObjectURL(data);
        let fileName = dis.split("attachment;filename*=utf-8''")[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.currentFolderId);
          });
        },
        () => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        }
      );
    },
    updateFolder() {},
    getfileByFolderId() {
      edocApi
        .getfileByFolderId({
          catalogueId: this.currentFolderId,
          page: this.currentPage,
          size: this.currenetPageDegree,
        })
        .then((res) => {
          this.fileDataList = res.body.results;
          this.totalElement = res.body.total;
        });
    },
    confirmUploadFile() {
      if (!this.currentFolderId) {
        this.$message.warning("请选择文件夹");
        return;
      }
      if (!this.addEnterhdPics.length) {
        this.$message.warning("请上传文件");
        return;
      }
      const formData = new FormData();
      // console.log(this.formInfo.hdstatus1, "haStatus");
      formData.append("fileList", this.addEnterhdPics[0]);
      formData.append("catalogueId", this.currentFolderId);
      formData.append("classification", this.fileType);

      edocApi.addFileByFolderId(formData).then((res) => {
        this.$message.success("操作成功");
        this.getfileByFolderId();
        this.fileUploadModal = 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.addEnterhdPics = [files[0]];
    },
    getMenuDatas(node, resolve) {
      setTimeout(() => {
        getMenusTree(node.data.id ? node.data.id : 0).then((res) => {
          if (this.user && this.user.isAdmin) {
            res.forEach((menu) => {
              menu.label =
                (menu.enterpriseType === 0 ? "局）" : "企）") + menu.label;
            });
          }
          resolve(res);
        });
      }, 100);
    },
    // 触发单选
    handleCurrentChange(val) {
      if (val) {
        const _this = this;
        // 清空菜单的选中
        this.$refs.menu.setCheckedKeys([]);
        // 保存当前的角色id
        this.currentId = val.id;
        this.currentName = val.name;
        // 初始化默认选中的key
        this.menuIds = [];
        val.menus.forEach(function (data) {
          _this.menuIds.push(data.id);
        });
        this.showButton = true;
      }
    },
    menuClick(data, node, target) {
      console.log("menuClick", data, node, target);
      // 传递文件夹ID，获取对应文件夹下的文件数据
      this.currentFolderId = data.id;
      this.getfileByFolderId();
    },
    menuChange(data, node, target) {
      console.log("menuChange", data, node, target);
      const menu = data;
      this.currentCheckedFolderId = node.checkedKeys.length
        ? node.checkedKeys[0]
        : "";

      // // 获取该节点的所有子节点，id 包含自身
      // getChild(menu.id).then(childIds => {
      //   // 判断是否在 menuIds 中，如果存在则删除，否则添加
      //   if (this.menuIds.indexOf(menu.id) !== -1) {
      //     for (let i = 0; i < childIds.length; i++) {
      //       const index = this.menuIds.indexOf(childIds[i])
      //       if (index !== -1) {
      //         this.menuIds.splice(index, 1)
      //       }
      //     }
      //   } else {
      //     for (let i = 0; i < childIds.length; i++) {
      //       const index = this.menuIds.indexOf(childIds[i])
      //       if (index === -1) {
      //         this.menuIds.push(childIds[i])
      //       }
      //     }
      //   }
      //   this.$refs.menu.setCheckedKeys(this.menuIds)

      //   /**
      //    * 1 勾选菜单后
      //    *
      //    */

      // })
    },
    // 保存菜单
    saveMenu() {
      this.menuLoading = true;
      const role = { id: this.currentId, menus: [] };
      // 得到已选中的 key 值
      this.menuIds.forEach(function (id) {
        const menu = { id: id };
        role.menus.push(menu);
      });
      crudRoles
        .editMenu(role)
        .then(() => {
          this.crud.notify("保存成功", CRUD.NOTIFICATION_TYPE.SUCCESS);
          this.menuLoading = false;
          this.update();
        })
        .catch((err) => {
          this.menuLoading = false;
          console.log(err.response.data.message);
        });
    },
    // 改变数据
    update() {
      // 无刷新更新 表格数据
      crudRoles.get(this.currentId).then((res) => {
        for (let i = 0; i < this.crud.data.length; i++) {
          if (res.id === this.crud.data[i].id) {
            this.crud.data[i] = res;
            break;
          }
        }
      });
    },
    // 获取部门数据
    getDepts() {
      getDepts({ enabled: true }).then((res) => {
        this.depts = res.content.map(function (obj) {
          if (obj.hasChildren) {
            obj.children = null;
          }
          return obj;
        });
      });
    },
    getSupDepts(depts) {
      const ids = [];
      depts.forEach((dept) => {
        ids.push(dept.id);
      });
      getDeptSuperior(ids).then((res) => {
        const date = res.content;
        this.buildDepts(date);
        this.depts = date;
      });
    },
    buildDepts(depts) {
      depts.forEach((data) => {
        if (data.children) {
          this.buildDepts(data.children);
        }
        if (data.hasChildren && !data.children) {
          data.children = null;
        }
      });
    },
    // 获取弹窗内部门数据
    loadDepts({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        getDepts({ enabled: true, pid: parentNode.id }).then((res) => {
          parentNode.children = res.content.map(function (obj) {
            if (obj.hasChildren) {
              obj.children = null;
            }
            return obj;
          });
          setTimeout(() => {
            callback();
          }, 200);
        });
      }
    },
    // 如果数据权限为自定义则获取部门数据
    changeScope() {
      if (this.form.dataScope === "自定义") {
        this.getDepts();
      }
    },
    checkboxT(row) {
      return row.level >= this.level;
    },
  },
};
</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>
  