<!-- eslint-disable vue/v-on-event-hyphenation -->
<template>
  <div>
    <a-table
      :columns="tableColumns"
      :data-source="pageData"
      bordered
      :pagination="false"
      :scroll="{ x: 100, 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%">数据报表</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"> 导出 </a-button>
        </div>
      </template>
    </a-table>
    <a-pagination
      :current="queryParams.pageNum"
      :total="total"
      :page-size="queryParams.pageSize"
      style="display: flex; justify-content: center; margin-top: 16px"
      :show-size-changer="true"
      :show-quick-jumper="true"
      @change="onChange" />
  </div>
</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 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 = () => {
    // 拼装开始结束时间
    if (!startDate.value || !endDate.value) {
      const nowDate = new Date();
      let nowDateString = nowDate.toISOString().split('T')[0];
      const [year, month, day] = nowDateString.split('-').map(Number);
      if (frequencyValue.value == '3') {
        startDate.value = year + '-' + month;
        endDate.value = year + '-' + month;
      } else if (frequencyValue.value == '4') {
        startDate.value = year + '';
        endDate.value = year + '';
      }
    }
    let startTime = '';
    let endTime = '';
    if (frequencyValue.value == '3') {
      startTime = startDate.value + '-01';
      const [year, month] = endDate.value.split('-').map(Number);

      // 创建下一个月的第一天
      const date = new Date(year, month, 1);

      // 减去一天得到当月的最后一天
      // date.setDate(date.getDate() - 1);
      endTime = date.toISOString().split('T')[0];
      // endTime = endDate.value + '-01';
    } else if (frequencyValue.value == '4') {
      startTime = startDate.value + '-01-01';
      endTime = endDate.value + '-12-31';
    } else {
      startTime = startDate.value + '';
      endTime = endDate.value + '';
    }
    http
      .post(environmentMonitor.getDeviceAveragesByRate, {
        orgId: orgId.value,
        startTime: startTime, //开始时间
        endTime: endTime, //结束时间

        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],
          });
        }
        let columnA: any[] = [...tableColumnsA];
        columnA.push(...tableColumnsB);
        tableColumns.value = columnA;

        // 数据赋值
        data.value = res.data.data;
        total.value = res.data.data.length;
        onChange(1, 10);
      });
  };
  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;
    }
    // frequencyOptions.value = [
    //   {
    //     value: '1',
    //     label: '30分钟',
    //   },
    //   {
    //     value: '2',
    //     label: '小时',
    //   },
    //   {
    //     value: '3',
    //     label: '天',
    //   },
    //   {
    //     value: '4',
    //     label: '月',
    //   },
    //   {
    //     value: '5',
    //     label: '年',
    //   },
    // ];
    typeList.value = [
      {
        id: 1,
        value: '温度',
      },
      {
        id: 2,
        value: 'CO2浓度',
      },
      {
        id: 3,
        value: 'PM2.5',
      },
      {
        id: 4,
        value: '光照度',
      },
      {
        id: 5,
        value: 'TVOC',
      },
      {
        id: 6,
        value: '湿度',
      },
    ];
    treeData2.value = [
      {
        label: '办公区',
        value: '0-0',
        children: [
          {
            label: '办公一区',
            value: '0-0-0',
          },
          {
            label: '办公二区',
            value: '0-0-1',
          },
          {
            label: '办公三区',
            value: '0-0-2',
          },
          {
            label: '办公四区',
            value: '0-0-3',
          },
        ],
      },
      {
        label: '站厅',
        value: '0-1',

        children: [
          {
            label: '站厅一区',
            value: '0-1-0',
            // disabled: true,
          },
          {
            label: '站厅二区',
            value: '0-1-1',
          },
          {
            label: '站厅三区',
            value: '0-1-2',
          },
          {
            label: '站厅四区',
            value: '0-1-3',
          },
        ],
      },
    ];
    getTableList();
  });

  // 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 {
    padding: 0px 16px;
  }
</style>
<style scoped>
  th.column-money,
  td.column-money {
    text-align: right !important;
  }
</style>
