<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; grid-gap: 5px"
        label-width="100px"
      >
        <el-form-item label="评估指标">
          <el-select v-model="matchForm.dataKey" 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="matchForm.industry"
            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="matchForm.companyType"
            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-input
            v-model="matchForm.threshold"
            placeholder="请输入内容"
            style="width: 100%"
          ></el-input>
        </el-form-item>
        <!-- 用电:月度;用气:年度;用人:季度 -->
        <el-form-item label="年度">
          <el-select v-model="matchForm.year" 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-if="matchForm.dataKey === 'powerConsume'">
          <div style="display: flex; gap: 5px">
            <el-select v-model="matchForm.elecStartMonth" filterable>
              <el-option
                v-for="key in monthOptions"
                :key="key"
                :label="key"
                :value="key"
              >
              </el-option>
            </el-select>
            <span>-</span>
            <el-select v-model="matchForm.elecEndMonth" filterable>
              <el-option
                v-for="key in monthOptions"
                :key="key"
                :label="key"
                :value="key"
              >
              </el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item
          label="季度"
          v-if="matchForm.dataKey === 'employeeNumber'"
        >
          <div style="display: flex; gap: 5px">
            <el-select v-model="matchForm.manStartSeason" filterable>
              <el-option
                v-for="key in seasonOptions"
                :key="key"
                :label="key"
                :value="key"
              >
              </el-option>
            </el-select>
            <span>-</span>
            <el-select v-model="matchForm.manEndSeason" filterable>
              <el-option
                v-for="key in seasonOptions"
                :key="key"
                :label="key"
                :value="key"
              >
              </el-option>
            </el-select>
          </div>
        </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-table :data="tableData" border>\
      code: "2422"
      enterpriseName: "企业1"
      location: "A"
      trueThreshold: -0.24883973894126177
      typeName: "A"
      typeNum: "1"
      <el-table-column prop="enterpriseName" label="企业名称" sortable></el-table-column>
      <el-table-column
        prop="location"
        label="坐落地"
        width="200" sortable
      ></el-table-column>
      <el-table-column
        prop="code"
        label="行业代码"
        width="200"
      ></el-table-column>
      <el-table-column
        prop="typeName"
        label="企业分类"
        width="200"
      ></el-table-column>
      <el-table-column
        prop="trueThreshold"
        label="相差值"
        width="200" sortable
      ></el-table-column>
    </el-table>
    <el-pagination
      v-show="total > 0"
      :total="total"
      :page.sync="matchForm.pageNum"
      :limit.sync="matchForm.pageSize"
      @pagination="submit"
       >
    </el-pagination>
  </div>
</template>
<script>
import { analysisMatch } from "@/api/analysis/analysis";
import { getYearData } from "@/api/home";
import { listEtypeAll } from "@/api/etype/etype";
import { listAllIndustry } from "@/api/industry/industry"; // 导入行业数据的接口
export default {
  props: {
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "400px",
    },
  },
  data() {
    return {
      total: 0,
      matchForm: {
        pageNum: 1,
        pageSize: 10,
        dataKey: "powerConsume", //评估指标
        industry: "", //行业
        companyType: "", //企业分类
        threshold: null, //相差值阈值
        // 用电
        year: "", //年度 (用电和用人都用这个年度)
        elecStartMonth: "", //起始月
        elecEndMonth: "", //结束月
        // 用人
        manStartSeason: "", //起始季度
        manEndSeason: "", //结束季度
      },
      dataKeys: ["powerConsume", "energyConsume", "employeeNumber"], // 可选项
      keyToChinese: {
        landArea: "用地面积",
        totalIndustrialValue: "工业总产值",
        gdp: "工业增加值",
        taxableIncome: "应税收入",
        paidTax: "实缴税金",
        mainBusinessIncome: "主营业务收入",
        employeeNumber: "从业人员数",
        profit: "利润总额",
        ownerEquity: "所有者权益",
        funding: "研发经费",
        energyConsume: "能源消费量",
        powerConsume: "电力消费量",
      },
      seasonMap: new Map(),
      monthMap: new Map(),
      yearsOptions: [],
      enterTypeList: [],
      enterTypeList: [],
      industryData: [],
      industryMap: new Map(),
      tableData: [],
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.fetchData();
    });
  },
  methods: {
    fetchData() {
      // 获取年份，获取季度、月度
      this.getYearData();
      this.getAllIndustry();
      this.getEtypeAll();
    },
    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) {
          this.industryData = response.rows.map((item) => ({
            key: item.code,
            value: item.code + item.industryName,
          }));
        }
      });
    },

    getEtypeAll() {
      return listEtypeAll().then((res) => {
        this.enterTypeList = res;
        // console.log(this.enterTypeList);
      });
    },
    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;
    },
    submit() {
      // 清除无关字段
      this.clearUnrelatedFields();
      // 必填项校验
      if (this.validateForm()) {
        // this.$message.success("提交成功");
        // console.log(this.matchForm);
        analysisMatch(this.matchForm).then(res=>{
          // console.log(res,"test")
          if(res && res?.rows){
            this.total = res.total;
            this.tableData = res.rows.map(item => {
              return {
                ...item,
                trueThreshold: parseFloat(item.trueThreshold).toFixed(4) // 转换并保留4位小数
              };
            });
          }
        })
      }
    },
    clearUnrelatedFields() {
      const { dataKey } = this.matchForm;
      if (dataKey === "powerConsume") {
        this.matchForm.manStartSeason = "";
        this.matchForm.manEndSeason = "";
      } else if (dataKey === "employeeNumber") {
        this.matchForm.elecStartMonth = "";
        this.matchForm.elecEndMonth = "";
      } else if (dataKey === "energyConsume") {
        this.matchForm.manStartSeason = "";
        this.matchForm.manEndSeason = "";
        this.matchForm.elecStartMonth = "";
        this.matchForm.elecEndMonth = "";
      }
    },

    validateForm() {
      const { matchForm } = this;

      // 行业校验
      if (!matchForm.industry) {
        this.$message.error("请选择行业");
        return false;
      }

      // 阈值校验
      const threshold = parseFloat(matchForm.threshold);
      if (isNaN(threshold)) {
        this.$message.error("请填写有效的相差值阈值");
        return false;
      }
      matchForm.threshold = threshold; // 转换为数字

      // 年度必填校验
      if (!matchForm.year) {
        this.$message.error("请选择年度");
        return false;
      }

      // 针对 powerConsume 的校验
      if (matchForm.dataKey === "powerConsume") {
        if (!matchForm.elecStartMonth) {
          this.$message.error("请选择起始月度");
          return false;
        }
        if (!matchForm.elecEndMonth) {
          this.$message.error("请选择结束月度");
          return false;
        }
        if (matchForm.elecStartMonth > matchForm.elecEndMonth) {
          this.$message.error("起始月度必须小于等于结束月度");
          return false;
        }
      }

      // 针对 employeeNumber 的校验
      if (matchForm.dataKey === "employeeNumber") {
        if (!matchForm.manStartSeason) {
          this.$message.error("请选择起始季度");
          return false;
        }
        if (!matchForm.manEndSeason) {
          this.$message.error("请选择结束季度");
          return false;
        }
        if (matchForm.manStartSeason > matchForm.manEndSeason) {
          this.$message.error("起始季度必须小于等于结束季度");
          return false;
        }
      }

      return true; // 所有校验通过
    },
  },
  computed: {
    seasonOptions() {
      const options = this.matchForm.year
        ? this.seasonMap.get(this.matchForm.year)
        : [];
      return options || []; // 以防得到 undefined
    },
    monthOptions() {
      const options = this.matchForm.year
        ? this.monthMap.get(this.matchForm.year)
        : [];
      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>
