<template>
    <div :class="className" :style="{ height: height, width: width }">
      <div class="select-container">
  
      <el-select v-model="selectedDataKey" @change="updateChart">
        <el-option v-for="key in dataKeys" :key="key" :value="key" :label="keyToChinese[key]">
          {{ keyToChinese[key] }}
        </el-option>
      </el-select>
      <el-select v-model="selectedYear" @change="updateChart">
        <el-option v-for="year in availableYears" :key="year" :value="year">
          {{ year }}
        </el-option>
      </el-select>
      <el-input
            v-model="selectedRange"
            placeholder="请设置数据分布区间"
            clearable
            style="width: 180px;"
          />
      </div>
      <div ref="chart" :style="{ height: height, width: width }"></div>
    </div>
  </template>
  
  <script>
  import * as echarts from 'echarts'
  import { listBase_data_year } from "@/api/base_data_year/base_data_year";
  require('echarts/theme/macarons') // echarts theme
  import resize from './mixins/resize'
  
  export default {
    mixins: [resize],
    props: {
      className: {
        type: String,
        default: 'chart'
      },
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: String,
        default: '400px'
      }
    },
    data() {
      return {
        chart: null,
        chartData: [],
        selectedDataKey: 'energyConsume', // 默认选择的字段
        dataKeys: [
          // 'code',
          // 'createBy',
          // 'createTime',
          'landArea',
          'totalIndustrialValue',
          // 'enterpriseName',
          'gdp',
          'taxableIncome',
          // 'id',
          'paidTax',
          // 'location',
          // 'mainBusiness',
          'mainBusinessIncome',
          'employeeNumber',
          'profit',
          'ownerEquity',
          'funding',
          // 'remark',
          'energyConsume',
          // 'updateBy',
          // 'updateTime',
          // 'year'
        ], // 可选项,
  
        keyToChinese: {
          'landArea': '用地面积',
          'totalIndustrialValue': '工业总产值',
          'gdp': '工业增加值',
          'taxableIncome': '应税收入',
          'paidTax': '实缴税金',
          'mainBusinessIncome': '主营业务收入',
          'employeeNumber': '从业人员数',
          'profit': '利润总额',
          'ownerEquity': '所有者权益',
          'funding': '研发经费',
          'energyConsume': '能源消费量',
        },
  
        selectedYear: null,
        queryParams: {
          pageNum: 1,
          pageSize: 2000000,  //  默认 2000000 条(全部一次性数据)
          enterpriseName: null,
          location: null,
          code: null,
          mainBusiness: null,
          landArea: null,
          totalIndustrialValue: null,
          gdp: null,
          taxableIncome: null,
          paidTax: null,
          mainBusinessIncome: null,
          employeeNumber: null,
          profit: null,
          ownerEquity: null,
          funding: null,
          energyConsume: null,
          year: null,
          month: null
        },
        availableYears: [],
        selectedRange: null
      }
    },
    mounted() {
      this.$nextTick(() => {
        this.fetchData();
      })
    },
    beforeDestroy() {
      if (this.chart) {
        this.chart.dispose();
      }
    },
    methods: {
      fetchData() {
        listBase_data_year(this.queryParams).then(response => {
          this.chartData = response.rows;
          this.availableYears = [...new Set(this.chartData.map(item => item.year))];
          this.selectedYear = this.availableYears[0] || null;
          this.initChart();
        }).catch(error => {
          console.error('Error fetching data:', error);
        });
      },
      initChart() {
        if (this.chart) {
          this.chart.dispose();
        }
        this.chart = echarts.init(this.$refs.chart, 'macarons');
        this.updateChart();
      },
      updateChart() {
        if (!this.chart) {
          return;
        }
        let filteredData = this.chartData;
        if (this.selectedYear) {
          filteredData = filteredData.filter(item => item.year === this.selectedYear);
        }
        const companyNames = filteredData.map(item => item.enterpriseName);
      
        const values = filteredData.map(item => item[this.selectedDataKey]);
  
        const minVal = 0;
        const maxVal = Math.max(...values);
  
        const binCount = Math.ceil((maxVal - minVal) / Number(this.selectedRange));
  
        // 生成区间标签和频次
        const histogramData = [];
        for (let i = 0; i < binCount; i++) {
          const x0 = minVal + i * Number(this.selectedRange);
          const x1 = Math.min(x0 + Number(this.selectedRange), maxVal);
          const label = `${x0}-${x1}`;
          const count = values.filter(value => value >= x0 && value < x1).length;
          histogramData.push({ name: label, value: count });
        }
  
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          legend: {
            data: [this.selectedYear + '年 ' + this.keyToChinese[this.selectedDataKey] + '统计']
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: histogramData.map(item => item.name),
            axisLabel: {
              fontSize: 12
            }
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            name: this.selectedYear + '年 ' + this.keyToChinese[this.selectedDataKey] + '统计',
            type: 'bar',
            itemStyle: {
                color: 'rgba(245,0,0,0.6)',
              },
            data: histogramData.map(item => item.value)
          }]
        };
  
        this.chart.setOption(option);
      }
    },
    watch: {
      selectedDataKey() {
        this.updateChart();
      },
      selectedYear() {
        this.updateChart();
      },
      selectedRange() {
        setTimeout(() => this.updateChart(), 2000);
      },
    }
  }
  </script>
  <style scoped>
  .select-container {
    margin: 10px 0;
    font-size: 16px; /* 调整字号大小 */
  }
  
  .select-container select {
    padding: 10px 20px; /* 增加内边距 */
    margin-right: 10px; /* 增加右边距 */
    border: 1px solid #121315; /* 蓝色边框 */
    border-radius: 4px; /* 圆角边框 */
    background-color: white; /* 背景色 */
    color: #121315; /* 文字颜色 */
    font-size: 16px; /* 调整字号大小 */
    cursor: pointer; /* 鼠标悬停时的指针样式 */
    outline: none; /* 移除焦点时的轮廓 */
  }
  
  .select-container select:hover {
    border-color: #1a7cc8; /* 鼠标悬停时的边框颜色 */
  }
  
  .select-container select:focus {
    border-color: #121315; /* 焦点时的边框颜色 */
    box-shadow: 0 0 0 2px rgba(64, 159, 255, 0.2); /* 焦点时的阴影效果 */
  }
  </style>
  