<template>
  <div class="eteo-container">
    <div class="left-cont minHeight">
      <div class="left-top">
        <el-button
          v-permission="permissionBtn.dataSourcePermission.eiaData_export"
          style="width: 100%"
          type="primary"
          plain
          size="medium"
          @click="exportClick"
          :loading="btnload"
          >导出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>
      <ul class="classify-list">
        <li
          :class="[
            'classify-item',
            { act: select_classify === item.BaseFromEiaSteoClassifyId },
          ]"
          v-for="item in classifyList"
          :key="item.BaseFromEiaSteoClassifyId"
          @click="changeClassify(item.BaseFromEiaSteoClassifyId)"
        >
          {{ item.ClassifyName }}
        </li>
      </ul>
    </div>
    <div
      class="right-cont minHeight"
      v-loading="dataloading"
      element-loading-text="获取数据中..."
    >
      <div class="right-box" @scroll="scrollHandle" v-if="rightShow">
        <div class="data-header">
          <lz-table
            :tableOption="tableOption"
            tableType="header"
            ref="table"
            source="smm"
          />
        </div>
        <div class="data-cont" v-if="dateArr.length">
          <lz-table
            :tableOption="tableOption"
            tableType="data"
            :dateArr="dateArr"
            source="smm"
          />
        </div>
        <div v-else class="nodata"></div>
      </div>
    </div>
  </div>
</template>

<script>
import lzTable from "@/components/lzTable.vue";
import { steoInterface } from "@/api/modules/thirdBaseApi.js";
export default {
  name: "",
  components: { lzTable },
  data() {
    return {
      exportBase: process.env.VUE_APP_API_ROOT + "/datamanage/eia_steo/data", //数据导出接口
      dataloading: false,
      rightShow: false,
      select_classify: "",
      classifyList: [],
      tableOption: [],
      dateArr: [], //最长的日期数组
      btnload: false,
      page_no: 1,
      page_size: 20,
      havemore: true, //是否还有数据

      leftSearchVal: "", //左侧搜索值
      leftSearchTradeCode: "", //如果是搜索选择的 则有此code
    };
  },
  methods: {
    /* 获取分类 */
    getClassify() {
      steoInterface.classifyList().then((res) => {
        if (res.Ret !== 200) return;
        this.classifyList = res.Data || [];
        this.select_classify =
          this.select_classify ||
          this.classifyList[0].BaseFromEiaSteoClassifyId;

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

    /* 获取数据 */
    getDataList: _.throttle(function () {
      this.dataloading = true;
      steoInterface
        .dataList({
          BaseFromEiaSteoClassifyId: this.select_classify,
          IndexCode: this.leftSearchTradeCode || "",
          PageSize: this.page_size,
          CurrentIndex: this.page_no,
          IsExport: false,
        })
        .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) => 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.initWidth();
            });
        });
    }, 200),

    /* 改变品种 */
    changeClassify(id) {
      this.select_classify = id;
      this.leftSearchVal = "";
      this.leftSearchTradeCode = "";
      this.page_no = 1;
      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;
    },

    /* 滚动加载 */
    scrollHandle(e) {
      const dom = e.target;
      let total = dom.scrollTop + dom.clientHeight;
      if (total >= dom.scrollHeight && this.havemore) {
        this.page_no++;
        console.log("load下一页");

        this.getDataList();
      }
    },

    //左侧搜索
    async handleLeftSearch(query, cb) {
      cb([]);
      if (!query) return;
      const res = await steoInterface.targetSearch({
        Keyword: query,
      });
      if (res.Ret !== 200) return;
      let arr = res.Data || [];
      if (!arr.length) {
        cb([{ nodata: true }]);
      } else {
        cb(arr);
      }
    },
    // 选中左侧搜索值
    handleSelectLeftSearchval(e) {
      if (!e.IndexCode) return;
      this.rightShow = false;

      this.select_classify = e.BaseFromEiaSteoClassifyId;
      this.leftSearchTradeCode = e.IndexCode;
      this.leftSearchVal = e.IndexName;

      this.page_no = 1;
      // 获取单独指标数据
      this.getDataList();
      this.$nextTick(() => {
        this.rightShow = true;
        this.handleScrollLeftWrap();
      });
    },
    // 左侧滚动
    handleScrollLeftWrap() {
      let top = $(".act")[0].offsetTop;
      $(".classify-list").animate({
        scrollTop: top - 200,
      });
    },
    // 对[#,;]转义
    escapeStr(str) {
      return str.replace(/#/g, escape("#")).replace(/;/g, escape(";"));
    },

    exportClick() {
      this.btnload = true;

      const link = document.createElement("a");
      link.href = this.exportApi;
      console.log(this.exportApi);
      link.download = "";
      link.click();

      setTimeout(() => {
        this.btnload = false;
      }, 5000);
    },
  },
  computed: {
    exportApi() {
      //数据导出
      let urlStr = this.exportBase;

      // token
      urlStr += `?${localStorage.getItem("auth") || ""}`;
      // 指标名称参数
      urlStr += `&BaseFromEiaSteoClassifyId=${this.select_classify}`;
      // 指标id
      urlStr += `&IndexCode=${this.leftSearchTradeCode}`;
      // 分类名称
      urlStr += `&IsExport=true`;
      return this.escapeStr(urlStr);
    },
  },
  mounted() {
    this.getClassify();
  },
};
</script>
<style lang="scss" scoped>
.eteo-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: 160px;
    margin-right: 20px;
    padding: 30px 0;
    overflow: hidden;
    .left-top {
      padding: 0 20px;
    }
    .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: 86%;
    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;
      }
    }
  }
}
</style>
