<template>
  <div style="padding: 8px 20px 20px;">
    <el-collapse ref="collapseRef" id="collapseTolDom" v-model="activeShowList" @change="collapseChange">
      <el-collapse-item :ref="key" v-for="(val,key, index) of chartDataLit" :title="`【${val && val.title || ''}】`" :name="key || ''" :key="key">
        <template slot="title">
          <span>{{`【${val && val.title || ''}】${val && val.serverIp || ''}`}}</span>
          <span class="disInlineBlock" :title="val.interfaceNameRemark" :style="fnStyleWid(val.title,val.serverIp)">
            {{val.interfaceNameRemark}}
          </span>
        </template>
        <div class="mt10 w100">
          <div class="w100 plr-20" style="font-size: 14px">
            <div v-for="(item,key,index) of val && val.formList || []" :key="`${key}-${index}`"  class="w50 disInlineBlock p10">
              <div class="disInlineBlock" style="width: 130px;color: #C0C4CC;">{{item}}</div>
              <div style="width: calc(100% - 130px);vertical-align: top;" class="disInlineBlock">{{val && val.formModel[key] || '-'}}</div>
            </div>
          </div>
          <div v-for="(item, chartIndex) of val && val.echartList || []" :key="`div-${val && val.title || ''}-${item && item.title || chartIndex}-${index}`" class="w100 mt20 mb20" style="height: 200px;border-top: 1px solid #d8dce5">
            <template v-if="item && item.title">
              <EchartsLine class="w100 h100" :key="`chart-${val && val.title || ''}-${item && item.title || ''}-${index}`" :lineData="item && item.dataVal || {}" :dateDataTrans="item && item.dateDataTrans || {}" :dateShowType="item && item.dateShowType || 'datetimerange'" :title="item && item.title || '图表数据'" :chartData="(valData, unit) => chartDataEvent(valData, item.fnEvent,val.title, key, unit)"></EchartsLine>
            </template>
            <div v-else class="w100 h100 flex-center" style="background: #f5f7fa;">
              <div class="loading-placeholder">
                <i class="el-icon-loading"></i>
                <span>加载中...</span>
              </div>
            </div>
          </div>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script setup>
  import EchartsLine from "@/components/echartsList/line.vue";
  export default {
    name: 'SecondAutoFind',
    components: {EchartsLine},
    props: {
      secondChartList: {
        type: Object,
        default: () => {}
      },
      activeNames: {
        type: Array,
        default: () => []
      },
    },
    watch: {
      secondChartList: {
        handler(val) {
          this.chartDataLit = this.fnFilterData(val);
          // 因加入了fnFilterData方法进行了筛选排序，导致默认打开的不为原指定的元素了，这里就没用了
          // this.activeShowList = val;
        },
        deep: true,
        immediate: true
      },
    },
    data() {
      return {
        activeShowList: [],
        chartDataLit: {},
        lastModel: [],
        scrollTimeout: null,
        deepCopyModel: [],
      }
    },
    created() {
      this.deepCopyModel = [];
    },
    methods: {
      simulateScroll(event) {
        if (!this.scrollTimeout) {
          this.scrollTimeout = setTimeout(() => {
            this.checkElementsInViewport();
            this.scrollTimeout = null;
          }, 200); // 200ms 节流间隔
        }
      },
      checkElementsInViewport() {
        // 获取每个折叠面板的位置信息
        Object.keys(this.$refs).forEach(key => {
          if (key !== 'collapseRef' && this.$refs[key]) {
            const ref = this.$refs[key];
            if (Array.isArray(ref)) {
              ref.forEach(item => {
                if (item.$el) {
                  const rect = item.$el.getBoundingClientRect();
                  const windowHeight = (window.innerHeight || document.documentElement.clientHeight) + 800;
                  const windowWidth = window.innerWidth || document.documentElement.clientWidth;
                  if (rect.top <= windowHeight && rect.left >= 0 && rect.right <= windowWidth) {
                    if (this.activeShowList.includes(key)) {
                      this.lastModel.push(key);
                      this.lastModel = Array.from(new Set(this.lastModel));
                      if (this.chartDataLit[key].echartList && !this.chartDataLit[key].echartList[0]) {
                        this.collapseChange(null, this.lastModel);
                      }
                    }
                  }
                }
              })
            } else if (ref.$el) {
              const rect = ref.$el.getBoundingClientRect();
              const windowHeight = window.innerHeight || document.documentElement.clientHeight;
              const windowWidth = window.innerWidth || document.documentElement.clientWidth;
              if (rect.top <= windowHeight && rect.left >= 0 && rect.right <= windowWidth) {
                if (this.activeShowList.includes(key)) {
                  this.lastModel.push(key);
                  this.lastModel = Array.from(new Set(this.lastModel));
                  if (this.chartDataLit[key].echartList && !this.chartDataLit[key].echartList[0]) {
                    this.collapseChange(null, this.lastModel);
                  }
                }
              }
            }
          }
        })
      },
      // 筛选
      fnFilterData(chartList) {
        if (!chartList) return {};
        const allKeys = Object.keys(chartList);
        const hasKeys = allKeys.filter(key => chartList[key].expand); // 含'net'的键
        const noKeys = allKeys.filter(key => !chartList[key].expand); // 不含'net'的键
        const newObj = {};
        // 先添加含'net'的键（保持原顺序）
        hasKeys.forEach(key => {
          newObj[key] = chartList[key];
        });
        // 再添加不含'net'的键（保持原顺序）
        noKeys.forEach(key => {
          newObj[key] = chartList[key];
        });
        // 默认打开hasKeys的所有元素
        if (newObj && Object.keys(newObj).length > 0) {
          let selectData = this.deepCopyModel && this.deepCopyModel.length > 0 ? this.deepCopyModel : hasKeys && hasKeys.length > 0 ? hasKeys : [Object.keys(newObj)[0]];
          this.lastModel = this.lastModel.length > 0 ? this.lastModel : selectData.length > 3 ? [selectData[0], selectData[1], selectData[2]] : selectData;
          this.collapseChange(selectData, this.lastModel);
        }
        return newObj;
      },
      collapseChange(val,model) {
        if (val && val.length > 0) {
          let collAll = val.concat(this.activeShowList);
          this.activeShowList = Array.from(new Set(collAll));
        }
        if (val && val.length > 0 && !model) {
          this.lastModel = this.lastModel.filter(item => val.includes(item));
          this.deepCopyModel = JSON.parse(JSON.stringify(this.activeShowList));
          this.simulateScroll();
        } else if (model && model.length > 0) {
          this.$emit("collapseChangeData", this.lastModel);
        } else if (val && val.length > 0) {
          let totalVal = this.lastModel.filter(item => val.includes(item));
          this.$emit("collapseChangeData", totalVal);
        }
      },
      chartDataEvent(valData, funcName, tabName, key, unit) {
        this.$emit("chartFnEvent", valData, funcName, tabName, key, unit);
        // // 检查函数是否存在，避免报错
        // if (typeof this[funcName] === 'function') {
        //   // 调用实际函数，并传递参数（如选中的值、当前项）
        //   // this[funcName]({startTime: valData[0], endTime: valData[1]});
        // } else {
        //   console.warn(`函数 ${funcName} 未定义`);
        // }
      },
      fnStyleWid(val1,val2) {
        let style = {'overflow': 'hidden', 'text-overflow': 'ellipsis', 'white-space': 'nowrap', 'padding-left': '20px'};
        let num1 = val1 ? val1.length : 0;
        let num2 = val2 ? val2.length : 0;
        let count = ((num1+num2)*8)+ 32 + 60;
        style['width'] = `calc(100% - ${count}px)`;
        return style;
      },
    }
  }
</script>
<style scoped>
  ::v-deep .el-collapse-item__header {
    background-color: #d4e3fc!important;
    /*color: #fff!important;*/
    padding-left: 20px;
    font-size: 1rem;
  }
  .loading-placeholder {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    font-size: 1.1rem;
  }
</style>
