<template>
  <div class="icpc-container coal-similarity-container">
    <span
        class="slide-btn-icon"
        :class="{'slide-left':isLeftWrapShow,'slide-right':!isLeftWrapShow}"
        @click="isLeftWrapShow = !isLeftWrapShow"
    >
        <i :class="{'el-icon-d-arrow-left':isLeftWrapShow,'el-icon-d-arrow-right':!isLeftWrapShow}"></i>
    </span>
    <div class="left-cont minHeight" v-show="isLeftWrapShow">
      <div class="left-top">
        <el-button
          style="width: 100%;"
          type="primary"
          plain
          size="medium"
          @click="exportClick"
          :loading="btnload"
          >导出Excel</el-button
        >
        <el-autocomplete
          style="margin-top: 20px; 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"
          @clear="clearSearchVal"
          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.BaseFromIcpiClassifyId }]"
          v-for="item in classifyList"
          :key="item.BaseFromIcpiClassifyId"
          @click="changeClassify(item)"
        >
          {{ item.ClassifyName }}
        </li>
      </ul>
    </div>
    <div
      class="right-cont minHeight"
      v-loading="dataloading"
      element-loading-text="获取数据中..."
    >
      <div class="right-box" v-if="rightShow" @scroll="scrollHandle">
        <template v-if="dateArr.length">
          <div class="data-header">
            <lz-table
              :tableOption="tableOption"
              tableType="header"
              ref="table"
              source="icpi"
            />
          </div>
          <div class="data-cont">
            <lz-table
              :tableOption="tableOption"
              tableType="data"
              :dateArr="dateArr"
              source="icpi"
            />
          </div>
        </template>
        <tableNoData v-else text="暂无数据" class="nodata"></tableNoData>
      </div>
    </div>
  </div>
</template>

<script>
import lzTable from "@/components/lzTable.vue";
import { lzDataInterface } from "@/api/api.js";
import { icpiInterface } from "@/api/api.js";

export default {
  name: "icpiConsumption",
  components: { lzTable },
  data() {
    return {
      isLeftWrapShow:true,
      dataloading: false,
      rightShow: false,
      exportBase: process.env.VUE_APP_API_ROOT + "/data_source/icpi/export/icpiDataList", //数据导出接口
      select_classify: "",
      classifyList: [],
      tableOption: [],
      dateArr: [], //最长的日期数组
      btnload: false,

      leftSearchVal: "", //左侧搜索值
      pageParams:{
        PageSize:20,
        CurrentIndex:1,
        KeyWord:''
      },
      havemore:true
    };
  },
  computed: {
    exportIcpiApi() {
      // 数据导出接口
      let urlStr = this.exportBase;
      // token
      urlStr += `?${localStorage.getItem("auth") || ""}`;
      // 分类Id参数
      urlStr += `&BaseFromIcpiClassifyId=${this.select_classify}`;
      urlStr += `&KeyWord=${this.pageParams.KeyWord}`;
      return this.escapeStr(urlStr);
    },
  },
  created() {
    this.getClassify();
  },
  methods: {
    /* 获取分类 */
    getClassify() {
      icpiInterface.classifyList().then((res) => {
        if (res.Ret !== 200) return;
        this.classifyList = res.Data || [];
        this.select_classify =
          this.select_classify || this.classifyList[0].BaseFromIcpiClassifyId;
        
        this.getDataList()
      });
    },

    /* 获取数据 */
    getDataList() {
      this.dataloading = true;
      icpiInterface.dataList({
        BaseFromIcpiClassifyId: Number(this.select_classify),
        PageSize:this.pageParams.PageSize,
        CurrentIndex:this.pageParams.CurrentIndex,
        KeyWord:this.pageParams.KeyWord
      }).then((res) => {
        this.rightShow = true;
        if (res.Ret !== 200) return;

        // 找出最多的页码 判断是否还有数据
        let page_arrs = res.Data.map((item) => item.Paging?item.Paging.Pages:0);
        let totalPage = Math.max.apply(Math, page_arrs);
        this.havemore = this.pageParams.CurrentIndex < totalPage ? true : false;
        
        // 设置表格数据
        this.setDataList(res.Data);
        this.CurrentIndex === 1 &&
          this.$nextTick(() => {
            this.initWidth();
          });
      }).finally(()=>{
        this.dataloading = false;
      })
    },
    /* 改变品种 */
    changeClassify(item) {
      this.select_classify = item.BaseFromIcpiClassifyId;
      this.leftSearchVal = ""
      this.pageParams.KeyWord=''
      this.pageParams.CurrentIndex=1
      this.getDataList()
    },

    initWidth() {
      $(".right-box")[0].style.width =
      this.$refs.table ? this.$refs.table.$el.clientWidth + 2 + "px":'0';
      $(".right-box")[0].scrollTop = 0;
      $(".right-box")[0].scrollLeft = 0;
    },
    // 对[#,;]转义
    escapeStr(str) {
      return str.replace(/#/g, escape("#")).replace(/;/g, escape(";")); 
    },
    /* 导出 */
    exportClick() {
      this.btnload = true;
      const link = document.createElement("a");
      link.href = this.exportIcpiApi;
      link.download = "";
      link.click();
      setTimeout(() => {
        this.btnload = false;
      }, 2000);
    },

    //左侧搜索
    async handleLeftSearch(query, cb) {
      cb([]);
      if (!query) return;
      const res = await icpiInterface.dataList({
        KeyWord: query
      });
      if (res.Ret === 200) {
        let arr = res.Data || [];
        if (!arr.length) {
          cb([{ nodata: true }]);
        } else {
          cb(arr);
        }
      }
    },
    // 选中左侧搜索值
    handleSelectLeftSearchval(e) {
      if (!e.BaseFromIcpiIndexId) return;
      this.rightShow = false;
      this.leftSearchVal = e.IndexName;
      this.pageParams.KeyWord=e.IndexName
      this.select_classify = e.BaseFromIcpiClassifyId;
      this.pageParams.CurrentIndex=1
      this.getDataList()
      this.$nextTick(() => {
        this.rightShow = true;
        this.handleScrollLeftWrap();
      });
    },
    clearSearchVal(){
      this.pageParams.KeyWord=''
      this.getDataList()
    },
    // 左侧滚动
    handleScrollLeftWrap() {
      let top = $(".act")[0].offsetTop;
      $(".classify-list").animate({
        scrollTop: top - 200,
      });
    },
    /* 滚动加载 */
    scrollHandle(e) {
      const dom = e.target;
      let total = dom.scrollTop + dom.clientHeight;
      if (total >= dom.scrollHeight && this.havemore) {
        this.pageParams.CurrentIndex++;
        // console.log("load下一页");
        this.getDataList();
      }
    },
    // 设置表格数据
    setDataList(data) {
      if(this.pageParams.CurrentIndex==1){
        this.tableOption = data;
        /* 不满7个追加7个空的显示一排 别问 问就是为了美观  */
        if (this.tableOption.length < 7){
          for (let i = 0; i < 7; i++) {
            this.tableOption.push({
              DataList: [],
            });
            if (this.tableOption.length >= 7) break;
          }
        }
      }else{
        this.tableOption.forEach((item) => {
          data.forEach((_item) => {
            if (item.IndexCode === _item.IndexCode) {
              item.DataList = item.DataList.concat(_item.DataList);
            }
          });
        });
      }

      // 合并所有日期
      let arr = this.tableOption.map((item) => item.DataList);
      let obj = [];
      arr.forEach((dataList) => {
        obj.push(...dataList.map((item) => item.DataTime));
      });
      // 日期去重倒序排序
      this.dateArr = [...new Set(obj)].sort().reverse();
      //数据最大长度小于13个 追加数据满13个 别问 问就是为了美观
      if (this.dateArr.length < 13){
        for (let i = 0; i < 13; i++) {
          this.dateArr.push("");
          if (this.dateArr.length >= 13) break;
        }
      }
    },
  },
};
</script>
<style lang="scss" scoped>
@import "../css/coalCommon.scss";
</style>
