<template>
  <div class="box">
    <el-card class="tree-box" shadow="always" :body-style="{ padding: '5px' }" ref="cardTree">
      <div slot="header" class="clearfix">
        <span v-show="!status">选择门类档案</span>
        <el-button style="float: right; padding:  0" type="text" @click='btns'>
          <el-tooltip class="item" effect="dark" v-if="!status" content="折叠" placement="right">
            <svg-icon icon-class="leftzd" v-if="!status" />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" v-if="status" content="展开" placement="left">
            <svg-icon icon-class="rightzd" v-if="status" />
          </el-tooltip>
        </el-button>
      </div>
      <el-scrollbar wrap-style="overflow-x:hidden;" style="height: calc(100vh - 170px)">
        <el-tree v-loading="treeLoading" highlight-current :data="treeData" :props="defaultProps"
          @node-click="handleNodeClick" default-expand-all node-key="id">
          <span slot-scope="{ node, data }" class="custom-tree-node">
            <!--可以根据情况，以数据类型来显示不同的图标或图片-->
            <svg-icon icon-class="wjj" style="margin-right: 5px; color: rgb(255, 207, 92)" v-if="data.childClass.length"
              class="iconfont icon-folder-open-fill" />
            <svg-icon icon-class="wj" style="margin-right: 5px; color: rgb(255, 207, 92)" v-else
              class="iconfont icon-wenjian" />
            <span>{{ node.label }}</span>
          </span>
        </el-tree>
      </el-scrollbar>
    </el-card>
    <div class="resize" title="收缩侧边栏">
      ⋮
    </div>
    <el-card class="form-box" ref='cardForm'>
      <div slot="header" class="clearfix" style="height:auto;">
        <div style=" width:50%;">
          <span>数据导入</span>
        </div>
        <div class="btn-box">
          <el-upload action="#" class="upload-box" ref="upload" accept=".xls,.xlsx,.csv" :file-list="fileList"
            :on-change="onChange" :http-request="httpRequest">
            <el-button size="mini" type="primary" :disabled="uploadBtn">上传excel和实体字段匹配</el-button>
          </el-upload>
          <el-button type="success" class="import-btn" size="mini" @click="importData" :disabled="importBtn"
            :loading="importLoading">导入数据</el-button>
        </div>
      </div>
      <content-box :tableData='tableData' :excelData="excelData" :tableLoading='tableLoading' />
    </el-card>
  </div>
</template>
<script>
import { mapState } from "vuex";
import { message, dragControllerDiv } from "@/utils/common";
import { importData, importDateThree } from "@/api/dataManagement/dataImport";
import contentBox from "./components/content";
import localStronge from "@/api/localData";
import { URL_PREFIX } from "@/utils/url-prefix";
export default {
  data() {
    return {
      status: false,
      defaultProps: {
        label: "className",
        children: "childClass",
      },
      treeNode: {},
      treeRow: {},
      fileList: [], // 上传文件
      excelData: [], // 上传excel接口返回数据
      uploadBtn: true, // 上传excel按钮禁用
      importBtn: true, // 导入按钮禁用
      importLoading: false, // 导入按钮加载
    };
  },
  watch: {
    status: {
      handler(val, oldVal) {
        const cardTree = this.$refs.cardTree.$el.style;
        const cardForm = this.$refs.cardForm.$el.style;
        if (val) {
          cardTree.width = "5%";
          cardForm.width = "94%";
        } else {
          cardTree.width = "22%";
          cardForm.width = "77%";
        }
      },
    },
  },
  components: {
    contentBox,
  },
  computed: {
    ...mapState({
      tableData: (state) => state.dataImport.tableData,
      treeData: (state) => state.dataImport.treeData,
      pagination: (state) => state.dataImport.pagination,
    }),
    treeLoading: {
      get() {
        return this.$store.state.dataImport.loading;
      },
      set(val) {
        this.$store.state.dataImport.loading = val;
      },
    },
    tableLoading: {
      get() {
        return this.$store.state.dataImport.tableLoading;
      },
      set(val) {
        this.$store.state.dataImport.tableLoading = val;
      },
    },
  },
  methods: {
    btns() {
      this.status = !this.status;
    },
    getTree() {
      this.treeLoading = true;
      this.$store.dispatch("dataImport/getTree", { className: "档案" });
    },
    handleNodeClick(data, node) {
      if (node.isLeaf) {
        this.importBtn = true;
        this.fileList = [];
        this.treeRow = data;
        this.treeNode = node;
        this.getData(data.id);
      }
    },
    // 获取表格数据
    getData(id) {
      this.tableLoading = true;
      const params = {
        entityId: id,
      };
      this.$store.dispatch("dataImport/getData", params).catch((err) => {
        this.tableLoading = false;
      });
      this.uploadBtn = false;
    },
    httpRequest(param) {
      let fileObj = param.file; // 相当于input里取得的files
      let fd = new FormData(); // FormData 对象
      fd.append("multipartFile", fileObj); // 文件对象
      let _this = this;
      this.$axios
        .post(
          URL_PREFIX +
            "/point-strategy/v/import/upload?userName=" +
            sessionStorage.getItem("username"),
          fd,
          {
            headers: {
              "Content-Type": "multipart/form-data",
              "Token": sessionStorage.getItem("token"),
            },
          }
        )
        .then((response) => {
          const res = response.data;
          if (res.code === "100") {
            message("success", "上传成功", 2000);
            _this.importBtn = false;
            _this.excelData = res.body.data.filter((item) => item);
            _this.updateTable();
          } else {
            _this.fileList = [];
            _this.$message.error(response.msg);
          }
        })
        .catch((error) => {
          _this.$message.error("上传失败！");
        });
    },
    onChange(file, fileList) {
      this.fileList = fileList.splice(fileList.length - 1, 1);
    },
    updateTable() {
      const getItem = (item) => {
        return this.excelData.includes(item.columnChnName)
          ? {
              ...item,
              columnExcel: item.columnChnName,
            }
          : {
              ...item,
              columnExcel: "",
            };
      };
      this.tableData.forEach((item, index) => {
        this.$set(this.tableData, index, getItem(item));
      });
      this.$store.commit("dataImport/GET_DATA", this.tableData);
    },
    importData() {
      const params = {
        entityId: this.treeRow.id,
        fileName: this.fileList[0].name,
        tableContent: this.tableData.filter((item) => item.columnExcel),
        userName: sessionStorage.getItem("username"),
      };
      this.importLoading = true;
      if (this.treeNode.parent.childNodes.length === 3) {
        importDateThree(params)
          .then((res) => {
            if (res.code === "100") {
              if (res.body.success) {
                message("success", "导入数据成功", 2000);
              } else {
                message("error", res.body.message, 2000);
              }
            }
          })
          .finally(() => {
            this.importLoading = false;
          });
      } else {
        importData(params)
          .then((res) => {
            if (res.code === "100") {
              if (res.body.success) {
                message("success", "导入数据成功", 2000);
              } else {
                message("error", res.body.message, 2000);
              }
            }
          })
          .finally(() => {
            this.importLoading = false;
          });
      }
    },
  },
  beforeDestroy() {
    this.$store.commit("dataImport/CLEAR_DATA");
  },
  mounted() {
    dragControllerDiv();
  },
  created() {
    this.getTree();
  },
};
</script>
<style lang='scss' scoped>
.box {
  padding: 5px;
  display: flex;
  justify-content: space-around;
  height: 100%;

  .tree-box {
    width: 22%;

    background-color: #fff;
    padding: 5px 10px;

    .clearfix {
      font-weight: 600;
      font-size: 17px;
      letter-spacing: 3px;
    }
  }

  .form-box {
    width: 77%;
    height: calc(100vh - 95px);
    overflow-y: auto;

    background-color: #fff;
    padding: 5px 10px;

    .btn-box {
      width: 50%;
      display: flex;
      justify-content: flex-end;

      .upload-box {
        ::v-deep {
          .el-upload-list {
            width: 270px;
          }
        }
      }

      .import-btn {
        position: absolute;
        height: 28px;
      }
    }

    ::v-deep .el-card__header {
      padding: 14px;
    }

    .clearfix {
      width: 100%;
      height: 30px;
      font-weight: 600;
      font-size: 17px;
      letter-spacing: 3px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}
</style>
