<template>
  <div>
    <BasicTable :clickToRowSelect="false" @register="registerTable">
      <template #toolbar>
        <Authority>
          <a-button type="primary" @click="exportData(dataCenter.columns,dataCenter.exportdataSource,'标准气象站.xlsx')">导出</a-button>
        </Authority>
      </template>
    </BasicTable>
    <!-- 弹窗1 -->
    <BasicModal
      :maskClosable="false"
      :footer="null"
      @cancel="cancel"
      :visible="dataCenter.showModal"
      :width="1200"
      :minHeight="600"
      :title="dataCenter.basicModalTitle"
    >
      <div class="box-basic">
        <div class="top-search">
          时间范围：
          <a-range-picker
            :value="dataCenter.timeData.time"
            :show-time="{ format: 'HH:mm:ss' }"
            format="YYYY-MM-DD HH:mm:ss"
            :placeholder="['开始时间', '结束时间']"
            @change="onChange"
            :allowClear="true"
          />
          <a-button @click="getHistoryRain" class="marg-left" type="primary">查询</a-button>
        </div>
        <div class="moddal-box" id="myElement"> </div>
      </div>
    </BasicModal>
    <!-- 弹窗2 -->
    <BasicModal
      :maskClosable="false"
      :footer="null"
      @cancel="cancel1"
      :visible="dataCenter.showModal1"
      :width="1200"
      :minHeight="600"
      title="降雨量(多站)"
    >
      <div class="box-basic">
        <div class="top-search"> 时间范围：{{ dataCenter.modalTime }} </div>
        <div class="moddal-box" id="myElement2"> </div>
      </div>
    </BasicModal>
  </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 elementResizeDetectorMaker from 'element-resize-detector';
let erd = elementResizeDetectorMaker(); //创建实例
import moment from 'moment';
import { BasicModal } from '/@/components/Modal/index';
import {
  getHistoryRainList,
  getDataHistRainStatios,
  getMonitorInfo,
  getHistoryTimeInquire,
} from '/@/api/swHome/index';
import { getNowTime } from '/@/utils/fnUtils.ts';
import * as echarts from 'echarts';
let dataCenter = reactive({
  oneTitle:'',
  showSchemasType: 'H',
  nameArr: [],
  modalTime: '',
  Modal1Sendid: '',
  showModal: false,
  showModal1: false,
  basicModalTitle: '降雨量',
  cahrtsList: [],
  timeData: {
    time: [],
  },
  columns: [],
  cahrtsData: [],
  searchFormSchema: [
    {
      field: 'senid',
      label: '监测站点:',
      component: 'Select',
      colProps: { span: 6 },
      componentProps: {
        options: [],
        mode: 'multiple',
        maxTagCount:1
      },
    },
    {
      field: 'step_size',
      label: '时段类型:',
      component: 'RadioGroup',
      colProps: { span: 6 },
      defaultValue: 'H',
      componentProps: {
        options: [
          { label: '实时', value: 'R' },
          { label: '小时', value: 'H' },
          { label: '日', value: 'D' },
          { label: '月', value: 'M' },
          { label: '年', value: 'Y' },
          
          
          
        ],
        // onChange: handleCustomerChange,
      },
    },
    {
      field: 'queryTime',
      label: '查询时间:',
      colProps: { span: 6 },
      component: 'RangePicker',
      componentProps: {
        showTime: {
          format: 'YYYY-MM-DD HH:mm:ss',
        },
      },
      ifShow: () => {
        return dataCenter.showSchemasType == 'H';
      },
    },
    {
      field: 'dayQueryTime',
      label: '查询时间:',
      colProps: { span: 6 },
      component: 'RangePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
      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: getHistoryRainList,
    columns: dataCenter.columns,
    showIndexColumn: false,
    clickToRowSelect: false,
    pagination: false,
    loading: false,
    immediate: false,
    dataSource: [],
    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 = params.start_time;
      let 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,
      };
    },
    afterFetch: (data) => {
      setTitle(data);
    },
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    rowKey: 'id',
    fetchSetting: {
      listField: 'data.value',
    },
  });
// 月份选择
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')],
  });
}

function handleCustomerChange(e) {
  dataCenter.timeData.time = [];
  dataCenter.showSchemasType = e.target.value;
}
// 弹窗处理
function cancel(e) {
  dataCenter.showModal = false;
}
function cancel1() {
  dataCenter.showModal1 = false;
}
// 弹窗点击查询
async function getHistoryRain() {
  singleStation();
}
function onChange(value, dateString) {
  dataCenter.timeData.time = dateString;
}
// 获取查询树状数据
function getRiveTreeData() {
  getDataHistRainStatios().then((res) => {
    res.data.forEach((element) => {
      element.label = element.sensor_name;
      element.value = element.senid;
    });
    dataCenter.searchFormSchema[0].componentProps.options = res.data;
  });
}
// 通过name匹配sinid
function setOptionsNmae(name) {
  dataCenter.nameArr = [];
  let senid = '';
  dataCenter.searchFormSchema[0].componentProps.options.forEach((element) => {
    if (element.sensor_name == name) {
      senid = element.senid;
    }
  });
  return senid;
}
// 处理头部数据
function setTitle(data) {
  let columns = [];
  columns.push({
    title: '时间',
    dataIndex: 'time',
    key: 'time',
    width: 200,
    customRender: ({ record, column, index, text }) => {
      // customRender的返回值要遵循vue-jsx语法,要加()和换行
      return <a onClick={handleTitle.bind(record, column, text)}>{text}</a>;
    },
    ellipsis: false,
  });
  let num = 0;
  let tabdata = [];
  data.forEach((dataItem, dataIndex) => {
    num++;
    let partition = {};
    const element = dataItem.detail;
    // console.log(element);
    partition.title = dataItem.name;
    partition.dataIndex = dataItem.name;
    // partition.width = 200;
    partition.key = 'partition' + num;
    partition.children = [];
    for (const elements in element['最大值']) {
      let content = element['最大值'][elements];
      partition.children.push({
        title: elements,
        dataIndex: elements,
        key: elements,
        width: elements.length*20,
        ellipsis: 'auto',
        customRender: ({ record, column, index, text }) => {
          // customRender的返回值要遵循vue-jsx语法,要加()和换行
          return <div onClick={handleTitle.bind(record, column, text)}>{text}</div>;
        },
      });
    }
    // console.log(partition);
    // 列表数据处理
    let index = 0;
    for (const elements in element) {
      let contentObj = {};
      let item = element[elements];
      contentObj.time = elements;
      for (const key1 in item) {
        let item1 = item[key1];
        if (tabdata.length != Object.keys(element).length) {
          contentObj[key1] = item1;
        } else {
          tabdata[index][key1] = item1;
        }
      }
      if (tabdata.length != Object.keys(element).length) {
        tabdata.push(contentObj);
      }
      index++;
    }
    columns.push(partition);
  });
  setTimeout(() => {
    dataCenter.exportColumns = columns
    dataCenter.exportdataSource = tabdata
    setTableData(tabdata);
    setColumns(columns);
  }, 100);
}
function handleTitle(record, text, column) {
  // console.log(text);
  // console.log(column);
  console.log(record.key);
  // 点击时间
  if (record.customTitle == '时间' && text != '最小值' && text != '最大值') {
    dataCenter.showModal1 = true;
    multistation(text);
  }
  if (record.customTitle != '时间') {
    dataCenter.timeData.time = [getNowTime(2), getNowTime(1)];
    dataCenter.oneTitle = `${record.key}`
    dataCenter.basicModalTitle = `降雨量(${record.key})`;
    dataCenter.showModal = true;
    dataCenter.Modal1Sendid = setOptionsNmae(record.key);
    singleStation();
  }
  setTimeout(() => {
    erd.listenTo(document.getElementById('myElement'), () => {
      if (chart) {
        chart.resize();
      }
    });
    erd.listenTo(document.getElementById('myElement2'), () => {
      if (chart2) {
        chart2.resize();
      }
    });
  }, 300);
}
// 查询多站
function multistation(time) {
  let hostData = {
    time: time,
    senid: [],
    step_size:getForm().getFieldsValue().step_size
  };
  dataCenter.nameArr = getRawDataSource().data.head;
  dataCenter.nameArr.forEach((element) => {
    dataCenter.searchFormSchema[0].componentProps.options.forEach((elements) => {
      if (
        elements.sensor_name == element
      ) {
        console.log(elements.sensor_name);
        console.log(element);
        hostData.senid.push(elements.senid);
      }
    });
  });
  dataCenter.modalTime = time;
  getHistoryTimeInquire(hostData).then((res) => {
    let echarts2Data = {
      name: [],
      value: [],
    };
    res.data.forEach((element) => {
      echarts2Data.name.push(element.st_name);
      echarts2Data.value.push(element.value);
    });
    echarts2(echarts2Data);
  });
}
// 查询单一测站
async function singleStation() {
  let historyFormData = {};
  historyFormData.senid = dataCenter.Modal1Sendid;
  historyFormData.start_time = dataCenter.timeData.time[0] ? dataCenter.timeData.time[0] : '';
  historyFormData.end_time = dataCenter.timeData.time[1] ? dataCenter.timeData.time[1] : '';
  let activeInfoData = await getMonitorInfo(historyFormData).then((res) => {
    return res.data;
  });
  dataCenter.cahrtsData = activeInfoData;
  setTimeout(() => {
    setCharts();
  }, 0);
}
// 处理charts数据
function setCharts() {
  dataCenter.cahrtsList.time = [];
  dataCenter.cahrtsList.data = [];
  dataCenter.cahrtsData.forEach((element) => {
    dataCenter.cahrtsList.time.push(element.time);
    dataCenter.cahrtsList.data.push(element.factv);
  });
  echarts1();
}
// 图表
let chart;
let chart2;
function echarts1() {
  chart = echarts.init(document.getElementById('myElement'));
  var option = {
    
    toolbox: {
        feature: {
          saveAsImage: {
            name:dataCenter.basicModalTitle
          }
        }
      },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
      formatter(params) {
        var relVal = params[0].name;
        for (var i = 0, l = params.length; i < l; i++) {
          console.log('tooltip数据值', params[i].value);
          //遍历出来的值一般是字符串，需要转换成数字，再进项tiFixed四舍五入
          relVal +=
            '<br/>' + params[i].marker + dataCenter.oneTitle +' : ' + Number(params[i].value);
        }
        return relVal;
      },
    },
    xAxis: {
      type: 'category',
      data: dataCenter.cahrtsList.time,
      axisLabel: {
        //x轴文字的配置
        show: true,
        textStyle: {
          color: '#333',
        },
        formatter: function (val) {
          var strs = val.split(''); //字符串数组
          var str = '';
          for (var i = 0, s; (s = strs[i++]); ) {
            //遍历字符串数组
            if (i > 5 && i < 17) {
              str += s;
            }

            if (!(i % 10)) str += '\n'; //按需要求余
          }
          return str;
        },
      },
    },
    yAxis: {
      type: 'value',
      name: '单位：mm',
      scale: true,
      axisLabel: {
        //y轴文字的配置
        textStyle: {
          color: '#333',
          margin: 15,
        },
        formatter: function (value) {
          return value + '';
        },
        // formatter: '{value} %'//y轴的每一个刻度值后面加上‘%’号
      },
      splitLine: {
        //网格线
        lineStyle: {
          type: 'dashed', //设置网格线类型 dotted：虚线 solid:实线
          width: 1, //y轴线的宽度
          color: '#ccc',
        },
        show: true, //隐藏或显示
      },
    },
    series: [
      {
        data: dataCenter.cahrtsList.data,
        type: 'bar',
        smooth: true,
      },
    ],
  };
  option && chart.setOption(option);
}
function echarts2(echarts2Data) {
  chart2 = echarts.init(document.getElementById('myElement2'));
  var option = {
    toolbox: {
      feature: {
        saveAsImage: {
          name: `降雨量(多站)`
        }
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
      formatter(params) {
        var relVal = params[0].name;
        for (var i = 0, l = params.length; i < l; i++) {
          console.log('tooltip数据值', params[i].value);
          //遍历出来的值一般是字符串，需要转换成数字，再进项tiFixed四舍五入
          relVal +=
            '<br/>' + params[i].marker  + Number(params[i].value);
        }
        return relVal;
      },
    },
    xAxis: {
      type: 'category',
      data: echarts2Data.name,
      axisLabel: {
        //x轴文字的配置
        show: true,
        textStyle: {
          color: '#333',
        },
        // formatter: function (val) {
        //   var strs = val.split(''); //字符串数组
        //   var str = '';
        //   for (var i = 0, s; (s = strs[i++]); ) {
        //     //遍历字符串数组
        //     if (i > 5 && i < 17) {
        //       str += s;
        //     }

        //     if (!(i % 10)) str += '\n'; //按需要求余
        //   }
        //   return str;
        // },
      },
    },
    yAxis: {
      type: 'value',
      name: '单位：mm',
      scale: true,
      axisLabel: {
        //y轴文字的配置
        textStyle: {
          color: '#333',
          margin: 15,
        },
        formatter: function (value) {
          return value + '';
        },
        // formatter: '{value} %'//y轴的每一个刻度值后面加上‘%’号
      },
      splitLine: {
        //网格线
        lineStyle: {
          type: 'dashed', //设置网格线类型 dotted：虚线 solid:实线
          width: 1, //y轴线的宽度
          color: '#ccc',
        },
        show: true, //隐藏或显示
      },
    },
    series: [
      {
        data: echarts2Data.value,
        type: 'bar',
        smooth: true,
      },
    ],
  };
  option && chart2.setOption(option);
}
const exportData = () => {
  let header = {};
  dataCenter.exportColumns.forEach((element) => {
    if(element.title == '时间'){
      header[element.key] = element.title ? element.title : 'time';
    }else{
      element.children.forEach(elements => {
        header[elements.key] = elements.title ? elements.title : 'time';
      });
    }
  });
  jsonToSheetXlsx({
    data:dataCenter.exportdataSource,
    header: header,
    filename: '雨情历史查询.xlsx',
  });
}
onMounted(async () => {
  getRiveTreeData();
  // setTimeout(() => {
  // dataCenter.searchFormSchema[2].defaultValue = [getNowTime(2), getNowTime(1)];
  // }, 1000);
  getForm().setFieldsValue({
    queryTime: [getNowTime(2), getNowTime(1)],
  });
  setTimeout(() => {
    reload();
  }, 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>
