<template>
    <div :class="className" :style="{ height: height, width: width }">
      <div class="select-container">
        <el-select v-model="selectedEnterprise" @change="updateChart">
          <el-option v-for="item in uniqueEnterprises" :key="item.enterpriseName" :value="item.enterpriseName">
            {{ item.enterpriseName }}
          </el-option>
        </el-select>
        <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-select v-model="selectedModel" @change="updateChart">
          <el-option v-for="model in availableModels" :key="model" :value="model">
            {{ model }}
          </el-option>
        </el-select>
      <div style="display: inline; padding-left: 10px;">采用的预测模型：{{ selectedModel }}</div>
      </div>
      <div ref="chart" :style="{ height: height, width: width }"></div>
    </div>
  </template>

  <script>
  import * as echarts from 'echarts'
  import { listPredict } from "@/api/predict_season/predict_season";
  import { listBase_data_season } from "@/api/base_data_season/base_data_season";
  require('echarts/theme/macarons')
  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: [],
        base_data_seasonData: [],
        selectedDataKey: 'taxableIncomePredict',// 默认第一个

        dataKeys: [
        //   'totalIndustrialValuePredict',
          'taxableIncomePredict',
          'paidTaxPredict',
        //   'energyConsumePredict',
        ],
        keyToChinese: {
        //   'totalIndustrialValuePredict': '工业总产值预测',
          'taxableIncomePredict': '应税收入预测',
          'paidTaxPredict': '实缴税金预测',
        //   'energyConsumePredict': '能源消费量预测'
        },

        keyToChineseTruth: {
          'totalIndustrialValuePredict': '工业总产值实际数据',
          'taxableIncomePredict': '应税收入实际数据',
          'paidTaxPredict': '实缴税金实际数据',
          'energyConsumePredict': '能源消费量实际数据'
        },
        selectedYear: null,
        selectedEnterprise: null,
        selectedModel: null,
        queryParams: {
          pageNum: 1,
          pageSize: 2000000,
          enterpriseName: this.selectedEnterprise,
          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: this.selectedYear,
          month: null,
          model: null
        },
        availableYears: [],
        uniqueEnterprises: [],
        availableModels: []
      }
    },
    mounted() {
      this.$nextTick(() => {
        this.fetchData();
      })
    },
    beforeDestroy() {
      if (this.chart) {
        this.chart.dispose();
      }
    },
    methods: {
      fetchData() {
        listPredict(this.queryParams).then(response => {
          this.chartData = response.rows;
          //console.log(this.chartData)
          this.availableYears = [...new Set(this.chartData.map(item => item.year))];
          this.selectedYear = this.availableYears[0] || null;
          this.uniqueEnterprises = [...new Set(this.chartData.map(item => ({enterpriseName: item.enterpriseName})))];
          this.uniqueEnterprises = Array.from(new Set(this.chartData.map(item => item.enterpriseName))).map(name => ({enterpriseName: name}));
          this.selectedEnterprise = this.uniqueEnterprises.length > 0 ? this.uniqueEnterprises[0].enterpriseName : null;
          this.availableModels = [...new Set(this.chartData.map(item => item.model))];
          this.selectedModel = this.availableModels[0] || null;

          // 获取实际数据
          listBase_data_season(this.queryParams).then(response => {
            this.base_data_seasonData = response.rows;
            console.log('vvv' + this.base_data_seasonData.length) 
            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.filter(item =>
        item.year === this.selectedYear &&
        item.enterpriseName === this.selectedEnterprise &&
        item.model === this.selectedModel
      );
      //const xValues = filteredData.map(item => item.month + '月');
      const xValues = ['1季度', '2季度', '3季度', '4季度'];
      let yValues;

      // 根据选择的不同预测数据 key 获取对应的预测值
      switch (this.selectedDataKey) {
        case 'totalIndustrialValuePredict':
          yValues = filteredData.map(item => [item.totalIndustrialValuePredict, item.season]);
          break;
        case 'taxableIncomePredict':
          yValues = filteredData.map(item => [item.taxableIncomePredict, item.month]);
          break;
        case 'paidTaxPredict':
          yValues = filteredData.map(item => [item.paidTaxPredict, item.month]);
          break;
        case 'energyConsumePredict':
          yValues = filteredData.map(item => [item.energyConsumePredict, item.season]);
          break;
        case 'powerConsumePredict':
            yValues = filteredData.map(item => [item.powerConsumePredict, item.season]);
            break;
        case 'fundingConsumePredict':
            yValues = filteredData.map(item => [item.fundingConsumePredict, item.season]);
            break;
      }

      // console.log('jjj', yValues);

     // 处理实际数据
      const base_data_seasonFiltered = this.base_data_seasonData.filter(item =>
        item.year === this.selectedYear &&
        item.enterpriseName === this.selectedEnterprise
      );
      // const base_data_seasonXValues = base_data_monthFiltered.map(item => item.month + '月');
      let base_data_seasonYValues;

      switch (this.selectedDataKey) {
        case 'totalIndustrialValuePredict':
          base_data_seasonYValues = base_data_seasonFiltered.map(item => [item.totalIndustrialValue, item.month]);
          break;
        case 'taxableIncomePredict':
          base_data_seasonYValues = base_data_seasonFiltered.map(item => [item.taxableIncome, item.season]);
          break;
        case 'paidTaxPredict':
          base_data_seasonYValues = base_data_seasonFiltered.map(item => [item.paidTax, item.season]);
          break;
        case 'powerConsumePredict':
          base_data_seasonYValues = base_data_seasonFiltered.map(item => [item.powerConsume, item.month]);
          break;
        case 'energyConsumePredict':
          base_data_seasonYValues = base_data_seasonFiltered.map(item => [item.energyConsume, item.month]);
          break;
      }

      this.chart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: [
            this.selectedEnterprise + ' ' + this.selectedYear + '年' + this.keyToChinese[this.selectedDataKey],
            this.selectedEnterprise + ' ' + this.selectedYear + '年' + this.keyToChineseTruth[this.selectedDataKey],
          ]
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: xValues,
          axisLabel: {
            fontSize: 12
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [
           {
             name: this.selectedEnterprise + ' ' + this.selectedYear + '年' + this.keyToChinese[this.selectedDataKey],
             type: 'line',
             data: yValues.map((value) => [xValues[value[1] - 1], value[0]]),// 根据多少季度去获取对应的数据
             color: '#4CAF50'
           },
          {
            name: this.selectedEnterprise + ' ' + this.selectedYear + '年' + this.keyToChineseTruth[this.selectedDataKey],
            type: 'line',
            data: base_data_seasonYValues.map((value) => [xValues[value[1] - 1], value[0]]),
            color: '#FF5722'
          }
        ]
      });
    }
    }
    ,
    watch: {
      selectedDataKey() {
        this.updateChart();
      },
      selectedYear() {
        this.updateChart();
      },
      selectedEnterprise() {
        this.updateChart();
      }
    }
  }
  </script>

  <style scoped>
  .select-container {
    margin: 10px 5px;
    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>
