<template>
  <div>
    <BasicTable :clickToRowSelect="false" @register="registerTable">
      <template #toolbar>
        <Authority>
          <a-button type="primary"
            @click="exportData(dataCenter.exportColumns, dataCenter.dataSourceArr, '雨情历史查询.xlsx')">导出</a-button>
        </Authority>
      </template>
    </BasicTable>
  </div>
</template>
<script lang="tsx" setup>
import { defineComponent, ref, watch, onMounted, reactive } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { ImpExcel, ExcelData, jsonToSheetXlsx } from '/@/components/Excel';
import { exportData } from '/@/utils/fnUtils.ts';
import moment from 'moment';
import {
  getDataHistRainStatios,
  gethistoryRain2
} from '/@/api/swHome/index';
import { getNowTime } from '/@/utils/fnUtils.ts';
let dataCenter = reactive({
  oneTitle: '',
  showSchemasType: 'H',
  nameArr: [],
  modalTime: '',
  Modal1Sendid: '',
  showModal: false,
  showModal1: false,
  basicModalTitle: '降雨量',
  cahrtsList: [],
  timeData: {
    time: [],
  },
  dataSourceArr: [],
  columns: [],
  exportColumns: [],
  cahrtsData: [],
  searchFormSchema: [
    {
      field: 'senid',
      label: '监测站点:',
      component: 'Select',
      colProps: { span: 5 },
      componentProps: {
        options: [],
        mode: 'multiple',
        maxTagCount: 1
      },
    },
    {
      field: 'step_size',
      label: '时段类型:',
      component: 'RadioGroup',
      colProps: { span: 7 },
      defaultValue: 'H',
      componentProps: {
        options: [
          { label: '实时', value: 'R' },
          { label: '小时', value: 'H' },
          { label: '日', value: 'D' },
          { label: '月', value: 'M' },
          { label: '年', value: 'Y' },
        ],
        onChange: (value) => {
          console.log(value.target.value)
          if (value.target.value == 'R') {
            dataCenter.showSchemasType = 'D'
          } else {
            dataCenter.showSchemasType = 'H'
          }
        },
      },
    },
    {
      field: 'queryTime',
      label: '查询时间:',
      colProps: { span: 6 },
      component: 'RangePicker',
      componentProps: {
        showTime: {
          format: 'HH',
        },
        format: "YYYY-MM-DD HH",
        valueFormat: 'YYYY-MM-DD HH'
      },
      ifShow: () => {
        return dataCenter.showSchemasType == 'H';
      },
    },
    {
      field: 'queryTime',
      label: '查询时间:',
      colProps: { span: 6 },
      component: 'RangePicker',
      componentProps: {
        showTime: {
          format: 'YYYY-MM-DD HH:mm:ss',
        },
      },
      ifShow: () => {
        return dataCenter.showSchemasType == 'D';
      },
    },
    {
      field: 'monthQueryTime',
      label: '查询时间:',
      colProps: { span: 6 },
      component: 'RangePicker',
      componentProps: {
        format: 'YYYY-MM',
        valueFormat: 'YYYY-MM',
        mode: ['month', 'month'],
        onPanelChange: monthPanelChange,
        // open: monthPickShow.value,
      },
      ifShow: () => {
        return dataCenter.showSchemasType == 'M';
      },
    },
    {
      field: 'yearQueryTime',
      label: '查询时间:',
      colProps: { span: 6 },
      component: 'RangePicker',
      componentProps: {
        format: 'YYYY',
        valueFormat: 'YYYY',
        mode: ['year', 'year'],
        onPanelChange: yearPanelChange,
      },
      ifShow: () => {
        return dataCenter.showSchemasType == 'Y';
      },
    },
  ],
});
const [registerTable, { reload, getRawDataSource, getForm, setLoading, setColumns, setTableData }] =
  useTable({
    title: '雨情历史查询',
    // api: gethistoryRain2,
    columns: dataCenter.columns,
    showIndexColumn: false,
    clickToRowSelect: false,
    pagination: false,
    loading: false,
    immediate: false,
    formConfig: {
      labelWidth: 120,
      schemas: dataCenter.searchFormSchema,
      fieldMapToTime: [['queryTime', ['start_time', 'end_time'], 'YYYY-MM-DD HH:mm:ss']],
      actionColOptions: {
        span: 5,
      },
    },
    beforeFetch: (params: any) => {
      let senid;
      if (params.senid) {
        senid = params.senid;
      } else {
        senid = [];
      }
      let start_time = ''
      let end_time = ''
      if (dataCenter.showSchemasType == 'H') {
        start_time = params.start_time.split(':')[0] + '00:00';
        end_time = params.end_time.split(':')[0] + '00:00';
      } else {
        start_time = params.start_time;
        end_time = params.end_time;
      }
      //判断查询模式
      // if (dataCenter.showSchemasType == 'D') {
      //   start_time = params.dayQueryTime[0];
      //   end_time = params.dayQueryTime[1];
      // }
      // if (dataCenter.showSchemasType == 'M') {
      //   start_time = moment(params.monthQueryTime[0]).format('YYYY-MM');
      //   end_time = moment(params.monthQueryTime[1]).format('YYYY-MM');
      // }
      // if (dataCenter.showSchemasType == 'Y') {
      //   start_time = moment(params.yearQueryTime[0]).format('YYYY');
      //   end_time = moment(params.yearQueryTime[1]).format('YYYY');
      // }
      return {
        senid: senid,
        step_size: params.step_size,
        start_time: start_time,
        end_time: end_time,
      };
    },
    handleSearchInfoFn: (params) => {

      getList(params)
    },
    afterFetch: (data) => {
      processingData(data);
    },
    sortFn: (info) => {
      if (info.order == 'descend') {
        dataArr.sort((a, b) => {
          let aNum = a[info.field] == '--' ? -1 : a[info.field] * 1
          let bNum = b[info.field] == '--' ? -1 : b[info.field] * 1
          if (aNum < bNum) return 1;
          if (aNum > bNum) return -1;
          return 0;
        });
      }
      if (info.order == 'ascend') {
        dataArr.sort((a, b) => {
          let aNum = a[info.field] == '--' ? -1 : a[info.field] * 1
          let bNum = b[info.field] == '--' ? -1 : b[info.field] * 1
          if (aNum < bNum) return -1;
          if (aNum > bNum) return 1;
          return 0;
        });
      }
      setTableData(dataArr);
    },
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    rowKey: 'id',
    fetchSetting: {
      listField: 'data',
    },
  });
// 月份选择
function monthPanelChange(value) {
  getForm().setFieldsValue({
    monthQueryTime: [moment(value[0]).format('YYYY-MM'), moment(value[1]).format('YYYY-MM')],
  });
}
// 年份选择
function yearPanelChange(value) {
  getForm().setFieldsValue({
    yearQueryTime: [moment(value[0]).format('YYYY'), moment(value[1]).format('YYYY')],
  });
}
let dataArr = []
const processingData = (pageData) => {
  // 处理头部数据
  let columns = [
    {
      title: '站名',
      dataIndex: 'name',
      key: 'name',
      width: 100,
      align: 'center',
      fixed: 'left',
    },
  ];
  let dataSource = [];
  let titleArr = []
  pageData.time.forEach((element) => {
    if (element != '最小值' && element != '最大值' && element != '站名' && element != '累积降雨量') {
      let dayArr = element.split(' ')
      let daySt = dayArr[0]
      let timeSt = dayArr[1]
      titleArr.push(daySt)
    }
  });
  // 最上层title去重
  let arrWithoutDuplicates = Array.from(new Set(titleArr));
  arrWithoutDuplicates.forEach(element => {
    let obj1 = {
      title: element,
      dataIndex: element,
      key: element,
      children: []
    }
    columns.push(obj1);
  });
  pageData.time.forEach((element) => {
    if (element != '最小值' && element != '最大值' && element != '站名' && element != '累积降雨量') {
      console.log(element)
      let dayArr = element.split(' ')
      let daySt = dayArr[0]
      let timeSt = dayArr[1]
      columns.forEach(elements => {
        if (elements.title != '最小值' && elements.title != '最大值' && elements.title != '站名' && elements.title != '累积降雨量') {
          if (elements.title == daySt) {
            elements.children.push({
              title: timeSt,
              dataIndex: element,
              key: element,
              width: 100,
              align: 'center',
              sorter: true
            })
          }
        }
      });
    } else {
      let obj1 = {
        title: element,
        dataIndex: element,
        key: element,
        width: 160,
        align: 'center',
        sorter: true
      }
      if (element == '最小值') {
        obj1.customCell = (record) => {
          if (record) {
            return {
              style: {
                background: 'rgba(15, 177, 94, 0.06)',
              },
            };
          }
        };
        obj1.width = 100
      }
      if (element == '最大值') {
        obj1.customCell = (record) => {
          if (record) {
            return {
              style: {
                background: 'rgba(255, 52, 52, 0.06)',
              },
            };
          }
        };
        obj1.width = 100
      }
      if (element == '累积降雨量') {
        obj1.customCell = (record) => {
          if (record) {
            return {
              style: {
                background: 'rgba(45, 116, 231, 0.06)',
              },
            };
          }
        };
        obj1.width = 120
      }
      columns.push(obj1);
    }
  })
  dataCenter.exportColumns = [
    {
      title: '站名',
      dataIndex: 'name',
      key: 'name',
      width: 100,
      align: 'center',
      fixed: 'left',
    },
  ]
  // 处理时间列
  pageData.time.forEach((element) => {
    let obj1 = {
      title: element,
      dataIndex: element,
      key: element,
      width: 160,
      align: 'center',
      sorter: true
    }
    dataCenter.exportColumns.push(obj1);
  });
  pageData.name.forEach((element) => {
    dataSource.push({
      name: element,
    });
  });
  dataSource.forEach((element) => {
    for (const key in pageData.value) {
      if (Object.prototype.hasOwnProperty.call(pageData.value, key)) {
        const item = pageData.value[key];
        element[key] = item[element.name];
      }
    }
  });
  setTimeout(() => {
    setColumns(columns);
    dataArr = dataSource
    setTableData(dataSource);
    dataCenter.dataSourceArr = dataSource
  }, 100);
}
// 获取查询树状数据
const getRiveTreeData = async () => {
  await getDataHistRainStatios().then((res) => {
    res.data.forEach((element) => {
      element.label = element.sensor_name;
      element.value = element.senid;
    });
    dataCenter.searchFormSchema[0].componentProps.options = res.data;
  });
}
const getList = (formData) => {
  let form = JSON.parse(JSON.stringify(formData))
  let start_time = ''
  let end_time = ''
  if (dataCenter.showSchemasType == 'H') {
    start_time = form.start_time.split(':')[0] + ':00:00';
    end_time = form.end_time.split(':')[0] + ':00:00';
  } else {
    start_time = form.start_time;
    end_time = form.end_time;
  }
  form.start_time = start_time
  form.end_time = end_time
  setLoading(true)
  gethistoryRain2(form).then(res => {
    processingData(res.data);
    setLoading(false)
  })
}
onMounted(async () => {
  await getRiveTreeData();
  // 设置默认前10个站点为查询字段
  let senidList = dataCenter.searchFormSchema[0].componentProps.options
  let senidArr = []
  senidList.forEach((element, index) => {
    if (index <= 9) {
      senidArr.push(element.senid)
    }
  });
  getForm().setFieldsValue({
    queryTime: [getNowTime(2), getNowTime(1)],
    senid: senidArr
  });
  setTimeout(() => {
    getList(getForm().getFieldsValue())
  }, 0);
});
</script>
<style scoped lang="less">
.form-box {
  position: absolute;
  z-index: 9;
  width: 66.6666%;

  .custom-input {
    width: calc(100% - 100px);
  }
}

.span-label {
  width: 90px;
  padding-right: 10px;
  display: inline-block;
  text-align: right;
  line-height: 32px;
}

.marg-left {
  margin-left: 10px;
}

.ant-table-striped-modal {
  margin-top: 20px;
}

.box-basic {
  height: calc(100% - 46px);
  width: calc(100% - 28px);
  position: absolute;
  // min-height: 600px;
}

.moddal-box {
  display: flex;
  height: calc(100% - 32px);

  .left-box {
    width: 140px;
    overflow: hidden;
    height: 100%;
    background-color: #f4f4f4;

    ul {
      padding: 10px;

      li {
        line-height: 40px;
        padding-left: 10px;
        cursor: pointer;
      }
    }
  }

  .center-box {
    flex: 1;
    overflow: hidden;
    height: 100%;
    margin-left: 20px;
  }

  .right-box {
    width: 400px;
    height: 100%;
    overflow: auto;
    margin-left: 20px;
    position: relative;

    ul {

      // position: relative;
      li {
        display: flex;
        line-height: 36px;

        &>div {
          // flex: 1;
          text-align: center;
        }

        &>div:nth-child(1) {
          min-width: 180px;
        }

        &>div:nth-child(2) {
          flex: 1;
        }

        &>div:nth-child(3) {
          flex: 1;
        }
      }

      li:nth-child(1) {
        position: absolute;
        width: 100%;
      }

      li:nth-child(2) {
        padding-top: 36px;
      }
    }
  }
}

.top-search {
  padding-bottom: 10px;
}

.active-tab {
  background-color: #ccc;
}
</style>
