<template>
  <div class="smmTarget-container target-container" id="box">
    <span
        v-show="!isLeftWrapShow"
        class="slide-btn-icon slide-right"
        @click="isLeftWrapShow = !isLeftWrapShow"
    >
        <i :class="{'el-icon-d-arrow-left':isLeftWrapShow,'el-icon-d-arrow-right':!isLeftWrapShow}"></i>
    </span>
    <div class="left-cont minHeight" id="left" v-show="isLeftWrapShow">
        <span
            v-show="isLeftWrapShow"
            class="slide-btn-icon slide-left"
            @click="isLeftWrapShow = !isLeftWrapShow"
        >
            <i :class="{'el-icon-d-arrow-left':isLeftWrapShow,'el-icon-d-arrow-right':!isLeftWrapShow}"></i>
        </span>
      <div class="left-top">
        <el-button
          v-permission="permissionBtn.dataSourcePermission.yyzxData_export"
          style="width: 100%"
          type="primary"
          plain
          size="medium"
          @click="exportClick"
          :loading="btnload"
          :disabled="!select_classify&&!leftSearchTradeCode"
          >导出Excel</el-button
        >
        <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="ClassifyId"
          :props="{
            label: 'ClassifyName',
            children: 'Children',
          }"
          :current-node-key="select_classify"
          :expand-on-click-node="false"
          check-strictly
          highlight-current
          empty-text="暂无分类"
          @current-change="nodeChangeHandle"
        >
        </el-tree>
      </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">
        <div class="right-box" @scroll="scrollHandle">
          <div class="data-header">
            <lz-table
              :tableOption="tableOption"
              tableType="header"
              ref="table"
              source="yyzx"
              @editTarget="editTargetByTable"
            />
          </div>
          <div class="data-cont" v-if="dateArr.length">
            <lz-table
              :tableOption="tableOption"
              tableType="data"
              :dateArr="dateArr"
              source="yyzx"
            />
          </div>
          <div v-else class="nodata"></div>
        </div>
      </template>
      <div v-else class="nodata-cont">
        <tableNoData text="暂无数据"/>
      </div>
    </div>
  </div>
</template>

<script>
import lzTable from "@/components/lzTable.vue";
import { yongyiInterface } from "@/api/api.js";
export default {
  name: "Yyzx",
  components: { lzTable },
  directives: {
    drag(el, bindings) {
      el.onmousedown = function (e) {
        var init = e.clientX;
        // console.log(init);
        var box = $('#box')[0];
        // console.log(box.clientWidth)
        let total_wid = box.offsetWidth;
        var left = $('#left')[0];
        var right = $('#right')[0];
        var initWidth = left.offsetWidth;
        document.onmousemove = function (e) {
          var end = e.clientX;
          var newWidth = end - init + initWidth;
          left.style.width = newWidth + 'px';
          right.style.width = newWidth > 320 ? total_wid - newWidth + 'px' : total_wid - 320 + 'px';
        };
        document.onmouseup = function () {
          document.onmousemove = document.onmouseup = null;
          e.releaseCapture && e.releaseCapture();
        };
        e.setCapture && e.setCapture();
        return false;
      };
    }
  }, 
  data() {
    return {
      isLeftWrapShow:true,
      exportBase:process.env.VUE_APP_API_ROOT + "/datamanage/yongyi/export", //ssm数据导出接口
      dataloading: false,
      rightShow: false,
      select_classify: 0,
      classifyList: [],
      tableOption: [],
      dateArr: [], //最长的日期数组
      btnload: false,
      page_no: 1,
      page_size: 20,
      havemore: true, //是否还有数据

      leftSearchVal: "", //左侧搜索值
      leftSearchTradeCode: "", //如果是搜索选择的 则有此code
      isShowSingleData: false, //右侧是否展示的是单个指标数据
    };
  },
  methods: {
    /* 获取分类 */
    getClassify() {
      yongyiInterface.classifyList().then((res) => {
        if (res.Ret !== 200) return;
        this.classifyList = res.Data.List || [];
      });
    },
    /* 获取数据 */
    getDataList: _.throttle(function () {
      this.isShowSingleData = false;
      this.dataloading = true;
      yongyiInterface
        .dataList({
          ClassifyId: this.select_classify,
          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.concat(_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 (this.tableOption.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.rightShow && this.initWidth();
            });
        });
    }, 200),
    // 获取单个指标数据
    async getTargetDataList(code) {
      this.isShowSingleData = true;
      this.dataloading = true;
      try {
        const res = await yongyiInterface.getTargetDataList({
          IndexCode: code,
        });
        this.rightShow = true;
        if (res.Ret !== 200) return;
        const DataList = res.Data.Data || [];
        // 设置为没有更多数据
        this.haveMore = false;
        // 合并数据
        this.tableOption = [
          {
            DataList: DataList,
            ...res.Data,
          },
        ];
        // 这里是单个指标所以不用合并日期
        const arr = DataList.map((item) => item.DataTime);
        this.dateArr = [...new Set(arr)].sort().reverse();
        /* 不满6个追加6个空的显示一排 别问 问就是为了美观  */
        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.select_quota = res.Data.IndexName;
        this.select_Unit = res.Data.Unit;
        this.select_frequency = res.Data.Frequency;
        this.select_ModifyTime = res.Data.ModifyTime || "";
        this.dataloading = false;
        this.rightShow && this.initWidth();
      } catch (err) {
        console.log(err);
      }
    },
    initWidth() {
      this.$nextTick(() => {
        $(".right-box")[0].style.width =
          this.$refs.table.$el.clientWidth + 5 + "px";
        $(".right-box")[0].scrollTop = 0;
        $(".right-box")[0].scrollLeft = 0;
      });
    },
    /* 无频度的异常显示处理 7*12*/
    nodataDeal() {
      this.tableOption = [];
      this.dateArr = [];
      for (let i = 0; i < 7; i++) {
        this.tableOption.push({
          DataList: [],
        });
        if (this.tableOption.length >= 7) break;
      }
      for (let i = 0; i < 12; i++) {
        this.dateArr.push("");
        if (this.dateArr.length >= 12) break;
      }
    },
    /* 滚动加载 */
    scrollHandle(e) {
      if (this.isShowSingleData) return;
      const dom = e.target;
      let total = dom.scrollTop + dom.clientHeight;
      if (total >= dom.scrollHeight && this.havemore) {
        this.page_no++;
        console.log("load下一页");
        this.getDataList();
      }
    },
    /* 数据导出 */
    exportClick() {
      this.btnload = true;
      const link = document.createElement("a");
      link.href = this.exportDataUrl;
      link.download = "";
      link.click();
      setTimeout(() => {
        this.btnload = false;
      }, 5000);
    },
    //左侧搜索
    async handleLeftSearch(query, cb) {
      cb([]);
      if (!query) return;
      const res = await yongyiInterface.getTargetListByName({
        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.leftSearchTradeCode = e.IndexCode;
      this.leftSearchVal = e.IndexName;

      // 获取单独指标数据
      this.getTargetDataList(e.IndexCode);
    },

    getTargetData(code, arr) {
      for (const item of arr) {
        if (item.BaseFromBaiinfoIndexCode === code) return item;
        if (item.Children && item.Children.length) {
          const _item = this.getTargetData(code, item.Children);
          if (_item) return _item;
        }
      }
    },
    // 对[#,;]转义
    escapeStr(str) {
      return str.replace(/#/g, escape("#")).replace(/;/g, escape(";")); 
    },
  
    //改变选中节点
    nodeChangeHandle(data, node) {
      if (data.ClassifyId === this.select_classify) return;
      this.select_classify = data.ClassifyId;
      this.leftSearchVal=''
      this.page_no = 1;
      this.page_size = 20;
      this.getDataList()
    },
   
  },
  computed: {
    exportDataUrl() {
      // 数据导出接口
      let urlStr = this.exportBase;
      // token
      urlStr += `?${localStorage.getItem("auth") || ""}`;
      if (this.isShowSingleData) {
        // 指标id
        urlStr += `&IndexCode=${
          this.isShowSingleData ? this.leftSearchTradeCode : ""
        }`;
      } else {
        // 目录id
        urlStr += `&ClassifyId=${
          this.isShowSingleData ? "" : this.select_classify
        }`;
      }
      return this.escapeStr(urlStr);
    },
  },
  created() {},
  mounted() {
    this.getClassify();
  },
};
</script>
<style lang="scss">
@import "../css/customtree.scss";
@import "../css/baseTargetPage.scss";
.smmTarget-dialog-cont {
  .el-cascader {
    .el-input {
      width: 100% !important;
    }
  }
}
</style>
<style lang="scss" scoped>
.smmTarget-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;
    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;
      }
    }
    .classify-list {
      padding: 0 20px;
      /* margin-top: 20px; */
      height: calc(100vh - 280px);
      overflow-y: auto;
      .classify-item {
        font-size: 14px;
        color: #666;
        margin-bottom: 20px;
        &:hover {
          cursor: pointer;
          color: #409eff;
        }
        &.act {
          color: #409eff;
        }
      }
    }
  }
  .right-cont {
    width: 82%;
    padding: 30px;
    .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>
