<template>
  <div class="">
    <a-form labelAlign="left"
            layout="inline" :model="where" :rules="whereRules"

    >

      <a-form-item label="起始日期:">
        <a-input-number id="inputNumber" v-model:value="where.startYear" :min="1970" :max="2050" />
      </a-form-item>
      <a-form-item label="结束日期:">
        <a-input-number id="inputNumber" v-model:value="where.endYear" :min="1970" :max="2050" />
      </a-form-item>
      <a-form-item label="昼夜:">
        <a-select
          :options="timeSlotOptions"
          v-model:value="where.timeSlot"
          placeholder="昼夜"
        >
        </a-select>
      </a-form-item>

      <a-form-item class="ele-text-left" :wrapper-col="{ span: 24 }">
        <a-space>
          <a-button type="primary" @click="reload">查询</a-button>
          <a-button @click="reset">重置</a-button>
          <a-button @click="exportFile">导出Excel</a-button>
        </a-space>
      </a-form-item>
    </a-form>
    <ele-pro-table
      v-if="hisYears.length > 0"
      ref="table"
      row-key="id"
      :datasource="url"
      :columns="columns"
      :where="where"
      :needPage="false"
      :initLoad="false"
      :scroll="{ x: 'max-content' }"
      :method="'POST'"
      @done="(d) => (data = d.data)"
    >
      <template #toolbar>
        <!-- 搜索表单 -->

        <!-- <a-space>

        </a-space> -->
      </template>
    </ele-pro-table>
  </div>
</template>

<script>
// import _ from "lodash";
import XLSX from "xlsx";
import {
  pageRoadNoiseCompare,
  getHistoryyears,
} from "@/api/ecology/noise/road-sound";

export default {
  name: "StatisticSoundRoadCompare",
  components: {},
  data() {

    const groupTimeLengthOptions = [
      {
        label: "年",
        value: "monitor_year",
      },
      {
        label: "季度",
        value: "quarter",
      },
    ];
    const whereRules = {};
    return {
      url: pageRoadNoiseCompare,
      data: [],
      where: {
        groupModel: "area",
        groupTimeLength: "monitor_year",
        reportTimeScope: [],
        valueType: ["index_Leq"],
        timeSlot: "昼",
        timeRange: [],
        regionLevel: "市级"
      },
      timeRange: [],
      whereRules,
      hisYears: [],
      timeScope: [],
      columns: [{title: "年", dataIndex: "year"}],
      groupTimeLengthOptions,
      timeSlotOptions: [
        {
          value: "昼",
          label: "昼",
        },
        {
          value: "夜",
          label: "夜",
        },
      ],
    };
  },
  mounted() {
    getHistoryyears().then((res) => {
      this.hisYears = res.data.data;
      this.$nextTick(() => {
        this.reload();
      });
    });
  },
  methods: {
    /* 刷新表格 */
    reload() {
      if (this.where.valueType.length == 0) {
        this.$message.error("请至少选择一个类型");
        return;
      }

      this.stableDone();
      this.$refs.table.reload({
        where: this.where,
      });
    },
    /* 重置搜索 */
    reset() {
      this.where = {
        groupModel: "area",
        groupTimeLength: "monitor_year",
        reportTimeScope: [],
        valueType: ["index_Leq"],
        timeRange: [],
        timeSlot: "昼",
        regionLevel: "市级"
      };
      this.this.timeScope = [];
      this.reload();
    },
    reportTimeScopeChange(d, dstr) {
      console.log(d, dstr);
    },
    timeRangePanelChange(val) {
      val[0] && (this.where.timeRange[0] = val[0].year());
      val[1] && (this.where.timeRange[1] = val[1].year());
      this.timeRange = val;
    },
    // 数据加载完成
    stableDone() {
      const columns = [];
      if (this.where.groupModel == "area") {
        columns.push({
          title: "城区",
          dataIndex: "area",
          sorter: true,
        });
      } else if (this.where.groupModel == "place") {
        columns.push({
          title: "测点",
          dataIndex: "area",
          sorter: true,
        });
      } else if (this.where.groupModel == "city") {
        columns.push({
          title: "城市",
          dataIndex: "area",
          sorter: true,
        });
      }

      this.hisYears.forEach((item) => {
        if (
          (!this.where.startYear || this.where.startYear <= item) &&
          (!this.where.endYear || !this.where.endYear >= item)
        ) {
          if (this.where.valueType.includes("index_Leq")) {
            columns.push({
              title: item + "年",
              align: "center",
              children: [
                {
                  title: "Leq",
                  dataIndex: item + "Leq",
                  align: "center",
                  customRender: ({text}) => {
                    const val = text ? Number(text).toFixed(1) : "";
                    return val;
                  },
                },
                {
                  title: "等级",
                  align: "center",
                  dataIndex: item + "LeqLevel",
                }
              ]
            });

          }
        }
      });
      //
      this.columns = columns;
    },
    exportFile() {
      const arr = [];
      const th1 = [];
      const th2 = [];
      const merges = []; // 合并
      const columnsTemp = []; // 树形结构整理成list
      this.columns.forEach((item, index) => {
        if (item.children) {
          item.children.forEach(citem => {
            th1.push(item.title)
            th2.push(citem.title)
            columnsTemp.push(citem)
          })
          merges.push({s: {r: 0, c: th1.length - 2}, e: {r: 0, c: th1.length - 1}})
        } else {
          th1.push(item.title)
          th2.push("")
          columnsTemp.push(item)
          merges.push({s: {r: 0, c: index}, e: {r: 1, c: index}})
        }
      })
      arr.push(th1, th2);
      this.data.forEach((d) => {
        const td = columnsTemp.map((item) => {
          if (typeof d[item.dataIndex] == "number") {
            return d[item.dataIndex].toFixed(1);
          }
          return d[item.dataIndex];
        });
        arr.push(td);
      });
      let sheet = XLSX.utils.aoa_to_sheet(arr);
      sheet['!merges'] = merges;
      this.$util.exportSheet(XLSX, sheet, new Date().getTime().toString());
    },
  },
};
</script>

<style scoped>
</style>
