<!-- eslint-disable vue/v-on-event-hyphenation -->
<template>
  <!-- <a-spin :spinning="loading"> -->
  <div style="background: #ffffff; height: 95%; position: relative">
    <a-spin :spinning="loading">
      <a-table
        :columns="tableColumns"
        :data-source="pageData"
        bordered
        :pagination="false"
        style="height: 75%"
        :scroll="{ x: 200, y: 450 }">
        <template #title>
          <div
            style="display: flex; align-items: center; justify-content: space-between; width: 100%">
            <div style="display: flex; align-items: center; width: 85%">
              <div style="width: 10%"
                ><ns-icon name="title" size="11" style="margin-right: 3px" />数据报表</div
              >

              <a-select
                v-model:value="frequencyValue"
                placeholder="请选择频率"
                style="width: 17%; margin-left: 10px"
                :options="frequencyOptions"
                @change="changeFrequency" />
              <!-- <a-date-picker style="width: 13%; margin-left: 10px" v-model:value="timeValue" /> -->
              <!-- :picker="dateTypeValue" -->
              <a-range-picker
                :value="hackValue || dateRange"
                :disabled-date="disabledDate"
                @change="onChangeDate"
                @openChange="onOpenChange"
                @calendarChange="onCalendarChange"
                style="width: 17%; margin-left: 10px"
                :placeholder="['请选择日期', '请选择日期']" />
              <a-button type="primary" style="margin-left: 10px" @click="getTableList">
                查询
              </a-button>
            </div>
            <a-button type="primary" style="position: absolute; right: 40px; top: -45px">
              导出
            </a-button>
          </div>
        </template>
      </a-table>
    </a-spin>
    <a-pagination
      :current="queryParams.pageNum"
      :total="total"
      :show-total="(total, range) => ` 共 ${total} 条`"
      :page-size="queryParams.pageSize"
      style="
        display: flex;
        position: absolute;
        bottom: 20px;
        right: 30px;
        justify-content: right;
        margin-top: 16px;
        margin-right: 30px;
      "
      :show-size-changer="true"
      :show-quick-jumper="true"
      @change="onChange" />
  </div>
  <!-- </a-spin> -->
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  // import { http } from '/nerv-lib/util/http';
  import { Pagination, SelectProps, TreeSelectProps, TableColumnType } from 'ant-design-vue';
  import { tableColumns as tableColumnsA } from './config';
  import type { Dayjs } from 'dayjs';
  import dayjs from 'dayjs';
  import { http } from '/nerv-lib/util';
  import { dict, getEnum } from '/@/api';
  import { environmentMonitor } from '/@/api/monitor';
  // import { energyConsumption } from '/@/api/carbonEmissionFactorLibrary';
  defineOptions({
    name: 'AverageData', // 与页面路由name一致缓存才可生效
    components: {
      'a-pagination': Pagination,
    },
  });

  const loading = ref(false);
  const x = ref(1200);

  const typeList = ref();
  // 采集频率
  const frequencyValue = ref<string | undefined>();

  // 采集频率list
  const frequencyOptions = ref<SelectProps['options']>([]);

  const treeData2 = ref<TreeSelectProps['treeData']>([]);
  const data = ref([]);
  const pageData = ref([]);
  let tableColumns = ref<TableColumnType[]>([]);

  const total = ref<number>();
  const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
  });
  const orgId = ref('');
  const result = JSON.parse(sessionStorage.getItem('ORGID')!);
  orgId.value = result;

  type RangeValue = [Dayjs, Dayjs];
  const dates = ref<RangeValue>();
  const hackValue = ref<RangeValue>();
  const dateRange = ref<[Dayjs, Dayjs] | undefined>([dayjs(), dayjs()]);
  // const dateTypeValue = ref<string | undefined>('year');
  const startDate = ref<String>();
  const endDate = ref<String>();

  const onChangeDate = (val: RangeValue, dateStrings: any) => {
    dateRange.value = val;
    if (dateStrings && dateStrings.length === 2) {
      startDate.value = dateStrings[0];
      endDate.value = dateStrings[1];
    }
  };
  const onOpenChange = (open: boolean) => {
    if (open) {
      dates.value = [] as any;
      hackValue.value = [] as any;
    } else {
      hackValue.value = undefined;
    }
  };
  const disabledDate = (current: Dayjs) => {
    if (frequencyValue.value == '1' || frequencyValue.value == '2') {
      if (!dates.value || (dates.value as any).length === 0) {
        return false;
      }
      const tooLate = dates.value[0] && current.diff(dates.value[0], 'days') > 6;
      const tooEarly = dates.value[1] && dates.value[1].diff(current, 'days') > 6;
      return tooEarly || tooLate;
    }
  };
  const onCalendarChange = (val: RangeValue) => {
    dates.value = val;
  };
  // 切换频率
  const changeFrequency = () => {
    //
    // if (frequencyValue.value == '0' || frequencyValue.value == '1' || frequencyValue.value == '2') {
    //   dateTypeValue.value = 'date';
    // } else if (frequencyValue.value == '3') {
    //   dateTypeValue.value = 'month';
    // } else if (frequencyValue.value == '4') {
    //   dateTypeValue.value = 'year';
    // }
    dateRange.value = undefined;
  };
  // 获取表格数据
  const getTableList = () => {
    loading.value = true;
    // 拼装开始结束时间
    if (!startDate.value || !endDate.value) {
      const nowDate = new Date();
      let nowDateString = nowDate.toISOString().split('T')[0];
      const [year, month, day] = nowDateString.split('-').map(Number);
      startDate.value = year + '-' + month + '-' + day;
      endDate.value = year + '-' + month + '-' + day;
    }
    http
      .post(environmentMonitor.getDeviceAveragesByRate, {
        orgId: orgId.value,
        startTime: startDate.value, //开始时间
        endTime: endDate.value, //结束时间

        timeRate: frequencyValue.value, // 频率
      })
      .then((res) => {
        // 拼接表头
        let headerList = res.data.headerList;
        let tableColumnsB = [];
        for (let i = 0; i < headerList.length; i++) {
          tableColumnsB.push({
            title: headerList[i],
            dataIndex: headerList[i],
            width: 150,
            align: 'center',
          });
        }
        x.value = 300 + headerList.length * 150;
        let columnA: any[] = [...tableColumnsA];
        columnA.push(...tableColumnsB);
        tableColumns.value = columnA;

        // 数据赋值
        data.value = res.data.data;
        total.value = res.data.data.length;
        onChange(1, 10);
      })
      .finally(() => {
        loading.value = false;
      });
  };
  onMounted(async () => {
    // 获取频率
    let frequency = await getEnum({ params: { enumType: 'TimeFlagEnum' } });
    frequencyOptions.value = frequency.data;
    if (frequencyOptions.value && frequencyOptions.value.length > 0) {
      frequencyValue.value = frequencyOptions.value[frequencyOptions.value.length - 1].value;
    }
    getTableList();
  });

  // 分页器
  const onChange = (pageNumber: number, size: number) => {
    queryParams.value.pageNum = pageNumber;
    queryParams.value.pageSize = size;

    const start = (pageNumber - 1) * size;
    const end = start + size;
    pageData.value = data.value.slice(start, end);
    // getTableList();
  };
</script>
<style scoped lang="less">
  ::v-deep .ant-table-title {
    display: flex;
  }
  ::v-deep .ant-table-container {
    margin: 0px 16px;
  }
</style>
<style scoped>
  th.column-money,
  td.column-money {
    text-align: right !important;
  }
  ::v-deep .ant-table.ant-table-bordered > .ant-table-title {
    border: none !important;
  }
  /* ::v-deep .ant-table-title + .ant-table-container table > thead > tr:first-child th:last-child {
    display: none !important;
  } */
</style>
