<template>
  <!-- 同比增速 -->
  <div
    :class="className"
    :style="{ height: '100%', width: width, padding: '15px' }"
  >
    <div class="select-container">
      <el-form
        style="
          display: grid;
          grid-template-columns: 1fr 1fr 1fr;
          align-items: center;
          grid-gap: 5px;
        "
        label-width="100px"
      >
        <el-form-item label="评估指标">
          <el-select v-model="rateForm.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="行业">
          <el-select
            v-model="rateForm.selectedIndustry"
            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-form-item>
        <el-form-item label="企业分类">
          <el-select
            v-model="rateForm.selectEnterType"
            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="排序方式">
          <el-select
            v-model="rateForm.selectedRange"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="key in sortOptions"
              :key="key"
              :label="key"
              :value="key"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="年度">
          <el-select
            v-model="rateForm.selectedYear"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="key in yearsOptions"
              :key="key"
              :label="key"
              :value="key"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="季度"
          v-show="
            rateForm.selectedDataKey === 'taxableIncome' ||
            rateForm.selectedDataKey === 'paidTax'
          "
        >
          <el-select
            v-model="rateForm.selectedSeason"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="key in seasonOptions"
              :key="key"
              :label="key"
              :value="key"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="起始月度"
          v-show="
            rateForm.selectedDataKey === 'totalIndustrialValue' ||
            rateForm.selectedDataKey === 'powerConsume'
          "
        >
          <el-select
            v-model="rateForm.selectedStartMonth"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="key in monthOptions"
              :key="key"
              :label="key"
              :value="key"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="结束月度"
          v-show="
            rateForm.selectedDataKey === 'totalIndustrialValue' ||
            rateForm.selectedDataKey === 'powerConsume'
          "
        >
          <el-select
            v-model="rateForm.selectedEndMonth"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="key in monthOptions"
              :key="key"
              :label="key"
              :value="key"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="submit"
            size="mini"
            >搜索</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <el-button-group
      style="margin-right: 30px; position: absolute; right: 0; z-index: 10"
      v-show="sortButtonShow"
    >
      <el-button
        size="mini"
        :type="sortActive === 'asc' ? 'primary' : 'default'"
        @click="changSort('asc')"
        >升序</el-button
      >
      <el-button
        size="mini"
        :type="sortActive === 'desc' ? 'primary' : 'default'"
        @click="changSort('desc')"
        >降序</el-button
      >
      <el-button
        size="mini"
        :type="sortActive === 'location' ? 'primary' : 'default'"
        @click="changSort('location')"
        >按坐落地升序</el-button
      >
    </el-button-group>
    <div ref="chart" :style="{ height: height, width: width }"></div>
    <!-- littlegreen - 新增数据展示table -->
    <el-table :data="tableData" border>
      <el-table-column prop="enterpriseName" label="企业名称"></el-table-column>
      <el-table-column
        prop="rate"
        label="同比增速"
        width="200"
      ></el-table-column>
      <el-table-column
        prop="location"
        label="坐落地"
        width="200"
      ></el-table-column>
    </el-table>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { getYearData } from "@/api/home";
import { listEtypeAll } from "@/api/etype/etype";
import { analysisGrowthRate } from "@/api/analysis/analysis";
import { listBase_data_year } from "@/api/base_data_year/base_data_year";
import { listIndustry, listAllIndustry } from "@/api/industry/industry"; // 导入行业数据的接口
require("echarts/theme/macarons"); // echarts theme
import resize from "@/views/dashboard/mixins/resize";

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "400px",
    },
  },
  data() {
    return {
      rateForm: {
        selectedDataKey: "funding",
        selectedIndustry: null,
        selectedRange: null,
        selectedYear: null,
        selectedSeason: null,
        selectedStartMonth: null,
        selectedEndMonth: null,
        selectEnterType: null,
      },
      seasonMap: new Map(),
      monthMap: new Map(),
      yearsOptions: [],
      enterTypeList: [], // 企业类型列表
      sortOptions: ["升序", "降序", "坐落地排序"],
      label: "评估指标值/万元",
      chart: null,
      chartData: [],
      industryData: [],
      industryMap: new Map(),
      searchData: [],
      // 默认选择的字段
      selectedCode: null,
      sortActive: "asc",
      sortButtonShow: false,
      dataKeys: [
        "funding",
        "energyConsume",
        "paidTax",
        "taxableIncome",
        "totalIndustrialValue",
        "powerConsume",
      ], // 可选项
      keyToChinese: {
        landArea: "用地面积",
        totalIndustrialValue: "工业总产值",
        gdp: "工业增加值",
        taxableIncome: "应税收入",
        paidTax: "实缴税金",
        mainBusinessIncome: "主营业务收入",
        employeeNumber: "从业人员数",
        profit: "利润总额",
        ownerEquity: "所有者权益",
        funding: "研发经费",
        energyConsume: "能源消费量",
        powerConsume: "电力消费量",
      },
      keyToUnit: {
        landArea: "/亩",
        totalIndustrialValue: "/万元",
        gdp: "/万元",
        taxableIncome: "/万元",
        paidTax: "/万元",
        mainBusinessIncome: "/万元",
        employeeNumber: "/人",
        profit: "/万元",
        ownerEquity: "",
        funding: "/万元",
        energyConsume: "/万m³",
        powerConsume: "/万KW·h",
      },
      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,
      },
      industryQueryParams: {
        pageNum: 1,
        pageSize: 2000000,
        industryName: null,
        code: null,
      }, //  查询行业信息
      availableYears: [],
      selectedRange: 300, // 不能为 0
      tableData: [],
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.fetchData();
    });
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
    }
  },
  methods: {
    fetchData() {
      // 获取年份，获取季度、月度
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      Promise.all([
        this.getYearData(),
        this.getAllIndustry(),
        this.getEtypeAll(),
      ])
        .then(() => {
          loading.close();
          this.initChart();
        })
        .catch((error) => {
          loading.close();
          this.$message.error(error);
          // console.error("Error fetching data:", error);
        });
    },
    getYearData() {
      return getYearData().then((res) => {
        this.yearsOptions = res.rows[0].years;
        this.seasonMap = this.generateSeason(this.yearsOptions);
        this.monthMap = this.generateMonthlyData(this.yearsOptions);
      });
    },

    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);
      });
    },
    initChart() {
      if (this.chart) {
        this.chart.dispose();
      }
      this.chart = echarts.init(this.$refs.chart, "macarons");
      // this.updateChart();
    },
    submit() {
      const that = this;
      let {
        selectedDataKey,
        selectedStartMonth,
        selectedEndMonth,
        selectedSeason,
        selectedYear,
        selectedIndustry,
      } = this.rateForm;
      // -----数据校验 start-----
      if (!selectedIndustry) {
        this.$message.error("请选择行业");
        return;
      }

      if (!selectedYear) {
        this.$message.error("请选择年度");
        return;
      }
      const validateMonths = (startMonth, endMonth) => {
        if (!startMonth) {
          this.$message.error("请选择开始月份");
          return false;
        }
        if (!endMonth) {
          this.$message.error("请选择结束月份");
          return false;
        }
        if (endMonth < startMonth) {
          this.$message.error("结束月份不能小于开始月份");
          return false;
        }
        return true;
      };
      if (["totalIndustrialValue", "powerConsume"].includes(selectedDataKey)) {
        if (!validateMonths(selectedStartMonth, selectedEndMonth)) return;
        this.rateForm.selectedSeason = null;
      } else if (["taxableIncome", "paidTax"].includes(selectedDataKey)) {
        this.rateForm.selectedStartMonth = null;
        this.rateForm.selectedEndMonth = null;
        if (!selectedSeason) {
          this.$message.error("请选择季度");
          return;
        }
      } else if (["energyConsume", "funding"].includes(selectedDataKey)) {
        this.rateForm.selectedSeason = null;
        this.rateForm.selectedStartMonth = null;
        this.rateForm.selectedEndMonth = null;
      }
      // -----数据校验 end-----
      const propertyMapping = {
        selectedDataKey: "analysisType",
        selectedIndustry: "code",
        selectedRange: "sort",
        selectedYear: "year",
        selectedSeason: "season",
        selectedStartMonth: "startMonth",
        selectedEndMonth: "endMonth",
        selectEnterType: "typeNum",
      };
      const renamedRateForm = this.renameProperties(
        this.rateForm,
        propertyMapping
      );
      analysisGrowthRate(renamedRateForm)
        .then((res) => {
          if (res && res?.rows) {
            that.searchData = res.rows;
            that.updateChart(res.rows);
          }
          console.log(res);
        })
        .catch((err) => {
          this.$message.error("请求数据失败");
          return;
        });
    },
    updateChart(rawData) {
      const that = this;
      if (!this.chart) {
        return;
      }
      const categories = [];
      const seriesData = [];
      let sortedData = [];
      sortedData = rawData.map((item) => ({
        ...item, // 扩展其他属性
        rate: isNaN(parseFloat(item.rate))
          ? null
          : (parseFloat(item.rate) * 100).toFixed(2),
      }));
      console.log(rawData, sortedData, "sortedData");
      if (this.sortActive === "asc") {
        sortedData.sort((a, b) => {
          if (a.rate === null && b.rate === null) return 0;
          if (a.rate === null) return -1;
          if (b.rate === null) return 1;
          if (a.rate === "Infinity" && b.rate === "Infinity") return 0;
          if (a.rate === "Infinity") return 1;
          if (b.rate === "Infinity") return -1;
          return parseFloat(a.rate) - parseFloat(b.rate);
        });
      } else if (this.sortActive === "desc") {
        sortedData.sort((a, b) => {
          if (a.rate === null && b.rate === null) return 0;
          if (a.rate === null) return 1; // 将null排在最后
          if (b.rate === null) return -1;
          if (a.rate === "Infinity" && b.rate === "Infinity") return 0;
          if (a.rate === "Infinity") return -1; // 将Infinity排在最前
          if (b.rate === "Infinity") return 1;
          // 转换为数字进行比较并进行降序排列
          return parseFloat(b.rate) - parseFloat(a.rate);
        });
      } else if (this.sortActive === "location") {
        sortedData.sort((a, b) => a.location.localeCompare(b.location));
      }
      // 处理数据
      // if (this.sortActive === "asc") {
      //   sortedData.sort((a, b) => parseFloat(a.rate) - parseFloat(b.rate));
      // } else if (this.sortActive === "desc") {
      //   sortedData.sort((a, b) => parseFloat(b.rate) - parseFloat(a.rate));
      // } else if (this.sortActive === "location") {
      //   sortedData.sort((a, b) => a.location.localeCompare(b.location));
      // }

      sortedData.forEach((item) => {
        categories.push(item.enterpriseName);
        if (!item.rate || item.rate === "Infinity") {
          seriesData.push({
            value: null,
            itemStyle: {
              color: "#ff0000",
            },
          });
        } else {
          seriesData.push({
            value: item.rate,
            itemStyle: {
              color: item.rate >= 0 ? "#5470C6" : "#91CC75",
            },
          });
        }
      });
      that.tableData = sortedData;
      // console.log(sortedData);
      const values = seriesData.map((s) => s.value || 0);
      const minValue = Math.min(...values); // 获取最小值
      const maxValue = Math.max(...values); // 获取最大值

      const minAbs = Math.abs(minValue); // 最小值的绝对值
      const maxAbs = Math.abs(maxValue); // 最大值的绝对值

      // 选择较大的绝对值来设置对称的 minVal 和 maxVal
      const maxBound = Math.max(minAbs, maxAbs);

      const minVal = -maxBound; // 设置最小值为负
      const maxVal = maxBound; // 设置最大值为正

      // console.log(minVal, maxVal);
      // 配置图表
      const option = {
        title: {
          text: "企业同比增速分析",
          left: "center",
        },
        tooltip: {
          trigger: "item",
          formatter: function (params) {
            if (!params.value && params.value !== 0) {
              return `${params.name}<br/>同比增速：数据异常`;
            }
            return `${params.name}<br/>同比增速：${params.value}%`;
          },
        },
        xAxis: {
          type: "category",
          data: categories,
          axisLabel: {
            rotate: 45,
          },
          boundaryGap: true, // 使 x 轴对称居中
        },
        yAxis: {
          type: "value",
          axisLabel: {
            formatter: "{value}%",
          },
          min: minVal,
          max: maxVal,
        },
        series: [
          {
            data: seriesData,
            type: "bar",
            barWidth: "60%",
            label: {
              show: true,
              position: "top",
              formatter: function (params) {
                return params.value === null ? "异常" : params.value + "%";
              },
            },
          },
        ],
        dataZoom: [
          {
            type: "inside",
            start: 0,
            end: 100,
          },
        ],
      };
      this.chart.setOption(option);
      this.sortButtonShow = true;
    },
    generateSeason(years) {
      const currentYear = new Date().getFullYear();
      const currentMonth = new Date().getMonth() + 1;
      const season = new Map();

      years.forEach((year) => {
        if (year === currentYear) {
          // 当前年份，判断当前月份
          if (currentMonth < 1) {
            season.set(year, []);
          } else if (currentMonth < 4) {
            season.set(year, [1]); // 第一季度
          } else if (currentMonth < 7) {
            season.set(year, [1, 2]); // 前两季度
          } else if (currentMonth < 10) {
            season.set(year, [1, 2, 3]); // 前三季度
          } else {
            season.set(year, [1, 2, 3, 4]); // 四个季度
          }
        } else if (year < currentYear) {
          // 过去的年份都包含四个季度
          season.set(year, [1, 2, 3, 4]);
        } else {
          // 未来的年份
          season.set(year, []);
        }
      });

      return season;
    },
    generateMonthlyData(years) {
      const currentYear = new Date().getFullYear();
      const currentMonth = new Date().getMonth() + 1;
      const monthlyData = new Map();
      years.forEach((year) => {
        if (year === currentYear) {
          // 当前年份，判断当前月份
          const months = Array.from({ length: currentMonth }, (_, i) => i + 1);
          monthlyData.set(year, months); // 设置当前年份的已过月份
        } else if (year < currentYear) {
          // 过去的年份包含所有12个月
          monthlyData.set(year, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
        } else {
          // 未来的年份
          monthlyData.set(year, []);
        }
      });

      return monthlyData;
    },
    keyToChineseEtype(num) {
      const item = this.enterTypeList.find((element) => element.number === num);
      return item ? item.name : null;
    },
    renameProperties(obj, mapping) {
      return Object.keys(mapping).reduce((accumulator, currentKey) => {
        const newKey = mapping[currentKey];
        accumulator[newKey] = obj[currentKey];
        return accumulator;
      }, {});
    },
    changSort(sortType) {
      this.sortActive = sortType;
      this.updateChart(this.searchData);
    },
    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; // 都不是数字，保持原顺序
        }
      });
    },
  },
  watch: {
    // littlegreen - 关闭监测数值变化
    selectedDataKey() {
      this.label = "评估指标值" + this.keyToUnit[this.selectedDataKey];
    },
    // selectedYear() {
    //   this.updateChart();
    // },
    // selectedRange() {
    //   setTimeout(this.updateChart, 2500);
    // },
    // selectedCode() {
    //   this.updateChart();
    // },
  },
  computed: {
    seasonOptions() {
      const options = this.rateForm.selectedYear
        ? this.seasonMap.get(this.rateForm.selectedYear)
        : [];
      return options || []; // 以防得到 undefined
    },
    monthOptions() {
      const options = this.rateForm.selectedYear
        ? this.monthMap.get(this.rateForm.selectedYear)
        : [];
      return options || []; // 以防得到 undefined
    },
  },
};
</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>
