<template>
  <!-- 年度预测数据 - littlegreen - 补充form-label -->
  <div :class="className" :style="{ height: height, width: width }">
    <div class="select-container">
      <el-form
        style="
          display: grid;
          grid-template-columns: 1fr 1fr 1fr;
          align-items: center;
          grid-gap: 20px;
        "
        label-width="120px"
      >
        <el-form-item label="企业" style="margin-bottom: 0">
          <el-select v-model="selectedEnterprise" style="width: 100%">
            <el-option
              v-for="item in uniqueEnterprises"
              :key="item.enterpriseName"
              :value="item.enterpriseName"
            >
              {{ item.enterpriseName }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="评估指标" style="margin-bottom: 0">
          <el-select v-model="selectedDataKey" style="width: 100%">
            <el-option
              v-for="key in dataKeys"
              :key="key"
              :value="key"
              :label="keyToChinese[key]"
            >
              {{ keyToChinese[key] }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年度" style="margin-bottom: 0">
          <el-select v-model="selectedYear" style="width: 100%">
            <el-option v-for="year in availableYears" :key="year" :value="year">
              {{ year }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预测模型" style="margin-bottom: 0">
          <el-select v-model="selectedModel" style="width: 100%">
            <el-option
              v-for="model in availableModels"
              :key="model"
              :value="model"
            >
              {{ model }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报警阈值" style="margin-bottom: 0">
          <el-input
            v-model="errorVal"
            placeholder="报警阈值"
            clearable
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="采用预测模型:" style="margin-bottom: 0">
          <div style="display: inline; padding-left: 10px">
            {{ selectedModel }}
          </div>
        </el-form-item>
        <el-form-item style="margin-bottom: 0">
          <el-button
            type="primary"
            @click="updateChart"
            size="mini"
            >计算</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div ref="chart" :style="{ height: height, width: width }"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { listPredict } from "@/api/predict_year/predict_year";
import { listBase_data_year } from "@/api/base_data_year/base_data_year";
require("echarts/theme/macarons");
import resize from "./mixins/resize";
import basicInfoFormVue from '../tool/gen/basicInfoForm.vue';
import { Decimal } from "decimal.js";
export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "400px",
    },
  },
  data() {
    return {
      errorVal: null,
      chart: null,
      chartData: [],
      base_data_yearData: [],
      selectedDataKey: "energyConsumePredict", // 默认第一个

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

      keyToChineseTruth: {
        totalIndustrialValuePredict: "工业总产值实际数据",
        taxableIncomePredict: "应税收入实际数据",
        paidTaxPredict: "实缴税金实际数据",
        energyConsumePredict: "能源消费量实际数据",
        powerConsumePredict: "电力消费量实际数据",
        fundingConsumePredict: "研发经费实际数据",
      },
      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_year(this.queryParams).then((response) => {
            this.base_data_yearData = response.rows;
            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();
    },
    // littlegreen 检验是否正确填写预警值
    checkErrorVal(number) {
      let val = parseFloat(number);
      let flag;
      if (!number) {
        return (flag = 0);
      }
      if (isNaN(val)) {
        this.$message({
          message: "请输入有效的数字。",
          type: "error",
        });
        return (flag = 2);
      }
      return (flag = 1);
    },
    updateChart() {
      // littlegreen - 如果预警值不为空，判断是否为数字，不是数字就return
      const that = this;
      let flag = this.checkErrorVal(this.errorVal);
      if (flag == 2) {
        return;
      }
      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.year + "年");
      let yValues;

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

      // 处理实际数据
      const base_data_yearFiltered = this.base_data_yearData.filter(
        (item) =>
          item.year === this.selectedYear &&
          item.enterpriseName === this.selectedEnterprise
      );
      const base_data_yearXValues = base_data_yearFiltered.map(
        (item) => item.year + "年"
      );
      let base_data_yearYValues;

      switch (this.selectedDataKey) {
        case "totalIndustrialValuePredict":
          base_data_yearYValues = base_data_yearFiltered.map((item) => [
            item.totalIndustrialValue,
            item.year,
          ]);
          break;
        case "taxableIncomePredict":
          base_data_yearYValues = base_data_yearFiltered.map((item) => [
            item.taxableIncome,
            item.year,
          ]);
          break;
        case "paidTaxPredict":
          base_data_yearYValues = base_data_yearFiltered.map((item) => [
            item.paidTax,
            item.year,
          ]);
          break;
        case "powerConsumePredict":
          base_data_yearYValues = base_data_yearFiltered.map((item) => [
            item.powerConsume,
            item.year,
          ]);
          break;
        case "energyConsumePredict":
          base_data_yearYValues = base_data_yearFiltered.map((item) => [
            item.energyConsume,
            item.year,
          ]);
          break;
        case "fundingConsumePredict":
          base_data_yearYValues = base_data_yearFiltered.map((item) => [
            item.funding,
            item.year,
          ]);
          break;
      }

      // littlegreen - 获取预警的markArea
      function getErrorArray(flag, monthYValues, yValues, xValues) {
        // console.log(yValues, monthYValues,flag)
        if (flag == 0) {
          return [];
        }
        const errorArray = [];
        const error = new Decimal(that.errorVal);
        monthYValues.forEach(monthYValue => {
          const yVal = new Decimal(monthYValue[0]);
          const month = monthYValue[1];
          const baseData = yValues.find((base) => base[1] === month);
          if (baseData) {
            const baseVal = new Decimal(baseData[0]);
            // console.log(yVal,baseVal)
            const difference = yVal.minus(baseVal);
            // console.log(difference.toNumber(),error)
            if (difference.gt(error)) {
              errorArray.push([
                {
                  x: 10 + (80 / (xValues.length)) * (xValues.indexOf(month+"年")) + "%",
                },
                {
                  x: 10 + (80 / (xValues.length)) * (xValues.indexOf(month+"年") + 1) + "%",
                },
              ]);
            }
          }
        });
        return errorArray;
      }
      yValues.sort((a, b) => {
        let aValue = new Decimal(a[1]);
        let bValue = new Decimal(b[1]);
        return aValue.cmp(bValue); // cmp方法用于比较两个Decimal对象
      });
      base_data_yearYValues.sort((a, b) => {
        let aValue = new Decimal(a[1]);
        let bValue = new Decimal(b[1]);
        return aValue.cmp(bValue); // cmp方法用于比较两个Decimal对象
      });
      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) => [
              value[1]+"年",
              value[0]
              ]), // 根据多少年去获取对应的数据
            color: "#4CAF50",
            // itemStyle: {
            //   // color: "rgba(245,0,0,0.6)",
            //   normal: {
            //     color: function (params) {
            //       const value = params.data[1];
            //       if (flag == 1) {
            //         if (value >= that.errorVal)
            //           //预警值有值
            //           return "blue";
            //       }
            //       return "#4CAF50";
            //     },
            //   },
            // },
          },
          {
            name:
              this.selectedEnterprise +
              " " +
              this.selectedYear +
              "年" +
              this.keyToChineseTruth[this.selectedDataKey],
            type: "line",
            data: base_data_yearYValues.map((value) => [
              value[1]+"年",
              value[0]
            ]),
            color: "#FF5722",
            markArea: {
              itemStyle: {
                color: "rgba(255, 173, 177, 0.4)",
              },
              data: getErrorArray(flag, base_data_yearYValues, yValues, xValues),
            },
            // itemStyle: {
            //   // color: "rgba(245,0,0,0.6)",
            //   normal: {
            //     color: function (params) {
            //       const value = params.data[1];
            //       if (flag == 1) {
            //         if (value >= that.errorVal)
            //           //预警值有值
            //           return "blue";
            //       }
            //       return "#FF5722";
            //     },
            //   },
            // }
          },
        ],
      });
    },
  },
  watch: {
    // littlegreen - 不用实时更新
    // 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>
