<template>
  <div>
    <BasicTable :clickToRowSelect="false" @register="registerTable">
      <template #tableTitle>
        多站点气象{{dataCenter.exportNama}}历史查询
      </template>
      <template #toolbar>
        <Authority>
          <a-button type="primary" @click="exportData()">导出</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="myElement5"> </div>
      </div>
    </BasicModal>
    <!-- 弹窗2 -->
    <BasicModal
      :maskClosable="false"
      :footer="null"
      @cancel="cancel1"
      :visible="dataCenter.showModal1"
      :width="1200"
      :minHeight="600"
      :title="dataCenter.customTitle+'(多站)'"
    >
      <div class="box-basic">
        <div class="top-search"> 时间范围：{{ dataCenter.modalTime }} </div>
        <div class="moddal-box" id="myElement4"> </div>
      </div>
    </BasicModal>
  </div>
</template>

<script lang="tsx" setup>
import { defineComponent, ref, onMounted, reactive } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { getUserPage } from '/@/api/log/logManager';
import { BasicModal } from '/@/components/Modal/index';
import moment from 'moment';
import elementResizeDetectorMaker from 'element-resize-detector';
let erd = elementResizeDetectorMaker(); //创建实例
import * as echarts from 'echarts';
import { getNowTime, getMonth, getYear } from '/@/utils/fnUtils.ts';
import { ImpExcel, ExcelData, jsonToSheetXlsx } from '/@/components/Excel';
import {
  getDataHistWeaElement,
  getDataHistWeaStations,
  getDataHistQueryOneElement,
  getHistoryTimeInquire,
  getMonitorInfo,
} from '/@/api/swHome/index';
import { useModal } from '/@/components/Modal';
import eventBus from '/@/utils/eventBus';
let dataCenter = reactive({
  unitTitle:'',
  customTitle:'',
  showSchemasType: 'H',
  cahrtsData: [],
  cahrtsList: [],
  modalTime: '',
  basicModalTitle: '降雨量',
  Modal1Sendid: '',
  timeData: {
    time: [],
  },
  nameArr: [],
  columnsArr: [],
  listArr: [],
  showModal1: false,
  showModal: false,
  exportNama:'',
  searchFormSchema: [
    {
      field: 'queryMode',
      label: '查询模式:',
      component: 'RadioGroup',
      colProps: { span: 7 },
      defaultValue: '1',
      componentProps: {
        options: [
          { label: '单要素', value: '1' },
          { label: '单站点', value: '2' },
        ],
        onChange: (e) => {
          eventBus.emit('setShowType', e.target.value);
        },
      },
    },
    {
      field: 'dchar',
      label: '要素:',
      component: 'Select',
      colProps: { span: 7 },
      componentProps: {
        options: [],
        placeholder: '单选',
        onChange: (e) => {
          itemDchar(e)
        },
      },
    },
    {
      field: 'stcdList',
      label: '监测站点:',
      component: 'Select',
      colProps: { span: 8 },
      componentProps: {
        options: [],
        mode: 'multiple',
        placeholder: '多选',
        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: handleCustomerChange,
      },
    },
    {
      field: 'queryTime',
      label: '查询时间:',
      colProps: { span: 7 },
      component: 'RangePicker',
      componentProps: {
        showTime: {
          format: 'YYYY-MM-DD HH:mm:ss',
        },
      },
      ifShow: () => {
        return dataCenter.showSchemasType == 'H';
      },
    },
    {
      field: 'dayQueryTime',
      label: '查询时间:',
      colProps: { span: 7 },
      component: 'RangePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
      ifShow: () => {
        return dataCenter.showSchemasType == 'D';
      },
    },
    {
      field: 'monthQueryTime',
      label: '查询时间:',
      colProps: { span: 7 },
      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: 7 },
      component: 'RangePicker',
      componentProps: {
        format: 'YYYY',
        valueFormat: 'YYYY',
        mode: ['year', 'year'],
        onPanelChange: yearPanelChange,
      },
      ifShow: () => {
        return dataCenter.showSchemasType == 'Y';
      },
    },
  ],
  columns: [],
});
const [registerModal] = useModal();
const [registerTable, { reload, getForm, setColumns, setTableData }] = useTable({
  title: '气象历史查询',
  api: getDataHistQueryOneElement,
  columns: dataCenter.columns,
  showIndexColumn: false,
  clickToRowSelect: 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 sta_list = [];
    params.stcdList?.forEach((element) => {
      sta_list.push(setListData(element));
    });
    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');
    }
    dataCenter.searchFormSchema[1].componentProps.options.forEach(element => {
      if(params.dchar == element.value){
        dataCenter.exportNama = element.label
      }
    });
    
    return {
      sta_list: sta_list,
      dchar: params.dchar,
      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',
  immediate:false,
  pagination:false,
  resizeHeightOffset:10,
  fetchSetting: {
    listField: 'data.body',
  },
});
// 月份选择
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;
}
// 弹窗点击查询
async function getHistoryRain() {
  singleStation();
}
function onChange(value, dateString) {
  dataCenter.timeData.time = dateString;
}
// 弹窗处理
function cancel(e) {
  dataCenter.showModal = false;
}
function cancel1() {
  dataCenter.showModal1 = false;
}
function setListData(item) {
  let data = {};
  dataCenter.searchFormSchema[2].componentProps.options.forEach((element) => {
    if (element.value == item) {
      data.stcd = element.value;
      data.st_name = element.st_name;
      data.st_type = element.st_type;
    }
  });
  return data;
}
function setTitle(data) {
  dataCenter.searchFormSchema[1].componentProps.options.forEach(element => {
    if(getForm().getFieldsValue().dchar == element.value){
      dataCenter.customTitle = element.label
    }
  });
  dataCenter.nameArr = [];
  let columns = [];
  let tabdata = [];
  columns.push({
    title: '时间',
    dataIndex: 'time',
    key: 'time',
    width: 100,
    customRender: ({ record, column, index, text }) => {
      // customRender的返回值要遵循vue-jsx语法,要加()和换行
      return <a onClick={handleTitle.bind(record, column, text)}>{text}</a>;
    },
  });
  // 表格数据
  data.forEach((element) => {
    let obj = {};
    obj.time = element.time;
    element.zone_list.forEach((element1) => {
      element1.child.forEach((element2) => {
        obj[element2.st_name] = element2.v;
        obj.senid = element2.senid;
      });
    });
    tabdata.push(obj);
  });
  let columnsData = data[0] ? data[0] : [];
  // 设置表头
  columnsData.zone_list.forEach((item1, index1) => {
    let partition = {};
    partition.title = item1.zone_name;
    partition.dataIndex = item1.zone_name;
    // partition.width = 200;
    partition.key = 'partition' + index1;
    partition.children = [];
    item1.child.forEach((item2, index2) => {
      partition.children.push({
        title: item2.st_name,
        dataIndex: item2.st_name,
        key: item2.st_name,
        senid: item2.senid,
        width: item2.st_name.length*20,
        customRender: ({ record, column, index, text }) => {
          // customRender的返回值要遵循vue-jsx语法,要加()和换行
          return <div onClick={handleTitle.bind(record, column, text)}>{text}</div>;
        },
      });
      dataCenter.nameArr.push(item2.st_name);
    });
    columns.push(partition);
  });
  dataCenter.columnsArr = columns;
  setTimeout(() => {
    dataCenter.exportColumns = columns
    dataCenter.exportdataSource = tabdata
    setColumns(columns);
    setTableData(tabdata);
  }, 100);
}
function handleTitle(record, text, column) {
  console.log(record);
  console.log(text);
  // 点击时间
  if (record.customTitle == '时间' && text != '最小值' && text != '最大值') {
    dataCenter.showModal1 = true;
    multistation(text);
  }
  if (record.customTitle != '时间') {
    dataCenter.timeData.time = [getNowTime(2), getNowTime(1)];
    dataCenter.basicModalTitle = `${record.key}(${dataCenter.customTitle})`;
    dataCenter.showModal = true;
    dataCenter.Modal1Sendid = record.senid;
    singleStation();
  }
}
// 查询单一测站
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();
}
// 查询多站
function multistation(time) {
  dataCenter.modalTime = time;
  let hostData = {
    time: time,
    senid: [],
    step_size:getForm().getFieldsValue().step_size
  };
  dataCenter.nameArr.forEach((element) => {
    dataCenter.columnsArr.forEach((item, index) => {
      item.children?.forEach((item1) => {
        if (element == item1.key) {
          hostData.senid.push(item1.senid);
        }
      });
    });
  });
  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 getDataData() {
  await getDataHistWeaElement().then((res) => {
    res.data.forEach((element) => {
      element.label = element.dchar_name;
      element.value = element.dchar;
      element.unit = element.unit;
    });
    dataCenter.searchFormSchema[1].componentProps.options = res.data;
    getForm().setFieldsValue({
      dchar: res.data[0].dchar
    });
  });
  await getDataHistWeaStations().then((res) => {
    res.data.forEach((element) => {
      element.label = element.st_name;
      element.value = element.stcd;
    });
    dataCenter.searchFormSchema[2].componentProps.options = res.data;
    getForm().setFieldsValue({
      stcdList: [res.data[0].stcd]
    });
  });
  setTimeout(() => {
    reload()
  }, 100);
}
let chart;
function echarts1() {
  chart = echarts.init(document.getElementById('myElement5'));
  var option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    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: '单位：'+dataCenter.unitTitle,
      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);
}
let chart2;
function echarts2(echarts2Data) {
  chart2 = echarts.init(document.getElementById('myElement4'));
  var option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    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: '单位：'+dataCenter.unitTitle,
      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 itemDchar = (item) => {
  dataCenter.searchFormSchema[1].componentProps.options.forEach(element => {

    if(element.value == item){
      dataCenter.unitTitle = element.unit
    }
  });
}
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: `多站点${dataCenter.exportNama}要素历史数据查询.xlsx`,
  });
}
onMounted(async () => {
  // dataCenter.searchFormSchema[1].defaultValue[0] = getNowTime(2);
  // dataCenter.searchFormSchema[1].defaultValue[1] = getNowTime(2);
  getForm().setFieldsValue({
    queryTime: [getNowTime(2), getNowTime(1)]
  });
  await getDataData();
  
  // getForm().setFieldsValue({
  //   monthQueryTime: [getMonth(0), getMonth(1)],
  // });
  // getForm().setFieldsValue({
  //   yearQueryTime: [getYear(0), getYear(1)],
  // });
});
</script>
<style scoped lang="less">
.box-basic {
  height: calc(100% - 46px);
  width: calc(100% - 28px);
  position: absolute;
  // min-height: 600px;
}
.moddal-box {
  display: flex;
  height: calc(100% - 32px);
}
</style>
