<template>
  <div class="content">
    <div class="content-echarts">
      <div v-for="(chart, index) in chartOptions" :key="index">
        <div class="content-header">
          <div class="verline"></div>
          <span>{{ chart.title }}</span>
        </div>
        <div :ref="`chartContainer${index}`" class="chart-container"></div>
      </div>
    </div>
    <div class="content-table">
      <ComTable
        :columns="columns"
        :table-data="tableData"
        @handlePagesizeChange="handlePagesizeChange"
        ref="comTable"
        :table-option="tableOption"
        :page-option="pageOption"
      ></ComTable>
    </div>
  </div>
</template>
<script>
import { processData } from '@/utils/dealWithData'
import { postReq } from '@/request/api'
import ComTable from '@/components/ComTable'
// import { debounce } from 'lodash'; 
export default {
  name: 'StatisicalAnView',
  components: { ComTable },
  props: {
    pageOption: {
      type: Object,
      default: () => ({}), // 默认空对象
      required: false // 非必须
    },
    tableInfo: {
      type: Object,
      default: () => ({}), // 默认空对象
      required: false // 非必须
    },
    columns: {
      type: Array,
      default: () => [], // 默认空对象
      required: false // 非必须
    },
    chartOptions: {
      type: Array,
      default: () => [], // 默认空对象
      required: false // 非必须
    },
    chartData: {
      type: Object,
      default: () => ({}), // 默认空对象
      required: false // 非必须
    },
    chartDatav: {
      type: Object,
      default: () => ({}), // 默认空对象
      required: false // 非必须
    },
    tableData: {
      type: Array,
      default: () => [] // 默认空对象
    },
    yAxisOption:{
      type: Array,
      default: () => [] // 默认空对象
    }
  },
  data() {
    return {
      paramsDate: {},
      tableOption: {
        scroll: {
          x: 1500
        },
        select: false
      },

      chartInstances: [] // 存储 ECharts 实例
    }
  },
  watch: {
    chartData: {
      handler(newVal) {
        if (newVal && Object.keys(newVal).length > 0) {
          this.$nextTick(() => {
            // this.destroyCharts(); // 先销毁旧图表
            this.initBarCharts(); // 重新初始化
          });
        }
      },
      deep: true,
      // immediate: true,
    },
    chartDatav: {
      handler(newVal) {
        if (newVal && Object.keys(newVal).length > 0) {
          this.$nextTick(() => {
            // this.destroyCharts(); // 先销毁旧图表
            this.initLineCharts(); // 重新初始化
          });
        }
      },
      deep: true,
      // immediate: true,
    },
  },
  mounted() {
    window.addEventListener('resize', this.handleResize);
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.handleResize);
    this.destroyCharts();
  },
  methods: {
    destroyCharts() {
      this.chartInstances.forEach((chart) => {
        if (chart && !chart.isDisposed()) {
          chart.dispose(); // 销毁旧图表
        }
      });
      this.chartInstances = []; // 清空实例数组
    },
    // 公共 ECharts 配置
    getCommonOption(option, dataKeys, isLineChart = false) {
      console.log(option,"ooooooooooooo")
      return {
        animation: false,
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
        },
        legend: {
          top: 20,
          textStyle: { color: '#fff' },
        },
        grid: {
          left: '3%',
          right: '3%',
          bottom: '5%',
          // containLabel: true,
        },
        xAxis: {
          type: 'category',
          data: isLineChart ? this.generateTimePoints() : processData(this.chartData, dataKeys).dates,
          axisLine: { lineStyle: { color: '#fff' } },
          axisLabel: { color: '#fff' },
        },
        yAxis: option.yAxisOption &&option.yAxisOption.length?option.yAxisOption:
          {
            type: 'value',
            splitLine: { lineStyle: { type: 'dashed', color: '#435463' } },
            axisLabel: { color: '#fff' },
          },
      };
    },
    generateTimePoints() {
      const timePoints = []

      for (let hour = 0; hour <= 24; hour++) {
        for (let minute = 0; minute < 60; minute += 10) {
          // 处理24:00的特殊情况
          if (hour === 24 && minute === 0) {
            timePoints.push('24:00')
            break
          }

          // 格式化小时和分钟，确保两位数
          const formattedHour = hour.toString().padStart(2, '0')
          const formattedMinute = minute.toString().padStart(2, '0')

          timePoints.push(`${formattedHour}:${formattedMinute}`)
        }
      }

      return timePoints
    },
    // 初始化柱状图
    initBarCharts() {
      
      this.chartOptions.forEach((option, index) => {
        if (option.type === 'bar') {
          const dom = this.$refs[`chartContainer${index}`]?.[0];
          if (!dom) return;
 
          const chart = this.$echarts.init(dom);
          this.chartInstances.push(chart);
 
          const dataKeys = option.infoKeys.map((item) => item.key);
          const commonOption = this.getCommonOption(option, dataKeys);
 
          chart.setOption({
            
            ...commonOption,
            series: option.infoKeys.map((info, i) => ({
              name: info.label,
              type: 'bar',
              barWidth: '20%',
              itemStyle: {
                borderRadius: [0, 0, 0, 0],
                color: info.lineColor,
              },
              index:option.yAxisOption&&option.yAxisOption.length?i:1,

              data: processData(this.chartData, dataKeys).values[i],
            })),
          });
        }
      });
    },
 
    // 初始化折线图
    initLineCharts() {
      this.chartOptions.forEach((option, index) => {
        if (option.type === 'line') {
          const dom = this.$refs[`chartContainer${index}`]?.[0];
          if (!dom) return;
 
          const chart = this.$echarts.init(dom);
          this.chartInstances.push(chart);
 
          const dataKeys = option.infoKeys.map((item) => item.key);
          const commonOption = this.getCommonOption(option, dataKeys, true);
 
          chart.setOption({
            ...commonOption,
            dataZoom: [
              {
                type: 'slider',
                show: true,
                xAxisIndex: 0,
                start: 0,
                end: 100,
                height: 20,
                bottom: 10,
              },
              {
                type: 'inside',
                xAxisIndex: 0,
                start: 0,
                end: 20,
              },
            ],
            series: option.infoKeys.map((info, i) => ({
              name: info.label,
              type: 'line',
              smooth: true,
              showSymbol: false,
              itemStyle: { color: info.lineColor },
              areaStyle: {
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    { offset: 0, color: info.colorStart },
                    { offset: 1, color: info.colorEnd },
                  ],
                },
              },
              index:option.yAxisOption&&option.yAxisOption.length?i:1,

              data: this.chartDatav[info.key],
            })),
          });
        }
      });
    },
    handleResize () {
      this.chartInstances.forEach((chart) => chart && chart.resize());
      // this.handleResize = debounce(this.resize, 300);
     
    },
    resize() {
      this.chartInstances.forEach((chart) => chart && chart.resize());
    },
   

    handlePagesizeChange(pageOption) {
      this.$emit('pagesizeChange', pageOption)
    }
  },
  
  
}
</script>

<style lang="scss" scoped>
.content {
  height: calc(100% - 10px);
  overflow: scroll;
}
.content-echarts {
  display: flex;
  flex-wrap: wrap;
  height: calc(750px - 38px);
  color: #fff;

  & > div {
    padding: 20px 5px;
    // margin-right: 10px;
    background-color: rgba(33, 105, 195, 0.12);
    border-radius: 2px;
    width: calc(50% - 15px);
    height: calc(50% - 10px);

    &:nth-child(odd) {
      margin-right: 10px;
    }
    .chart-container {
      width: 100%;
      height: 100%;
    }

    .content-header {
      font-size: 12px;
      display: flex;
      align-items: center;
      margin-left: 3%;
      .verline {
        margin-right: 10px;
        background: linear-gradient(
            180deg,
            rgba(0, 230, 172, 1) 0%,
            rgba(0, 210, 255, 1) 98.78%,
            rgba(0, 210, 255, 1) 100%
          ),
          rgba(1, 223, 239, 1);
        width: 4px;
        height: 20px;
        border-radius: 6px;
      }
    }
  }
}

.content-table {
  margin-top: 20px;
  min-height: 500px;
  width: 100%;
  padding-right: 10px;
  padding-bottom: 10px;

  .comtable{
    height:610px;
    // overflow: scroll;
  }
}
</style>
