<template>
  <div class="steelChemical-container" id="box">
    <div class="left-cont minHeight" id="left">
      <div class="left-top">
        <div>
          <el-button type="primary" size="medium" @click="addTargetHandle"
            >新增指标</el-button
          >
          <el-button
            type="primary"
            plain
            size="medium"
            @click="exportClick"
            :loading="btnload"
            >导出Excel</el-button
          >
        </div>
        <el-autocomplete
          style="margin: 20px 0; width: 100%"
          prefix-icon="el-icon-search"
          v-model="leftSearchVal"
          :fetch-suggestions="handleLeftSearch"
          :trigger-on-focus="false"
          placeholder="指标名称/指标ID"
          @select="handleSelectLeftSearchval"
          popper-class="el-autocomplete-suggestion-data-entry"
          clearable
        >
          <template slot-scope="scope">
            <div v-if="scope.item.nodata" style="text-align: center">
              暂无数据
            </div>
            <div v-else>
              {{ scope.item.IndexName }}
            </div>
          </template>
        </el-autocomplete>
      </div>

      <div class="scroll-wrap">
        <el-tree
          ref="treeRef"
          class="target_tree"
          :data="classifyList"
          node-key="UniqueCode"
          :props="{
            label: 'ClassifyName',
            children: 'Children',
          }"
          :allow-drag="canDragHandle"
          :allow-drop="canDropHandle"
          :current-node-key="select_node"
          :default-expanded-keys="defaultShowNodes"
          draggable
          :expand-on-click-node="false"
          check-strictly
          empty-text="暂无分类"
          @node-expand="handleNodeExpand"
          @node-collapse="handleNodeCollapse"
          @current-change="nodeChangeHandle"
          @node-drop="dropOverHandle"
          @node-drag-end="dropMouseLeave"
          @node-drag-leave="dropMouseLeave"
          @node-drag-enter="dropMouseOver"
        >
          <div class="custom-tree-node" slot-scope="{ node, data }">
            <span
              class="text_oneLine"
              :style="`width:${
                (select_node === data.UniqueCode && node.Nodewidth) || ''
              }`"
              >{{ data.ClassifyName }}</span
            >
            <div v-if="select_node === data.UniqueCode">
              <img
                src="~@/assets/img/data_m/move_ico.png"
                v-if="data.Button.MoveButton"
                alt=""
                style="width: 14px; height: 14px; margin-right: 5px"
                @click.stop="clickClassifyHandle('move', data, node)"
              />
              <img
                src="~@/assets/img/set_m/add.png"
                style="width: 14px; height: 14px; margin-right: 5px"
                @click.stop="clickClassifyHandle('add', data, node)"
                v-if="data.Button.AddButton"
              />
              <img
                src="~@/assets/img/set_m/edit.png"
                v-if="data.Button.OpButton"
                alt=""
                style="width: 14px; height: 14px; margin-right: 5px"
                @click.stop="clickClassifyHandle('edit', data, node)"
              />
              <img
                src="~@/assets/img/set_m/del.png"
                v-if="data.Button.DeleteButton"
                alt=""
                style="width: 14px; height: 14px"
                @click.stop="clickClassifyHandle('del', data, node)"
              />
            </div>
          </div>
        </el-tree>

        <div class="add-cont" @click="addClassifyHandle">
          <img
            src="~@/assets/img/set_m/add_ico.png"
            alt=""
            style="width: 16px; height: 16px; margin: 10px"
          />
          <span>添加分类</span>
        </div>
      </div>
      <span
        class="move-btn resize"
        v-drag
        id="resize"
        @mousemove="dynamicNode && resetNodeStyle(dynamicNode)"
      >
      </span>
    </div>

    <div
      class="right-cont minHeight"
      id="right"
      v-loading="dataloading"
      element-loading-text="获取数据中..."
    >
      <template v-if="rightShow">
        <el-button type="primary" size="medium" @click="edbRefreshHandle" :loading="isRefresh" style="margin-bottom: 10px" v-if="edb_id">一键更新</el-button>

        <div
          class="right-box"
          v-infinite-scroll="loadNext"
          :infinite-scroll-disabled="!haveMore"
          :infinite-scroll-immediate="false"
        >
          <div class="data-header">
            <lz-table
              :tableOption="tableOption"
              tableType="header"
              ref="table"
              source="gl"
            />
          </div>
          <div class="data-cont" v-if="dateArr.length">
            <lz-table
              :tableOption="tableOption"
              tableType="data"
              :dateArr="dateArr"
              source="gl"
            />
          </div>
          <div v-else class="nodata"></div>
        </div>
        <div class="frequency-list" v-if="frequencyList.length>1">
          <el-button
            type="primary"
            class="frequency-btn"
            :plain="select_frequency !== item.key"
            v-for="item in frequencyList"
            :key="item.key"
            @click="changeFrequency(item.key)"
            >{{ item.key }}</el-button
          >
        </div>
      </template>
      <div v-else class="nodata-cont">
        <img
          src="~@/assets/img/data_m/table_no.png"
          alt=""
          style="display: block;width: 140px;height: 148px;margin: 100px auto 0;"
        />
        暂无数据
      </div>
    </div>

    <!-- 分类弹窗 -->
    <m-dialog
      :show.sync="openClassifyDia"
      width="700px"
      :title="classifyForm.title"
      @close="openClassifyDia = false"
    >
      <div class="dialog-cont">
        <el-form
          ref="classifyFormRef"
          label-position="left"
          hide-required-asterisk
          label-width="80px"
          :model="classifyForm"
          :rules="classifyFormRules"
          @close="cancelDialogHandle"
        >
          <el-form-item label="一级目录" v-if="classifyForm.parent_classify_id">
            <span>{{ classifyForm.parent_classify_name }}</span>
          </el-form-item>
          <el-form-item label="分类名称" prop="classify_name">
            <el-input
              v-model="classifyForm.classify_name"
              style="width: 80%"
              placeholder="必填项"
            />
          </el-form-item>
        </el-form>
      </div>
      <div class="dia-bot">
        <el-button
          type="primary"
          style="margin-right: 20px"
          @click="saveClassifyHandle"
          >保存</el-button
        >
        <el-button type="primary" plain @click="cancelDialogHandle"
          >取消</el-button
        >
      </div>
    </m-dialog>

    <!-- 指标弹窗 -->
    <target-dialog
      :isOpenDialog.sync="addTargetDialog"
      :classifyList="classifyList"
      :edbForm="edbForm"
      @successCallback="addSuccessCallback"
    />
  </div>
</template>

<script>
import lzTable from "@/components/lzTable.vue";
import { steelInterface } from "@/api/modules/thirdBaseApi";
import mDialog from "@/components/mDialog.vue";
import targetDialog from "./components/targetDialog.vue";
import leftMixin from "./mixins/leftMixin.js";
export default {
  name: "",
  mixins: [leftMixin],
  components: { lzTable, mDialog, targetDialog },
  data() {
    return {
      dataloading: false,
      rightShow: false,
      exportBase:
        process.env.API_ROOT + "/datamanage/mysteel_chemical/export/dataList", //数据导出接口
      select_classify: "",
      leftSearchVal: "",
      classifyList: [],
      select_frequency: "",
      frequencyList: [],
      tableOption: [],
      dateArr: [], //最长的日期数组
      btnload: false,
      page_size: 20,
      page_no: 1,
      haveMore: false,
      isRefresh: false,

      edb_id: "", //搜索指标id
      select_node: "",
      dynamicNode: null,
      defaultShowNodes: [], //展开节点

      openClassifyDia: false,
      classifyForm: {
        title: "添加分类",
        classify_name: "",
        parent_classify_name: "",
        parent_classify_id: "",
      },
      classifyFormRules: {
        classify_name: [
          { required: true, message: "分类名称不能为空", trigger: "blur" },
        ],
      },

      addTargetDialog: false, //添加指标弹窗
      edbForm: {},
    };
  },
  methods: {
    /* 获取分类 */
    getClassify(params = null) {
      steelInterface.classifyList().then((res) => {
        if (res.Ret !== 200) return;
        this.classifyList = res.Data || [];
        // this.select_classify = this.select_classify || this.classifyList[0].BaseFromMysteelChemicalClassifyId;
        this.$nextTick(() => {
          /* 处理树展开和选中 */
          params && this.selectCurrentNode(params);
          !params &&
            this.select_node &&
            this.$refs.treeRef.setCurrentKey(this.select_node);
        });
      });
    },

    /* 获取频度 */
    getFrequency(defaultSelect) {
      steelInterface
        .frequencyList({
          BaseFromMysteelChemicalClassifyId: this.select_classify,
          BaseFromMysteelChemicalIndexId: this.edb_id,
        })
        .then((res) => {
          if (res.Ret !== 200) return;
          this.frequencyList = res.Data
            ? res.Data.map((item) => ({
                key: item.Frequency,
              }))
            : [];
          //设置当前选中的频度,若传入有默认选项则选中默认频度,否则选中列表第一个
          this.select_frequency =
            defaultSelect || this.frequencyList.length
              ? this.frequencyList[0].key
              : "";

          this.page_no = 1;
          this.select_frequency && this.getDataList();
        });
    },

    /* 获取数据 */
    getDataList() {
      this.dataloading = true;
      steelInterface
        .dataList({
          BaseFromMysteelChemicalClassifyId: this.select_classify,
          BaseFromMysteelChemicalIndexId: this.edb_id,
          Frequency: this.select_frequency,
          PageSize: this.page_size,
          CurrentIndex: this.page_no,
        })
        .then((res) => {
          this.rightShow = true;
          if (res.Ret !== 200) return;

          // 找出最多的页码 判断是否还有数据
          let page_arrs = res.Data.map((item) => item.Paging.Pages);
          let totalPage = Math.max.apply(Math, page_arrs);
          this.haveMore = this.page_no < totalPage ? true : false;

          // 合并数据
          if (this.page_no === 1) {
            this.tableOption = res.Data;
          } else {
            this.tableOption.forEach((item) => {
              res.Data.forEach((_item) => {
                if (item.IndexCode === _item.IndexCode) {
                  item.DataList = [...item.DataList, ..._item.DataList];
                }
              });
            });
          }

          // 合并所有指标中的日期 作为日期数组
          let arr = res.Data.map((item) => {
            return item.DataList;
          });

          let obj = [];
          for (let i of arr) {
            for (let j of i) {
              obj.push(j.DataTime);
            }
          }
          let arr2 = [...new Set(obj)].sort().reverse();

          let concatArr = [...new Set([...this.dateArr, ...arr2])]
            .sort()
            .reverse();
          this.dateArr = this.page_no === 1 ? arr2 : concatArr;

          /* 不满6个追加6个空的显示一排 别问 问就是为了美观  */
          if (res.Data.length < 7)
            for (let i = 0; i < 7; i++) {
              this.tableOption.push({
                DataList: [],
              });
              if (this.tableOption.length >= 7) break;
            }

          //数据最大长度小于12个 追加数据满12个 别问 问就是为了美观
          if (this.dateArr.length < 12)
            for (let i = 0; i < 12; i++) {
              this.dateArr.push("");
              if (this.dateArr.length >= 12) break;
            }

          this.dataloading = false;
          this.page_no === 1 &&
            this.$nextTick(() => {
              this.initWidth();
            });
        });
    },

    loadNext() {
      this.page_no++;
      this.getDataList();
    },

    /* 改变节点 */
    nodeChangeHandle(data, node) {
      if(this.dataloading) return this.$message('请求频繁,请数据加载完成后再试!')
      this.dynamicNode = node;
      this.select_node = data.UniqueCode;
      this.select_classify = data.BaseFromMysteelChemicalClassifyId;
      this.edb_id = data.BaseFromMysteelChemicalIndexId;

      this.select_frequency = "";
      this.rightShow = false;
      this.leftSearchVal = "";
      this.getFrequency();
      this.resetNodeStyle(node);
    },
    /* 改变频度 */
    changeFrequency(key) {
      this.select_frequency = key;
      this.getDataList();
    },

    initWidth() {
      $(".right-box")[0].style.width =
        this.$refs.table.$el.clientWidth + 5 + "px";
      $(".right-box")[0].scrollTop = 0;
      $(".right-box")[0].scrollLeft = 0;
    },

    /* 钢联数据导出 */
    exportClick() {
      this.btnload = true;

      const link = document.createElement("a");
      link.href = this.exportGlapi;
      link.download = "";
      link.click();
      setTimeout(() => {
        this.btnload = false;
      }, 5000);
    },

    //左侧搜索
    async handleLeftSearch(query, cb) {
      cb([]);
      if (!query) return;
      const res = await steelInterface.searchEdb({
        Keyword: query,
      });
      if (res.Ret === 200) {
        let arr = res.Data || [];
        if (!arr.length) {
          cb([{ nodata: true }]);
        } else {
          cb(arr);
        }
      }
    },

    // 选中左侧搜索值
    handleSelectLeftSearchval(e) {
      if (!e.IndexCode) return;

      this.leftSearchVal = e.IndexName;

      this.getClassify({ code: e.UniqueCode, id: e.Id });
    },

    /* 编辑分类 */
    async editClassifyHandle(
      {
        BaseFromMysteelChemicalClassifyId,
        ClassifyName,
        ParentId,
        BaseFromMysteelChemicalIndexId,
      },
      node
    ) {
      if (node.level === 3) {
        // 指标
        let { Data } = await steelInterface.edbDetail({
          BaseFromMysteelChemicalIndexId,
        });
        this.edbForm = {
          edb_id: Data.BaseFromMysteelChemicalIndexId,
          classify_id: Data.BaseFromMysteelChemicalClassifyId,
          from_edb_code: Data.IndexCode,
          frequency: Data.UpdateWeek,
          update_time: Data.UpdateTime ? Data.UpdateTime.split(",") : [],
        };
        this.addTargetDialog = true;
      } else {
        //分类
        this.openClassifyDia = true;
        this.classifyForm = {
          title: "编辑分类",
          classify_name: ClassifyName,
          classify_id: BaseFromMysteelChemicalClassifyId,
          parent_classify_name:
            node.level === 2 ? node.parent.data.ClassifyName : "",
          parent_classify_id: node.level === 2 ? ParentId : "",
        };
      }
    },

    /* 删除分类 */
    delClassifyHandle(
      { BaseFromMysteelChemicalClassifyId, BaseFromMysteelChemicalIndexId },
      node
    ) {
      this.$confirm(
        `${
          node.level === 3
            ? "删除后该指标不能被引用，确认删除吗?"
            : "删除分类将同步删除分类下所有指标，确认删除吗?"
        }`,
        "提示",
        {
          type: "warning",
        }
      )
        .then(async () => {
          let res =
            node.level === 3
              ? await steelInterface.edbDel({ BaseFromMysteelChemicalIndexId })
              : await steelInterface.classifyDel({
                  BaseFromMysteelChemicalClassifyId,
                });

          if (res.Ret !== 200) return;

          this.$message.success("删除成功");
          this.getClassify();
        })
        .catch(() => {});
    },

    clickClassifyHandle(key, item, node) {
      const handleMap = {
        add: this.addClassifyHandle,
        edit: this.editClassifyHandle,
        del: this.delClassifyHandle,
      };

      handleMap[key] && handleMap[key](item, node);
    },

    /* 添加分类 */
    addClassifyHandle(item = null) {
      this.openClassifyDia = true;
      this.classifyForm = item
        ? {
            title: "添加分类",
            classify_name: "",
            parent_classify_name: item.ClassifyName,
            parent_classify_id: item.BaseFromMysteelChemicalClassifyId,
          }
        : {
            title: "添加分类",
            classify_name: "",
          };
    },

    cancelDialogHandle() {
      this.$refs.classifyFormRef.clearValidate();
      this.classifyForm.classify_name = "";
      this.openClassifyDia = false;
    },

    /* 保存分类 */
    async saveClassifyHandle() {
      await this.$refs.classifyFormRef.validate();

      let params = {
        ClassifyName: this.classifyForm.classify_name,
        ParentId: this.classifyForm.parent_classify_id,
        Level: this.classifyForm.parent_classify_id ? 1 : 0,
      };
      const res = this.classifyForm.classify_id
        ? await steelInterface.classifyEdit({
            ...params,
            BaseFromMysteelChemicalClassifyId: this.classifyForm.classify_id,
          })
        : await steelInterface.classifyAdd(params);

      if (res.Ret !== 200) return;

      this.$message.success("保存成功");
      this.getClassify();
      this.openClassifyDia = false;
    },

    /* 添加指标 */
    addTargetHandle() {
      this.edbForm = {};
      this.addTargetDialog = true;
    },

    /* 指标刷新 */
    edbRefreshHandle() {
      this.isRefresh = true;
      steelInterface.edbRefresh({
        BaseFromMysteelChemicalIndexId: this.edb_id,
      }).then(res => {
        this.isRefresh = false;
        if(res.Ret !== 200) return
        this.$message.success('刷新成功');
        this.page_no = 1;
        this.getDataList();
      })
    },

    /* 添加后回调 */
    addSuccessCallback({ code, id }) {
      this.getClassify({ code, id });
    },

    // 对[# ;]转义
    escapeStr(str) {
      return str.replace(/#/g, escape("#")).replace(/;/g, escape(";"));
    },
  },
  computed: {
    exportGlapi() {
      // 数据导出接口
      let urlStr = this.exportBase;
      // token
      urlStr += `?${localStorage.getItem("auth") || ""}`;
      // 指标名称参数
      urlStr += `&BaseFromMysteelChemicalClassifyId=${this.select_classify}`;
      return this.escapeStr(urlStr);
    },
  },
  mounted() {
    this.getClassify();
  },
};
</script>
<style lang="scss" scoped>
.steelChemical-container {
  display: flex;
  * {
    box-sizing: border-box;
  }
  .minHeight {
    height: calc(100vh - 120px);
    background-color: #fff;
    box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
    border-radius: 4px;
  }
  div::-webkit-scrollbar {
    width: 5px !important;
  }
  .left-cont {
    min-width: 300px;
    width: 300px;
    flex-shrink: 0;
    margin-right: 20px;
    padding: 30px 0;
    overflow: hidden;
    position: relative;
    .left-top {
      padding: 0 20px;
    }
    .scroll-wrap {
      padding: 0 10px;
      height: calc(100vh - 280px);
      overflow-y: auto;
    }
    .target_tree {
      color: #333;
      .label-input .el-input__inner {
        height: 25px;
        line-height: 25px;
      }
      .custom-tree-node {
        display: flex !important;
        justify-content: space-between;
        align-items: center;
        display: block;
        flex: 1;
        .node_label {
          margin-right: 2px;
        }
        .el-icon-view {
          color: #409eff;
          font-size: 18px;
          margin-left: 5px;
        }
      }
    }
    .add-cont {
      margin: 50px 0 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #409eff;
      font-size: 16px;
      cursor: pointer;
    }
    .move-btn {
      height: 100%;
      width: 4px;
      position: absolute;
      right: 0px;
      top: 0;
      &:hover {
        cursor: col-resize;
      }
    }
  }
  .right-cont {
    width: 82%;
    padding: 30px;
    position: relative;
    .right-box {
      max-width: 100%;
      max-height: calc(100vh - 230px);
      border-left: 1px solid #dcdfe6;
      border-right: 1px solid #dcdfe6;
      overflow: auto;
      .data-header {
        width: 100%;
        position: sticky;
        top: 0;
        z-index: 2;
      }
      .data-cont {
        height: calc(100vh - 444px);
      }
      .nodata {
        height: calc(100vh - 460px);
        border: 1px solid #dcdfe6;
        font-size: 16px;
        color: #999;
      }
    }
    .frequency-list {
      margin-top: 20px;
      display: flex;
      flex-wrap: wrap;
      .frequency-btn {
        width: 112px;
        margin: 0 30px 10px 0;
      }
    }
  }
  .nodata-cont {
    width: 150px !important;
    text-align: center;
    color: #666;
    font-size: 16px;
    margin: 0 auto;
  }
}
.dialog-cont {
  padding-left: 50px;
}
.dia-bot {
  display: flex;
  justify-content: center;
}
</style>
<style lang="scss">
.steelChemical-container {
  .el-tree__drop-indicator {
    height: 3px;
    background-color: #409eff;
  }
  .el-tree-node__content {
    margin-bottom: 14px !important;
  }
  .el-tree-node__children {
    .el-tree-node {
      margin-bottom: 0px !important;
      padding-left: 18px;
    }
    .el-tree-node__content {
      margin-bottom: 5px !important;
      padding-left: 0 !important;
    }
  }
  .expanded.el-icon-caret-right:before {
    content: url("~@/assets/img/set_m/down.png") !important;
  }
  .el-icon-caret-right:before {
    content: url("~@/assets/img/set_m/slide.png") !important;
  }
  .el-tree-node__expand-icon.is-leaf.el-icon-caret-right:before {
    content: "" !important;
  }
  .el-tree-node__expand-icon.expanded {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  .el-tree-node.is-current > .el-tree-node__content {
    background-color: #f0f4ff !important;
  }
  .el-tree-node__content {
    padding-right: 10px !important;
  }
}
</style>
