<template>
  <div>
    <el-dialog v-dialogDrag width="80%" title="导入" :visible.sync="logTable" :close-on-click-modal="false"
      :modal-append-to-body="false" :before-close="cancel">
      <el-row>
        <el-col :span="24">
          <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>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <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-col>
        <el-col :span="2"></el-col>
        <el-col :span="16">
          <el-table :data="tableData" border @row-dblclick="handleRowDbclick" height="550">
            <el-table-column label="Excel表字段名" prop="columnExcel" align="center"></el-table-column>
            <el-table-column label="实体表字段名" prop="columnName" align="center"></el-table-column>
            <el-table-column label="字段中文名" prop="columnChnName" align="center" width="110"></el-table-column>
            <el-table-column label="允许为空" width="90" prop="columnCanNull" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.columnCanNull === "false" ? "否" : "是" }}</span>
              </template>
            </el-table-column>
            <el-table-column label="字段类型" width="90" prop="columnClass" align="center">
            </el-table-column>
            <el-table-column label="字段长度" prop="columnWidth" width="90" align="center"></el-table-column>
            <el-table-column label="字段小数位" width="110" prop="columnPoint" align="center"></el-table-column>
          </el-table>
          <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary">确 定</el-button>
          </span>
        </el-col>
      </el-row>
      <dia-field :visible="diaVisible" @cancel="fieldCancel" @revoke="revoke" :excelData="excelData" ref="diaField"
        @submit="submitForm" />
    </el-dialog>
  </div>
</template>

<script>
import { getTree } from "@/api/archives-management/fileManagement/notRecycleBin";
import { getData } from "@/api/dataManagement/dataImport";
import { URL_PREFIX } from "@/utils/url-prefix";
import { mapState } from "vuex";
import {
  importData,
  importDateThree,
  importFileDate,
} from "@/api/dataManagement/dataImport";
import { message, dragControllerDiv } from "@/utils/common";
import diaField from "./diaField";
export default {
  data() {
    return {
      defaultProps: {
        label: "className",
        children: "childClass",
      },
      treeNode: {},
      treeRow: {},
      fileList: [],
      importBtn: true, // 导入按钮禁用
      excelData: [], // 上传excel接口返回数据
      uploadBtn: true, // 上传excel按钮禁用
      importBtn: true, // 导入按钮禁用
      importLoading: false, // 导入按钮加载
      diaVisible: false,
      columnClassList: [],
    };
  },
  props: {
    logTable: {
      type: Boolean,
      default: () => false,
    },
  },
  components: {
    diaField,
  },
  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;
      },
    },
    tableData: {
      get() {
        return this.$store.state.dataImport.tableData;
      },
      set(val) {
        this.$store.state.dataImport.tableData;
      },
    },
  },
  methods: {
    cancel() {
      this.importBtn = true;
      this.fileList = [];
      this.$emit("logTableCancel");
    },
    // 撤销
    revoke(val) {
      const rowIndex = this.tableData.findIndex((item) => item.id === val.id);
      val.columnExcel = undefined;
      this.updateTable(rowIndex, val);
    },
    // 保存
    submitForm(val) {
      const rowIndex = this.tableData.findIndex((item) => item.id === val.id);
      this.updateTable(rowIndex, val);
    },
    // 更新store表格数据
    updateTable(rowIndex, row) {
      this.$set(this.tableData, rowIndex, row);
      this.$store.commit("dataImport/GET_DATA", this.tableData);
      this.fieldCancel();
    },
    fieldCancel() {
      this.diaVisible = false;
    },
    handleRowDbclick(row) {
      this.diaVisible = true;
      this.$refs.diaField.form = { ...row };
    },
    onChange(file, fileList) {
      this.fileList = fileList.splice(fileList.length - 1, 1);
    },
    httpRequest(param) {
      let fileObj = param.file; // 相当于input里取得的files
      let fd = new FormData(); // FormData 对象
      fd.append("multipartFile", fileObj); // 文件对象
      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();
            this.zidonggpipei();
          } else {
            this.fileList = [];
            this.$message.error(response.msg);
          }
        })
        .catch((error) => {
          // this.$message.error("上传失败！");
        });
    },
    zidonggpipei() {
      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);
      this.fieldCancel();
    },
    handleNodeClick(data, node) {
      if (node.isLeaf) {
        this.importBtn = true;
        this.fileList = [];
        this.treeRow = data;
        this.treeNode = node;
        this.getData(data.id);
      }
    },
    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;
      let _this = this;
      if (this.treeNode.parent.childNodes.length === 3) {
        importDateThree(params)
          .then((res) => {
            if (res.code === "100") {
              if (res.body.success) {
                message("success", "导入数据成功", 2000);
                _this.$emit("rest");
                _this.cancel();
              } else {
                message("error", res.body.message, 2000);
              }
            }
          })
          .finally(() => {
            this.importLoading = false;
          });
      } else {
        importFileDate(params)
          .then((res) => {
            if (res.code === "100") {
              if (res.body.success) {
                message("success", "导入数据成功", 2000);
                _this.$emit("rest");
                _this.cancel();
              } else {
                message("error", res.body.message, 2000);
              }
            }
          })
          .finally(() => {
            this.importLoading = false;
          });
      }
    },
    // 获取表格数据
    getData(id) {
      this.tableLoading = true;
      const params = {
        entityId: id,
      };
      this.$store.dispatch("dataImport/getData", params).catch((err) => {
        this.tableLoading = false;
      });
      this.uploadBtn = false;
    },
    getTree() {
      this.treeLoading = true;
      this.$store.dispatch("dataImport/getTree", { className: "文件" });
    },
  },
  mounted() {
    // this.getSelect();
    this.getTree();
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-row {
  margin-bottom: 8px;
}

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

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

  .import-btn {
    margin-left: 15px;
    // position: absolute;
    height: 28px;
  }
}
</style>