<template>
  <div style="padding: 8px 20px 20px;">
    <el-collapse ref="collapseRef" v-model="activeShowList" @change="collapseChange">
      <template v-for="(val,key, index) of chartDataLit">
        <el-collapse-item :ref="key" :title="`【${val && val.title || ''}】${val && val.serverIp || ''}`" :name="val && val.title || ''">
          <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">
<!--                <span class="w50 disInlineBlock" style="color: #C0C4CC;">{{item}}</span><span class="w50">{{val && val.formModel[key] || '-'}}</span>-->
                <div class="disInlineBlock" style="width: 120px;color: #C0C4CC;">{{item}}</div>
                <div style="width: calc(100% - 120px);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: 250px;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, 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>
      </template>
    </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);
        },
        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) {
        const allKeys = Object.keys(chartList);
        const hasKeys = allKeys.filter(key => chartList[key].type === 'net'); // 含'net'的键
        const noKeys = allKeys.filter(key => chartList[key].type !== 'net'); // 不含'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, unit) {
        this.$emit("chartFnEvent", valData, funcName, tabName, unit);
        // // 检查函数是否存在，避免报错
        // if (typeof this[funcName] === 'function') {
        //   // 调用实际函数，并传递参数（如选中的值、当前项）
        //   // this[funcName]({startTime: valData[0], endTime: valData[1]});
        // } else {
        //   console.warn(`函数 ${funcName} 未定义`);
        // }
      }
    }
  }
</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>
