<template>
  <div
    :class="className"
    :style="{ height: '100%', width: width, padding: '15px' }"
  >
    <!-- 招商评估 -->
    <div class="select-container">
      <el-form
        :model="form"
        :rules="rules"
        ref="ruleForm"
        style="
          display: grid;
          grid-template-columns: 1fr 1fr;
          align-items: center;
          grid-gap: 5px;
        "
      >
        <el-form-item
          label="新增企业年产值"
          label-width="200px"
          prop="annualOutputValue"
        >
          <div style="display: flex; align-items: center">
            <el-input
              v-model.number="form.annualOutputValue"
              placeholder="请输入企业年产值"
              clearable
            />
            <p
              style="
                flex: 0 0 auto;
                margin: 0 10px;
                width: 30px;
                text-align: center;
              "
            >
              万元
            </p>
          </div>
        </el-form-item>
        <el-form-item
          label="新增企业年实缴税金"
          label-width="200px"
          prop="taxPaid"
        >
          <div style="display: flex; align-items: center">
            <el-input
              v-model.number="form.taxPaid"
              placeholder="请输入企业年实缴税金"
              clearable
            />
            <p
              style="
                flex: 0 0 auto;
                margin: 0 10px;
                width: 30px;
                text-align: center;
              "
            >
              万元
            </p>
          </div>
        </el-form-item>
        <el-form-item
          label="新增企业用地面积"
          label-width="200px"
          prop="landArea"
        >
          <div style="display: flex; align-items: center">
            <el-input
              v-model.number="form.landArea"
              placeholder="请输入企业用地面积"
              clearable
            />
            <p
              style="
                flex: 0 0 auto;
                margin: 0 10px;
                width: 30px;
                text-align: center;
              "
            >
              亩
            </p>
          </div>
        </el-form-item>
        <el-form-item
          label="新增企业近三年亩均产值"
          label-width="200px"
          prop="averageOutputValuePerMuInRecentThreeYears"
        >
          <span slot="label">
            新增企业近三年亩均产值
            <el-tooltip class="item" effect="light" placement="bottom">
              <span slot="content">
                ①亩均产值=产值/用地面积<br />
                ②近三年：去年往前推三年，例如2025年时，计算年份为2024年、2023年、2022年<br />
                ③近三年平均亩均产值=（2022年亩均产值+2023年+2024年）/3
              </span>
              <i class="el-icon-question" /><!--小问号提示-->
            </el-tooltip>
          </span>
          <div style="display: flex; align-items: center">
            <el-input
              v-model.number="form.averageOutputValuePerMuInRecentThreeYears"
              placeholder="请输入企业近三年亩均产值"
              clearable
            />
          </div>
        </el-form-item>
        <el-form-item
          label="新增企业近三年亩均税收"
          label-width="200px"
          prop="averageTaxPerMuInRecentThreeYears"
        >
          <span slot="label">
            新增企业近三年亩均税收
            <el-tooltip class="item" effect="light" placement="bottom">
              <span slot="content">
                ①亩均税收=实缴税金/用地面积<br />
                ②近三年：去年往前推三年，例如2025年时，计算年份为2024年、2023年、2022年<br />
                ③近三年平均亩均税收=（2022年亩均税收+2023年+2024年）/3
              </span>
              <i class="el-icon-question" /><!--小问号提示-->
            </el-tooltip>
          </span>
          <div style="display: flex; align-items: center">
            <el-input
              v-model.number="form.averageTaxPerMuInRecentThreeYears"
              placeholder="请输入企业近三年亩均税收"
              clearable
            />
          </div>
        </el-form-item>
        <el-form-item label="行业代码" label-width="200px" prop="code">
          <el-select v-model="form.code" style="width: 100%" filterable>
            <el-option
              v-for="item in industryData"
              :key="item.key"
              :label="item.value"
              :value="item.key"
            >
            </el-option>
          </el-select>
          <!-- <el-select v-model="form.selectedCode" style="width: 100%" filterable>
            <el-option
              v-for="item in selectedIndustryArray"
              :key="item.key"
              :label="item.value"
              :value="item.key"
            >
            </el-option> </el-select> -->
        </el-form-item>
        <el-form-item label="企业分类" label-width="200px" prop="typeNum">
          <el-select v-model="form.typeNum" style="width: 100%" clearable>
            <el-option
              v-for="item in enterTypeList"
              :key="item.number"
              :value="item.number"
              :label="keyToChineseEtype(item.number)"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年度" label-width="200px" prop="year">
          <span slot="label">
            年度
            <el-tooltip class="item" effect="light" placement="bottom">
              <span slot="content">
                填写年度，例如填写2025年时，计算年份为2024年、2023年、2022年
              </span>
              <i class="el-icon-question" />
            </el-tooltip>
          </span>
          <div style="display: flex; align-items: center">
            <el-input
              v-model.number="form.year"
              placeholder="请输入年度"
              clearable
            />
          </div>
        </el-form-item>
        <el-form-item label-width="100px">
          <el-button type="primary" size="mini" @click="submitForm"
            >计算</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetForm"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div ref="chart" :style="{ height: height, width: width }"></div>
    <el-table :data="tableData" border style="width: 100%" height="500">
      <el-table-column prop="id" label="企业ID" width="100"></el-table-column>
      <el-table-column prop="enterpriseName" label="企业名称"></el-table-column>
      <el-table-column prop="landUsedInRecentThreeYears" label="近三年用地/亩">
        <template v-slot="scope">
          <span>{{ scope.row.landUsedInRecentThreeYears.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="averageAnnualOutputValue" label="年均产值/万元">
        <template v-slot="scope">
          <span>{{ scope.row.averageAnnualOutputValue.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="output" label="年均亩均产值"
        ><template slot="header">
          <el-tooltip
            class="item"
            effect="dark"
            content="新增企业的年均亩均产值=表单中填入的新增企业近三年亩均产值"
            placement="top"
          >
            <span slot="content">
              ①新增企业的年均亩均产值=表单中填入的新增企业近三年亩均产值<br />
              ②其他企业的年均亩均产值=（去年亩均产值+前年亩均产值+大前年亩均产值）/3<br />
            </span>
            <span>年均亩均产值</span>
          </el-tooltip>
        </template>
        <template v-slot="scope">
          <span>{{ scope.row.output.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="outputScore" label="亩均产值得分">
        <template slot="header">
          <el-tooltip
            class="item"
            effect="dark"
            content="年均亩均产值（新增企业近三年亩均产值）/行业基准值A*40"
            placement="top"
          >
            <span>亩均产值得分</span>
          </el-tooltip>
        </template>
        <template v-slot="scope">
          <span>{{ scope.row.outputScore.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="averageAnnualTaxPaid"
        label="年均实缴税金/万元"
        width="140"
      >
        <template v-slot="scope">
          <span>{{ scope.row.averageAnnualTaxPaid.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="tax" label="年均亩均税收"
        ><template slot="header">
          <el-tooltip
            class="item"
            effect="dark"
            content=""
            placement="top"
          >
            <span slot="content">
              ①新增企业的年均亩均税收=表单中填入的新增企业近三年亩均税收<br />
              ②其他企业的年均亩均税收=（去年亩均税收+前年亩均税收+大前年亩均税收）/3<br />
            </span>
            <span>年均亩均税收</span>
          </el-tooltip>
        </template>
        <template v-slot="scope">
          <span>{{ scope.row.averageAnnualTaxPaid.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="taxpaidScore" label="亩均税收得分">
        <template slot="header">
          <el-tooltip
            class="item"
            effect="dark"
            content="年均亩均税收（新增企业近三年亩均税收）/行业基准值B*60"
            placement="top"
          >
            <span>亩均税收得分</span>
          </el-tooltip>
        </template>
        <template v-slot="scope">
          <span>{{ scope.row.taxpaidScore.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="scoreTotal" label="企业综合得分"
        ><template slot="header">
          <el-tooltip
            class="item"
            effect="dark"
            content="亩均产值得分+亩均税收得分"
            placement="top"
          >
            <span>企业综合得分</span>
          </el-tooltip>
        </template>
        <template v-slot="scope">
          <span>{{ scope.row.scoreTotal.toFixed(2) }}</span>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import { getYearData } from "@/api/home";
import { listEtypeAll } from "@/api/etype/etype";
import { listAllIndustry } from "@/api/industry/industry"; // 导入行业数据的接口
import { analysisInvestment } from "@/api/analysis/analysis";

import * as echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme
import resize from "@/views/dashboard/mixins/resize";
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 {
      selectedDataKey: "totalIndustrialValueScore", // 默认选择的字段
      form: {
        annualOutputValue: null, // 年产值
        taxPaid: null, // 年缴税额
        landArea: null, // 占地面积
        typeNum: null, // 企业类型
        code: null, // 行业代码
        year: null, // 年份
        averageOutputValuePerMuInRecentThreeYears: null, // 近三年亩均产值
        averageTaxPerMuInRecentThreeYears: null, // 近三年亩均税收
      },
      rules: {
        annualOutputValue: [
          { required: true, message: "请输入新增企业年产值", trigger: "blur" },
          {
            type: "number",
            message: "企业年产值必须是数字",
            trigger: ["blur", "change"],
          },
        ],
        taxPaid: [
          {
            required: true,
            message: "请输入新增企业年缴税收",
            trigger: "blur",
          },
          {
            type: "number",
            message: "企业年缴税收必须是数字",
            trigger: ["blur", "change"],
          },
        ],
        landArea: [
          {
            required: true,
            message: "请输入新增企业占地面积",
            trigger: "blur",
          },
          {
            type: "number",
            message: "企业占地面积必须是数字",
            trigger: ["blur", "change"],
          },
        ],
        code: [
          { required: true, message: "请选择行业代码", trigger: "change" },
        ],
        year: [
          { required: true, message: "请输入年度", trigger: "blur" },
          {
            type: "number",
            message: "年度必须是数字",
            trigger: ["blur", "change"],
          },
          {
            validator: (rule, value, callback) => {
              const currentYear = new Date().getFullYear();
              if (value < 1900 || value > currentYear) {
                callback(new Error(`请输入合理的年度，示例：2025`));
              } else {
                callback();
              }
            },
            trigger: ["blur"],
          },
        ],
        averageOutputValuePerMuInRecentThreeYears: [
          { required: true, message: "请输入近三年亩均产值", trigger: "blur" },
          {
            type: "number",
            message: "近三年亩均产值必须是数字",
            trigger: ["blur", "change"],
          },
        ],
        averageTaxPerMuInRecentThreeYears: [
          { required: true, message: "请输入近三年亩均税收", trigger: "blur" },
          {
            type: "number",
            message: "近三年亩均税收必须是数字",
            trigger: ["blur", "change"],
          },
        ],
      },
      industryData: [],
      yearsOptions: [],
      enterTypeList: [],
      BaseA: 0,
      BaseB: 0,
      BaseData: [],
      chart: null,
      chartData: [],
      newScore: 0,
      tableData: [],
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.fetchData();
    });
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
    }
  },
  methods: {
    fetchData() {
      Promise.all([
        this.getYearData(),
        this.getAllIndustry(),
        this.getEtypeAll(),
      ])
        .then(() => {
          // console.log("All data fetched successfully");
          this.form.year = new Date().getFullYear();
          this.initChart();
        })
        .catch((error) => {
          console.error("Error fetching data:", error);
        });
    },
    sortByCode(arr) {
      return arr.sort((a, b) => {
        const numA = Number(a.code);
        const numB = Number(b.code);

        // 检查是否为有效数字
        const isANum = !isNaN(numA);
        const isBNum = !isNaN(numB);

        if (isANum && isBNum) {
          return numA - numB; // 都是数字，按数字升序排序
        } else if (isANum) {
          return -1; // a 是数字，放在前面
        } else if (isBNum) {
          return 1; // b 是数字，放在前面
        } else {
          return 0; // 都不是数字，保持原顺序
        }
      });
    },
    getYearData() {
      return getYearData().then((res) => {
        this.yearsOptions = res.rows[0].years;
      });
    },

    getAllIndustry() {
      return listAllIndustry().then((response) => {
        if (response?.rows) {
          let arr = this.sortByCode(response.rows);
          this.industryData = arr.map((item) => ({
            key: item.code,
            value: item.code + item.industryName,
          }));
        }
      });
    },
    getEtypeAll() {
      return listEtypeAll().then((res) => {
        this.enterTypeList = res;
        // console.log(this.enterTypeList);
      });
    },
    keyToChineseEtype(num) {
      const item = this.enterTypeList.find((element) => element.number === num);
      return item ? item.name : null;
    },
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: "Loading",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          analysisInvestment(this.form).then((res) => {
            loading.close();
            if (res && res?.code === 200 && res?.rows.length > 0) {
              let data = res.rows[0];
              this.BaseA = data.standardA;
              this.BaseB = data.standardB;
              this.BaseData = data.list;
              // console.log(this.BaseData);
              this.BaseData.push({
                id: "新企业",
                typeNum: this.form.typeNum,
                enterpriseName: "新企业"
              });
              this.updateChart();
            }
          });
        } else {
          // loading.close();
          console.log("error submit!!");
        }
      });
    },
    resetForm() {
      this.$refs.ruleForm.resetFields();
    },
    initChart() {
      if (this.chart) {
        this.chart.dispose();
      }
      this.chart = echarts.init(this.$refs.chart, "macarons");
    },
    updateChart() {
      const that = this;
      if (!that.chart) {
        return;
      }
      // 更新图表数据
      that.chartData = that.handleData(that.BaseData);
      console.log(that.chartData);
      // console.log(that.chartData);
      that.tableData = [];
      let totalValues = that.chartData
        .map((item) => item.scoreTotal)
        .filter((value) => {
          return Number.isFinite(value); // 只保留有限值
        });
      // console.log(totalValues);
      let { min, max, avg, stdDev } = that.getBebeQ(totalValues);
      const interval = 5;
      const center = new Decimal(avg);

      let minLimit = new Decimal(min); // 向下取整到最近的0.1
      let maxLimit = new Decimal(max); // 向上取整到最近的0.1

      // 确保 minLimit 和 maxLimit 关于 center 对称
      if (!center.minus(minLimit).equals(maxLimit.minus(center))) {
        const distanceToCenter = center
          .minus(minLimit)
          .gt(maxLimit.minus(center))
          ? center.minus(minLimit)
          : maxLimit.minus(center);

        maxLimit = new Decimal( center.plus(distanceToCenter).dividedBy(interval).ceil().toNumber() *  interval); // 更新 maxLimit 保持对称
        minLimit = new Decimal( center.minus(distanceToCenter).dividedBy(interval).floor().toNumber() * interval); // 更新 minLimit 保持对称
      }
      const intervals = [];

      // 创建区间
      let current = minLimit;
      let limit = maxLimit;
      // console.log(maxLimit.toNumber(), that.newScore);
      for (; current.lte(limit); current = current.plus(interval)) {
        intervals.push(current.toFixed(2)); // 保留两位小数
      }

      // 确保包含最大值
      if (!current.eq(maxLimit)) {
        intervals.push(limit.toFixed(2)); // 将最大值添加到 interval 中
      }
      // console.log(intervals);
      // 计算每个间隔的频次
      const frequency = new Array(intervals.length - 1).fill(0); // 初始化频次数组

      let intervalArr = intervals.slice(0, -1);
      const intervalStrings = [];
      for (let i = 0; i < intervalArr.length; i++) {
        const start = new Decimal(intervalArr[i]).toFixed(0); // 保留一位小数
        const end = new Decimal(intervalArr[i]).plus(interval).toFixed(0); // 保留一位小数
        intervalStrings.push({
          name: `${start}-${end}`,
          max: end,
          min: start,
        }); // 构建区间字符串
      }
      // console.log(intervalStrings);
      totalValues.forEach((value) => {
        let v = new Decimal(value); // 将 value 转换为 Decimal
        for (let j = 0; j < intervalStrings.length; j++) {
          // 保证包含右边界
          if (
            v.gte(new Decimal(intervalStrings[j].min)) &&
            v.lt(new Decimal(intervalStrings[j].max))
          ) {
            // if (value == that.newScore) {
            //   console.log("newScore1", value);
            // }
            // console.log(v, intervalStrings[j].min, intervalStrings[j].max);
            frequency[j]++;
            break; // 找到对应区间后可以跳出循环
          }
        }
      });

      // 确保处理最大值等于 maxLimit 的情况
      if (totalValues.some((value) => new Decimal(value).eq(maxLimit))) {
        frequency[frequency.length - 1]++;
      }

      // console.log(intervals, intervalStrings, frequency);

      const normalDistributionValues = intervals
        .slice(0, -1)
        .map((intervalStart, index) => {
          const intervalEnd = intervals[index + 1];

          // 将 intervalStart 和 intervalEnd 转换为 Decimal 实例
          const midPointDecimal = new Decimal(intervalStart)
            .plus(new Decimal(intervalEnd))
            .dividedBy(2);

          // 使用 Decimal 进行更高精度的计算
          const avgDecimal = new Decimal(avg);
          const stdDevDecimal = new Decimal(stdDev);

          const exponent = midPointDecimal
            .minus(avgDecimal)
            .dividedBy(stdDevDecimal)
            .pow(2)
            .negated()
            .dividedBy(new Decimal(2));

          // 取自然指数
          const exponentValue = new Decimal(Math.exp(exponent.toNumber()));

          // 计算系数
          const coefficient = new Decimal(1).dividedBy(
            stdDevDecimal.times(new Decimal(Math.sqrt(2 * Math.PI)))
          );

          return coefficient.times(exponentValue).toNumber(); // 返回计算结果
        });
      const newScore = new Decimal(that.newScore);
      // console.log(that.newScore, "newScore");
      // console.log(intervals, intervalStrings, frequency);
      const option = {
        color: ["rgba(245,0,0,0.6)"],
        dataZoom: [
          {
            type: "inside", // 内置于坐标系中
            start: 0,
            end: 100,
            xAxisIndex: [0],
          },
        ],
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          formatter: (params) => {
            // 使用箭头函数来保持 this 的上下文
            const seriesName = params[0].name; // 系列名称
            const dataIndex = params[0].dataIndex; // 数据索引
            const value = params[0].data; // 实际的数据值
            const xAxisLabel = params[0].axisValueLabel; // x轴的标签
            const yAxisLabel = params[0].seriesName;
            // 构建自定义的 tooltip 内容，包含年份
            return `${xAxisLabel}</br> 企业数量： ${value} `;
          },
        },
        legend: {
          data: [`企业数统计`, "正态分布"],
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "50px",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          name: "分布区间",
          // data: histogramData.map((item) => item.name),
          data: intervalStrings.map((item) => item.name),
          axisLabel: {
            fontSize: 12,
            rotate: 0,
            // padding: [0, 0, 0, -200]
          },
        },
        yAxis: [
          {
            name: "企业数",
            type: "value",
            minInterval: 1,
          },
          {
            name: "正态分布",
            type: "value",
          },
        ],
        series: [
          {
            name: `招商辅助`,
            type: "bar",
            barWidth: "30%",
            itemStyle: {
              // color: "rgba(245,0,0,0.6)",
              normal: {
                color: function (params) {
                  const value = params.dataIndex; // 获取当前柱子在数据中的索引
                  let min = new Decimal(intervalStrings[value].min);
                  let max = new Decimal(intervalStrings[value].max);
                  if (newScore.gte(min) && newScore.lt(max)) {
                    return "#ffcc00";
                  } else if (newScore.eq(maxLimit) && max.eq(maxLimit)) {
                    return "#ffcc00";
                  }
                  return "rgba(245,0,0,0.6)";
                  // 默认颜色
                },
              },
            },
            // data: histogramData.map((item) => item.value),
            data: frequency,
            label: {
              show: false, // 将show属性设置为false，去掉柱子上的数字
            },
          },
          {
            name: "正态分布",
            yAxisIndex: 1,
            type: "line",
            data: normalDistributionValues,
            lineStyle: {
              color: "#1a7cc8",
            },
            symbol: "none",
          },
        ],
      };
      this.chart.setOption(option);
      this.chart.on("click", function (param) {
        if (
          typeof param.dataIndex === "number" &&
          param.dataIndex >= 0 &&
          param.dataIndex < intervalStrings.length
        ) {
          let dataIndexValue = intervalStrings[param.dataIndex];
          const filteredArray = that.chartData.filter((item) => {
            let score = new Decimal(item.scoreTotal);
            let max = new Decimal(dataIndexValue.max);
            let min = new Decimal(dataIndexValue.min);
            let maxL = new Decimal(maxLimit);
            const isMaxValEqual = max.equals(maxL);
            const lowerBoundCheck = score.greaterThan(min) || score.equals(min);
            const upperBoundCheck = isMaxValEqual
              ? score.lessThan(max) || score.equals(max)
              : score.lessThan(max);
            return lowerBoundCheck && upperBoundCheck;
          });
          that.tableData = filteredArray.map((item) => {
            return item;
          });
        }
      });
    },
    // 计算亩均产值得分、亩均税收得分、企业综合得分
    handleData(data) {
      return data.map((item) => {
        const quNianTax = new Decimal(item.quNianTax || 0);
        const quNianArea = new Decimal(item.quNianArea || 0);
        const quNianInd = new Decimal(item.quNianInd || 0);

        const qianNianTax = new Decimal(item.qianNianTax || 0);
        const qianNianArea = new Decimal(item.qianNianArea || 0);
        const qianNianInd = new Decimal(item.qianNianInd || 0);

        const daQianNianTax = new Decimal(item.daQianNianTax || 0);
        const daQianNianArea = new Decimal(item.daQianNianArea || 0);
        const daQianNianInd = new Decimal(item.daQianNianInd || 0);

        // 计算去年亩均产值 quNianChanZhi、去年亩均税收 quNianShuiShou；
        const quNianChanZhi = quNianArea.gt(0)
          ? quNianInd.dividedBy(quNianArea)
          : new Decimal(0);
        const quNianShuiShou = quNianArea.gt(0)
          ? quNianTax.dividedBy(quNianArea)
          : new Decimal(0);
        // 计算前年亩均产值 qianNianChanZhi、亩均税收 qianNianShuiShou；
        // 计算大前年的亩均产值 daQianNianChanZhi、亩均税收 daQianNianShuiShou
        // 计算近三年的亩均产值 avgChanZhi = （quNianChanZhi + qianNianChanZhi + daQianNianChanZhi）/3   如果其中有数据为0，则不参与计算，即avgChanZhi = （quNianChanZhi + qianNianChanZhi）/2
        // 计算近三年的亩均税收 avgShuiShou = （quNianShuiShou + qianNianShuiShou + daQianNianShuiShou）/3   如果其中有数据为0，则不参与计算，即avgShuiShou = （quNianShuiShou + qianNianShuiShou）/2
        // 计算亩均产值得分 outputScore = avgChanZhi / BaseA * 40   如果outputScore计算结果大于40，则outputScore = 40
        // 计算亩均税收得分 taxpaidScore = avgShuiShou / BaseB * 60   如果taxpaidScore计算结果大于60，则taxpaidScore = 60
        // 计算企业综合得分 scoreTotal = outputScore + taxpaidScore
        // 计算前年的亩均产值和税收
        const qianNianChanZhi = qianNianArea.gt(0)
          ? qianNianInd.dividedBy(qianNianArea)
          : new Decimal(0);
        const qianNianShuiShou = qianNianArea.gt(0)
          ? qianNianTax.dividedBy(qianNianArea)
          : new Decimal(0);

        // 计算大前年的亩均产值和税收
        const daQianNianChanZhi = daQianNianArea.gt(0)
          ? daQianNianInd.dividedBy(daQianNianArea)
          : new Decimal(0);
        const daQianNianShuiShou = daQianNianArea.gt(0)
          ? daQianNianTax.dividedBy(daQianNianArea)
          : new Decimal(0);

        // 计算近三年平均亩均产值
        const validChanZhiValues = [quNianChanZhi, qianNianChanZhi, daQianNianChanZhi].filter(v => v.gt(0));
        let avgChanZhi = validChanZhiValues.length > 0 
          ? validChanZhiValues.reduce((sum, val) => sum.plus(val), new Decimal(0)).dividedBy(validChanZhiValues.length)
          : new Decimal(0);

        // 计算近三年平均亩均税收
        const validShuiShouValues = [quNianShuiShou, qianNianShuiShou, daQianNianShuiShou].filter(v => v.gt(0));
        let avgShuiShou = validShuiShouValues.length > 0 
          ? validShuiShouValues.reduce((sum, val) => sum.plus(val), new Decimal(0)).dividedBy(validShuiShouValues.length)
          : new Decimal(0);

        // 计算近三年年均使用土地面积（排除0值）
        const validLandValues = [quNianArea, qianNianArea, daQianNianArea].filter(v => v.gt(0));
        let landUsedInRecentThreeYears = validLandValues.length > 0 
          ? validLandValues.reduce((sum, val) => sum.plus(val), new Decimal(0)).dividedBy(validLandValues.length)
          : new Decimal(0);

        // 计算近三年年均产值（排除0值）
        const validOutputValues = [quNianInd, qianNianInd, daQianNianInd].filter(v => v.gt(0));
        let averageAnnualOutputValue = validOutputValues.length > 0 
          ? validOutputValues.reduce((sum, val) => sum.plus(val), new Decimal(0)).dividedBy(validOutputValues.length)
          : new Decimal(0);

        // 计算近三年年均税金（排除0值）
        const validTaxValues = [quNianTax, qianNianTax, daQianNianTax].filter(v => v.gt(0));
        let averageAnnualTaxPaid = validTaxValues.length > 0 
          ? validTaxValues.reduce((sum, val) => sum.plus(val), new Decimal(0)).dividedBy(validTaxValues.length)
          : new Decimal(0);

        // 如果是新企业，则直接拿form中的数据
        if (item.id === "新企业") {
          avgChanZhi = new Decimal(
            this.form.averageOutputValuePerMuInRecentThreeYears
          );
          avgShuiShou = new Decimal(this.form.averageTaxPerMuInRecentThreeYears);
          landUsedInRecentThreeYears = new Decimal(this.form.landArea);
          averageAnnualOutputValue = new Decimal(this.form.annualOutputValue);
          averageAnnualTaxPaid = new Decimal(this.form.taxPaid);
        }

        // 计算亩均产值得分（上限40）
        let outputScore = avgChanZhi.dividedBy(this.BaseA).times(40);
        outputScore = outputScore.gt(40) ? new Decimal(40) : outputScore;

        // 计算亩均税收得分（上限60）
        let taxpaidScore = avgShuiShou.dividedBy(this.BaseB).times(60);
        taxpaidScore = taxpaidScore.gt(60) ? new Decimal(60) : taxpaidScore;

        // 计算综合得分
        const scoreTotal = outputScore.plus(taxpaidScore);
        if (item.id === "新企业") {
          this.newScore = scoreTotal.toNumber();
        }
        // console.log(item.enterpriseName,avgChanZhi.toNumber(),avgShuiShou.toNumber(),outputScore.toNumber(),taxpaidScore.toNumber(),scoreTotal.toNumber())
        // 使用Decimal进行高精度计算
        // const averageAnnualOutputValue = new Decimal(
        //   item.averageAnnualOutputValue || 0
        // );
        // const averageAnnualTaxPaid = new Decimal(
        //   item.averageAnnualTaxPaid || 0
        // );
        // const landArea = new Decimal(item.landUsedInRecentThreeYears || 0);

        // // 计算亩均产值
        // let output = landArea.gt(0)
        //   ? averageAnnualOutputValue.dividedBy(landArea)
        //   : new Decimal(0);

        // // 计算亩均税收
        // let tax = landArea.gt(0)
        //   ? averageAnnualTaxPaid.dividedBy(landArea)
        //   : new Decimal(0);

        

        // // 计算得分
        // let outputScore = output.dividedBy(this.BaseA).times(40);
        // let taxpaidScore = tax.dividedBy(this.BaseB).times(60);

        // // 限制得分不超过最大值
        // outputScore = outputScore.gt(40) ? new Decimal(40) : outputScore;
        // taxpaidScore = taxpaidScore.gt(60) ? new Decimal(60) : taxpaidScore;

        // // 计算总分
        // const scoreTotal = outputScore.plus(taxpaidScore);

        // if (item.id === "新企业") {
        //   this.newScore = scoreTotal.toNumber();
        // }
        // output: output.toNumber(),
          // tax: tax.toNumber(),
          // outputScore: outputScore.toNumber(),
          // taxpaidScore: taxpaidScore.toNumber(),
          // scoreTotal: scoreTotal.toNumber(),
        return {
          ...item,
          landUsedInRecentThreeYears: landUsedInRecentThreeYears.toNumber(),
          averageAnnualOutputValue: averageAnnualOutputValue.toNumber(),
          averageAnnualTaxPaid: averageAnnualTaxPaid.toNumber(),
          output: avgChanZhi.toNumber(), //亩均产值
          tax: avgShuiShou.toNumber(), //亩均税收
          outputScore: outputScore.toNumber(), //亩均产值得分
          taxpaidScore: taxpaidScore.toNumber(),//亩均税收得分
          scoreTotal: scoreTotal.toNumber(),//综合得分
        };
      });
    },

    // 获取基础数据：最大值，最小值，平均值，标准差
    getBebeQ(numbers, digit = 2) {
      let sum = numbers.reduce(
        (acc, num) => acc.add(new Decimal(num)),
        new Decimal(0)
      );

      let max = Math.max.apply(null, numbers);
      let min = Math.min.apply(null, numbers);

      // 平均值
      let mean = sum.dividedBy(numbers.length);

      // 计算每个数与均值的差的平方
      const squaredDiffs = numbers.map((num) => {
        const diff = new Decimal(num).minus(mean);
        return diff.pow(2);
      });

      // 计算平方差的均值
      const sumOfSquaredDiffs = squaredDiffs.reduce(
        (acc, diff) => acc.add(diff),
        new Decimal(0)
      );

      const variance = sumOfSquaredDiffs.dividedBy(numbers.length);

      // 开平方得到标准差
      const standardDeviation = variance.sqrt();

      // 向上取整到最近的 0.1
      const ceilingRoundedMax = Math.ceil(max * 10) / 10;

      // 向下取整到最近的 0.1
      const floorRoundedMin = Math.floor(min * 10) / 10;

      return {
        max: ceilingRoundedMax,
        min: floorRoundedMin,
        avg: parseFloat(mean.toNumber().toFixed(digit)) || 0,
        stdDev: parseFloat(standardDeviation.toNumber().toFixed(digit)),
      };
    },
    calculateMeanAndStdDev(data) {
      const sum = data.reduce(
        (acc, val) => acc.plus(new Decimal(val)),
        new Decimal(0)
      );
      let mean = sum.dividedBy(data.length);

      const variance = data
        .reduce((acc, val) => {
          const diff = new Decimal(val).minus(mean);
          return acc.plus(diff.pow(2));
        }, new Decimal(0))
        .dividedBy(data.length);

      let stdDev = variance.sqrt();
      return { mean, stdDev };
    },
    calculateNormalDistribution(step, mean, stdDev) {
      // const min = Math.min(...data);
      // const max = Math.max(...data);
      // const step = (max - min) / 100;
      let arr = [];
      for (let x = min; x <= max; x += step) {
        const exponent = new Decimal(x)
          .minus(mean)
          .pow(2)
          .dividedBy(new Decimal(2).times(stdDev.pow(2)))
          .neg();
        const pdf = new Decimal(1)
          .dividedBy(stdDev.times(new Decimal(2).times(Math.PI).sqrt()))
          .times(exponent.exp());
        arr.push({ x, y: pdf.toNumber() });
      }
      return arr;
    },
  },
};
</script>
