<template>
  <div id="wfzywxk">
    <div class="left-div">
      <el-input
        class="public-input"
        placeholder="输入关键字进行过滤"
        suffix-icon="el-icon-search"
        v-model="filterText"
      ></el-input>
      <el-tree
        :data="tree_data"
        node-key="id"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        highlight-current
        :default-expanded-keys="[2]"
        :props="defaultProps"
        ref="tree"
        :current-node-key="2"
        @node-click="handleNodeClick"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span class="first-span" :title="node.label">{{ node.label }}</span>
          <!-- <span class="list-span">
            <el-button
              type="text"
              size="mini"
              @click="() => append(node, data)"
            >
              <i class="el-icon-circle-plus" title="添加子节点"></i>
            </el-button>
            <el-button type="text" size="mini" @click="() => edit(node, data)">
              <i class="el-icon-edit-outline" title="编辑机构"></i>
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="() => remove(node, data)"
            >
              <i class="el-icon-error" title="删除子节点"></i>
            </el-button>
            <!-- <el-button
              class="import"
              type="text"
              size="mini"
              :style="{
                display: getparentNode(node) == 25 ? '' : 'none !important',
              }"
            >
              <i class="el-icon-upload" @click="importExcelData(data)"></i>
            </el-button> -->
          </span> -->
        </span>
      </el-tree>
    </div>
    <div class="right-div">
      <component :is="currentRole" :clientDetails="clientDetails" ref="mychild"/>
    </div>
    <el-dialog title="新增文件夹" :visible.sync="dialogVisible">
      <span class="dialogContent"
        ><span>名称：</span>
        <el-input v-model="name" placeholder="请输入名称"></el-input>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="add_xzzj()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="编辑文件夹" :visible.sync="dialogVisible_edit">
        <span class="dialogContent"><span>名称：</span>
            <el-input v-model="name_edit" placeholder="请输入名称"></el-input>
        </span>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible_edit = false">取 消</el-button>
            <el-button type="primary" @click="edit_xzzj()">确 定</el-button>
        </span>
    </el-dialog>
    <el-dialog class="importData" :title="title" :visible.sync="dialogVisibleImport" id="impor_file">
      <span>
        <el-upload class="upload-demo" action="" :on-change="handleChange" :show-file-list="false" :auto-upload="false">
          <el-button size="small" type="primary" style="margin-bottom:15px;">读取excel文件</el-button>
        </el-upload>
        <el-table :data="tableDataFromExcel" style="width: 100%" height="300px">
          <template v-for="(item,index) in tableDataFromExcelHead">
            <el-table-column :prop="item.column_name" :label="item.column_comment" :key="index"></el-table-column>
          </template>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button @click="handleDelete(scope)" type="primary" icon="el-icon-delete" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisibleImport = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="defineImport">导入</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { get, post, delete_util } from "../../util/http_util";
import XLSX from "xlsx";
import navs from "./wfwxk.vue";
// import navs1 from "./znjsfx.vue";
let id = 1000;
export default {
  components: { navs },
  data() {
    return {
      clientDetails: {},
      currentRole: "navs",
      tree_data: [], //左侧树结构的数据
      dialogVisible: false, //新增子节点弹出框
      dialogVisible_edit:false,
      name_edit:'',
      name: "", //新增子节点的名称
      this_data: "",
      this_node: "",
      filterText: "",
      defaultProps: {
        children: 'children',
        label: 'label'
      },

      dialogVisibleImport: false,
      title: "",
      pickNew: "",
      tableDataFromExcelHead: [],
      tableDataFromExcel: [],
      module_name:'我方资源文档',
    };
  },
  methods: {
    edit(node,data){
        this.name_edit = data.label;
        this.dialogVisible_edit = true;
        this.this_data = data;
        this.this_node = node;
    },
    edit_xzzj(){
        if (this.name_edit.trim() == "") {
            this.$message({
                type: "warning",
                message: "名称不能为空",
            });
            return;
        }
        let paramDatas = {
            id:this.this_data.id,
            label: this.name_edit.trim(),
        };
        post("api/rest/document/updateDocumentTreeItem", paramDatas)
            .then((data) => {
                if (data == 1) {
                    this.$message({
                        type: "success",
                        message: "文件夹编辑成功",
                    });
                    this.dialogVisible_edit = false;
                    this.$refs.mychild.searchs(1);
                    this.query_tree();
                }
            })
            .catch((err) => {
                console.log(err);
            });
    },
    //添加子模块弹出框
    append(node, data) {
      this.name = "";
      this.dialogVisible = true;
      this.this_data = data;
      this.this_node = node;
    },
    //新增文件夹确定按钮
    add_xzzj() {
      if (this.name.trim() == "") {
        this.$message({
          type: "warning",
          message: "名称不能为空",
        });
        return;
      }
      let paramDatas = {
        label: this.name.trim(),
        level: this.this_node.data.level + 1,
        module: this.module_name,
        parentCode: this.this_node.data.code,
        createId:this.$store.state.userInfo.account,
      };
      post("api/rest/document/addDocumentTreeItem", paramDatas)
        .then((data) => {
          if (data == 1) {
            this.$message({
              type: "success",
              message: "文件夹新增成功",
            });
            this.dialogVisible = false;
            this.query_tree();
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //删除子模块
    remove(node, datas) {
      this.$confirm(
        "此操作将永久删除该文件夹以及其下所有文件夹, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          delete_util(
            "api/rest/document/removeDocumentTreeItem/" + node.data.id
          )
            .then((data) => {
              if (data == 1) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                // this.query_tree();
                const parent = node.parent;
                const children = parent.data.children || parent.data;
                const index = children.findIndex(d => d.id === data.id);
                children.splice(index, 1);
                this.$refs.mychild.searchs(1);
              }
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //查询tree数据
    query_tree() {
      this.tree_data = [];
      get("api/rest/document/queryDocumentTree?module="+this.module_name)
        .then((res) => {
          this.tree_data = [{
            id:2,
            label:'文档列表',
            level:0,
            children:res
          }];
          this.currentRole = "navs";
          let arr = [2];
          if(res.length>0){
            arr.push(res[0].id)
          }
          this.clientDetails = { type: arr };
        })
        .catch((err) => {
          this.$message.warning(err.message);
        });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    //节点点击事件
    handleNodeClick(node, data) {
        this.currentRole = "navs";
        let arr = [node.id];
        if(data.childNodes.length>0){
          arr.push(data.childNodes[0].data.id)
        }
        this.clientDetails = { type: arr };
      // if (node.id == 21 || this.getparentNode(data) == 21) {
      //   this.currentRole = "navs";
      //   this.clientDetails = { type: node.id };
      // } else if (node.id == 25 || this.getparentNode(data) == 25) {
      //   this.currentRole = "navs1";
      // } else {
      //   this.currentRole = "";
      // }
    },
    //查询当前节点的最顶层节点ID
    getparentNode(data) {
      if (data.data.parentCode == null) {
        return data.data.id;
      } else {
        return this.getparentNode(data.parent);
      }
    },
    //导入数据弹出框
    importExcelData(data) {
      this.dialogVisibleImport = true;
      this.title = data.label;
      this.pickNew = data;
      this.tableDataFromExcelHead = [];
      this.tableDataFromExcel = [];
    },
    // 核心部分代码(handleChange 和 importfile)
    handleChange(file, fileList) {
      this.tableDataFromExcelHead = [];
      this.tableDataFromExcel = [];
      this.fileContent = file.raw;
      const fileName = file.name;
      const fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
      if (this.fileContent) {
        if (fileType === "xlsx" || fileType === "xls") {
          this.importfile(this.fileContent);
        } else {
          this.$message({
            type: "warning",
            message: "附件格式错误，请重新上传！",
          });
        }
      } else {
        this.$message({
          type: "warning",
          message: "请上传附件！",
        });
      }
    },
    importfile(obj) {
      const reader = new FileReader();
      const that = this;
      reader.readAsArrayBuffer(obj);
      reader.onload = function () {
        const buffer = reader.result;
        const bytes = new Uint8Array(buffer);
        const length = bytes.byteLength;
        let binary = "";
        for (let i = 0; i < length; i++) {
          binary += String.fromCharCode(bytes[i]);
        }
        const XLSX = require("xlsx");
        const wb = XLSX.read(binary, {
          type: "binary",
        });
        const outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
        this.excelData = [...outdata];
        const arr = [],
          arr1 = [];
        if (this.excelData.length > 0) {
          [this.excelData[0]].map((v) => {
            for (let key in v) {
              let obj = {};
              obj["column_name"] = key;
              obj["column_comment"] = key;
              arr.push(obj);
            }
          });
          this.excelData.map((v, i) => {
            let obj1 = {};
            for (let key in v) {
              obj["column_name"] = key;
              obj["column_comment"] = key;
              obj1[key] = v[key];
            }
            arr1.push(obj1);
          });
          that.tableDataFromExcelHead = arr;
          that.tableDataFromExcel = that.tableDataFromExcel.concat(arr1);
        }
      };
    },
    //导入数据确定事件
    defineImport() {
      let importData = [];
      this.$refs.mychild.parentHandleclick("嘿嘿嘿");
      return;
      let obj = {
        content: this.tableDataFromExcel,
        title: this.tableDataFromExcelHead.reduce((pre, item) => {
          pre[item.column_name] = item.column_comment;
          return pre;
        }, {}),
        createId: "string",
        id: "string",
        name: this.pickNew.label,
        treeId: this.pickNew.id,
      };
      let length = this.tableDataFromExcel.length;
      post("api/rest/resource/addResourceItem", obj)
        .then((res) => {
          if (res == length) {
            this.$message.success("上传成功！");
            this.dialogVisibleImport = false;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  activated() {
    this.query_tree();
  },
};
</script>
<style lang="scss">
#wfzywxk {
  width: calc(100% - 50px);
  height: calc(100% - 70px);
  margin: 20px;
  .left-div {
    width: 15%;
    height: 100%;
    box-sizing: border-box;
    padding: 20px;
    float: left;
    background: url("../../assets/img/yqjc/01.png") no-repeat;
    background-size: 100% 100%;
    input {
      color: white;
      background-color: transparent;
    }
    .el-input {
      position: relative;
      font-size: 14px;
      display: inline-block;
      width: 100%;
    }
    .el-button + .el-button {
      margin-left: 0px !important;
    }
    .el-tree {
      color: white;
      background: transparent;
      height: calc(100% - 50px);
      margin-top: 10px;
      .el-tree-node__content {
        height: 40px;
        .el-icon-circle-plus {
          display: none;
        }
        .el-icon-error {
          display: none;
        }
        .el-icon-upload {
          display: none;
        }
        .el-icon-edit-outline {
          display: none;
        }
        .list-span{
          display: none;
        }
      }
    }
    .el-tree > .el-tree-node > .el-tree-node__content {
      height: 40px;
      background-image: url(../../assets/img/yqjc/24.png);
      background-repeat: no-repeat;
      background-size: 100% 100%;
      .el-icon-error {
        display: none !important;
      }
      .el-icon-edit-outline {
        display: none !important;
      }
      // .list-span{
      //   display: none !important;
      // }
      // .el-button{
      //   margin-left: -50px;
      // }
    }
    .el-tree
      > .el-tree-node
      > .el-tree-node__children
      > .el-tree-node
      > .el-tree-node__content {
      height: 40px;
      // background-image: url(../../assets/img/yqjc/24.png);
      background-repeat: no-repeat;
      background-size: 100% 100%;
    }
    .el-tree > .el-tree-node > .el-tree-node__content > .el-tree-node__label {
      font-size: 16px !important;
    }
    .custom-tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      padding-right: 8px;
      width: 82%;
      .first-span {
        width: 100%;
        float: left;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .list-span{
        position: absolute;
        right: 20px;
      }
    }
    .el-tree > .el-tree-node > .el-tree-node__children {
      background-color: #1d2d46ad !important;
      width: 100%;
      height: calc(100% - 44px);
      overflow: auto;
      position: relative;
      .el-tree-node{
        width: 300px;
      }
    }
    .el-tree-node:focus > .el-tree-node__content {
      background-color: #00648a96 !important;
      // border-radius: 5px;
    }

    .el-tree-node__content:hover,
    .el-tree-node__content:focus {
      background-color: #00638a50 !important;
      // border-radius: 5px;
      .el-icon-circle-plus {
        display: block;
      }
      .el-icon-edit-outline {
        display: block;
      }
      .el-icon-error {
        display: block;
      }
      .el-icon-upload {
        display: block;
      }
      .list-span{
        display: block;
      }
    }
    .el-tree--highlight-current
      .el-tree-node.is-current
      > .el-tree-node__content {
      background-color: #00648a96 !important;
      // border-radius: 5px;
    }
    .el-icon-circle-plus {
      font-size: 16px;
      color: #00a6f5;
    }
    .el-icon-edit-outline {
      font-size: 16px;
      color: #2ae209;
    }
    .el-icon-error {
      font-size: 16px;
      color: #ff5454;
    }
    .el-icon-upload {
      font-size: 16px;
      color: #2bce0e;
    }
  }
  .right-div {
    width: calc(85% - 10px);
    height: 100%;
    float: left;
    margin-left: 10px;
    background: url("../../assets/img/yqjc/02.png") no-repeat;
    background-size: 100% 100%;
  }
  .el-dialog {
    width: 400px;
    background-color: #1d2d47;
    .el-dialog__header {
      text-align: center;
      .el-dialog__title {
        color: white;
      }
    }
    .el-dialog__body{
      .dialogContent {
        span {
          float: left;
          margin-top: 5.5px;
          color: white;
        }
        .el-input {
          width: 80%;
          input {
            height: 30px;
          }
        }
      }
    }
  }
  #impor_file .el-dialog__body{
      text-align: center;
  }
  .importData .el-dialog {
    width: 35%;
    td,
    th {
      text-align: center;
    }
  }
  .el-dialog{
    .el-input__inner {
      color: white !important;
      background: none !important;
      border: 1px solid #146a80 !important;
      box-shadow: 0 0 10px #1b6097;
    }
    .el-textarea__inner {
      color: white !important;
      background: none !important;
      border: 1px solid #146a80 !important;
      box-shadow: 0 0 10px #1b6097;
    }
  }
}
</style>
