<template>
  <div>
    <BasicTable :clickToRowSelect="false" @register="registerTable">
      <template #tableTitle>
        {{dataCenter.exportName}}站气象要素历史查询
      </template>
      <template #toolbar>
        <Authority>
          <a-button type="primary"
            @click="exportData(dataCenter.exportColumns, dataCenter.exportdataSource, dataCenter.exportName+'站多要素历史数据查询.xlsx')">导出</a-button>
        </Authority>
      </template>
    </BasicTable>
    <!-- 弹窗2 -->
    <BasicModal :maskClosable="false" :footer="null" @cancel="cancel1" :visible="dataCenter.showModal1" :width="1200"
      :minHeight="600" :title="`${dataCenter.exportName}站${dataCenter.customTitle}监测过程线`">
      <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>
          <a-button class="right-position" type="primary" @click="exportExcel({
          time:'时间',
          factv:dataCenter.exportName+'站'+dataCenter.customTitle
        },dataCenter.cahrtsData, `${dataCenter.exportName}站${dataCenter.customTitle}监测过程线${currentDay()}.xlsx`)">导出</a-button>
        </div>
        <div class="box-inner-modal">
          <div class="moddal-box" id="myElement6"> </div>
          <div class="charts-list">
            <div id="echarts-box1"></div>
            <div>
              <div class="right-box">
                <ul>
                  <li>
                    <div>时间</div>
                    <div>{{ dataCenter.customTitle }}</div>
                  </li>
                  <li v-for="(item, index) in dataCenter.cahrtsData" :key="index">
                    <div>{{ item.time }}</div>
                    <div>{{ item.factv }}</div>
                  </li>

                </ul>
              </div>
            </div>
          </div>
        </div>
      </div>
    </BasicModal>
  </div>
</template>

<script lang="tsx" setup>
import { defineComponent, ref, onMounted, reactive } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { BasicModal } from '/@/components/Modal/index';
import { ImpExcel, ExcelData, jsonToSheetXlsx } from '/@/components/Excel';
import { currentDay } from '/@/utils/fnUtils.ts';
import {
  getDataHistWeaElement,
  getDataHistWeaStations,
  getDataHistQueryOneStation,
  getHistoryTimeInquire,
  getMonitorInfo,
} from '/@/api/swHome/index';
import { getNowTime, getMonth, getYear, exportData } from '/@/utils/fnUtils.ts';
import { useModal } from '/@/components/Modal';
import moment from 'moment';
function exportExcel(headers,data,names) {
    jsonToSheetXlsx({
      data,
      header: headers,
      filename: names,
    });
  }
import eventBus from '/@/utils/eventBus';
let dataCenter = reactive({
  customTitle: '',
  showSchemasType: 'H',
  modalTime: '',
  Modal1Sendid: '',
  timeData: {
    time: [],
  },
  cahrtsList: {},
  cahrtsData: {},
  sindMaxArr: {},
  basicModalTitle: '',
  showModal: false,
  showModal1: false,
  nameArr: [],
  senidArr: [],
  exportName:'',
  searchFormSchema: [
    {
      field: 'queryMode',
      label: '查询模式:',
      component: 'RadioGroup',
      colProps: { span: 7 },
      defaultValue: '2',
      componentProps: {
        options: [
          { label: '单要素', value: '1' },
          { label: '单站点', value: '2' },
        ],
        onChange: (e) => {
          eventBus.emit('setShowType', e.target.value);
        },
      },
    },
    {
      field: 'stcd',
      label: '监测站点:',
      component: 'Select',
      colProps: { span: 7 },
      placeholder: '单选',
      componentProps: {
        options: [],
      },
    },
    {
      field: 'dchar',
      label: '要素:',
      component: 'Select',
      colProps: { span: 7 },
      placeholder: '多选',
      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: 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: [],
});
function cancel1() {
  dataCenter.showModal1 = false;
}
const [registerModal] = useModal();
const [registerTable, { reload, getForm, setColumns, setTableData }] = useTable({
  title: dataCenter.exportName+'站气象要素历史查询',
  api: getDataHistQueryOneStation,
  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) => {
    console.log('params',params)
    let st_name = setListData(params.stcd);
    dataCenter.exportName = st_name
    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 {
      st_name: st_name,
      stcd: params.stcd,
      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',
  },
});
// 弹窗点击查询
async function getHistoryRain() {
  singleStation();
}
// 月份选择
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.showSchemasType = e.target.value;
}
function setTitle(data) {
  console.log(data);
  let dataArr = data;
  let columns = [];
  let tabdata = [];
  dataArr.thead.forEach((element) => {
    for (const key in element) {
      if (Object.prototype.hasOwnProperty.call(element, key)) {
        const elements = element[key];
        let senid = dataArr['最大值'][key] ? dataArr['最大值'][key].senid : '';
        let obj = {
          title: elements,
          dataIndex: key,
          key: key,
          width: 100,
          senid: senid,
          customRender: ({ record, column, index, text }) => {
            // customRender的返回值要遵循vue-jsx语法,要加()和换行
            // if (key != 'time') {
            //   return <a onClick={handleTitle.bind(record, column, text)}>{text}</a>;
            // } else {
            //   return <div onClick={handleTitle.bind(record, column, text)}>{text}</div>;
            // }
            if (key != 'time') {
              return <div onClick={handleTitle.bind(record, column, text)}>{text}</div>;
            } else {
              return <div onClick={handleTitle.bind(record, column, text)}>{text}</div>;
            }
          },
        };
        columns.push(obj);
      }
    }
  });
  // 写入数据
  dataArr.tbody.forEach((item, index) => {
    let obj = {};
    for (const key in item) {
      if (Object.prototype.hasOwnProperty.call(item, key)) {
        const element = item[key];
        if (key != 'time') {
          obj[key] = element.v;
        } else {
          obj.time = element;
        }
      }
    }
    tabdata.push(obj);
  });
  // 写入最大值和最小值
  let obj = {};
  for (const key in dataArr['最大值']) {
    if (Object.prototype.hasOwnProperty.call(dataArr['最大值'], key)) {
      const element = dataArr['最大值'][key];
      obj[key] = element.v;
      dataCenter.senidArr.push(element.senid);
    }
  }
  dataCenter.sindMaxArr = dataArr['最大值'];
  obj.time = '最大值';
  tabdata.push(obj);

  let obj1 = {};
  for (const key in dataArr['最小值']) {
    if (Object.prototype.hasOwnProperty.call(dataArr['最小值'], key)) {
      const element = dataArr['最小值'][key];
      obj1[key] = element.v;
    }
  }
  obj1.time = '最小值';
  tabdata.push(obj1);
  setTimeout(() => {
    dataCenter.exportColumns = columns
    dataCenter.exportdataSource = tabdata
    setTableData(tabdata);
    setColumns(columns);
  }, 100);
}
function handleTitle(record, text, column) {
  dataCenter.customTitle = record.customTitle
  // 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.showModal1 = true;
    dataCenter.Modal1Sendid = setSindId(record.key);
    singleStation();
  }
}
function setSindId(sindid) {
  return dataCenter.sindMaxArr[sindid].senid;
}
function setListData(item) {
  let data = {};
  dataCenter.searchFormSchema[1].componentProps.options.forEach((element) => {
    if (element.value == item) {
      data.st_name = element.st_name;
    }
  });
  return data.st_name;
}
// 查询单一测站
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: dataCenter.senidArr,
  };
  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);
  });
}
// 获取查询基础数据
const getDataData = async () => {
  let res = await getDataHistWeaElement()
  res.data.forEach((element) => {
    element.label = element.dchar_name;
    element.value = element.dchar;
  });
  dataCenter.searchFormSchema[2].componentProps.options = res.data;
  getForm().setFieldsValue({
    dchar: [res.data[0].dchar]
  });

  let res1 = await getDataHistWeaStations()
  res1.data.forEach((element) => {
    element.label = element.st_name;
    element.value = element.stcd;
  });
  dataCenter.searchFormSchema[1].componentProps.options = res1.data;
  getForm().setFieldsValue({
    stcd: res1.data[0].stcd
  });
  setTimeout(() => {
    reload()
  }, 0);
}
let chart;
function echarts1() {
  chart = echarts.init(document.getElementById('myElement6'));
  var option = {
    toolbox: {
      feature: {
        saveAsImage: {
          name:`${dataCenter.exportName}站${dataCenter.customTitle}监测过程线`
        }
      }
    },
    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.customTitle,
      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: 'line',
        smooth: true,
      },
    ],
  };
  option && chart.setOption(option);
}
let chart2;
function echarts2(echarts2Data) {
  chart2 = echarts.init(document.getElementById('myElement6'));
  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: '单位：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);
}
onMounted(async () => {
  getForm().setFieldsValue({
    queryTime: [getNowTime(2), getNowTime(1)]
  });
  // dataCenter.searchFormSchema[1].defaultValue[0] = getNowTime(2);
  // dataCenter.searchFormSchema[1].defaultValue[1] = getNowTime(2);
  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;
  width: 800px;
  height: 600px;
}

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

.box-inner-modal {
  display: flex;

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

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

.charts-list {
  height: 100%;
  display: flex;
  height: calc(100vh - 190px);

  &>div:nth-child(1) {
    flex: 1;
    height: calc(100vh - 190px);
    margin-right: 10px;
  }

  &>div:nth-child(2) {
    width: 400px;
    height: calc(100vh - 190px);
  }
}

.charts-list-top {
  display: flex;
  justify-content: flex-end;

  .left-mg {
    margin: 0 20px 0 0px !important;
  }

  .mg-text {
    line-height: 32px;
    cursor: pointer;
    color: #0671dd;
  }
}

.right-box {
  height: 575px;
  overflow: hidden;

  ul {
    // position: relative;
    height: calc(100vh - 230px);
    overflow: auto;

    li {
      display: flex;
      line-height: 45px;
      width: 393px !important;

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

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

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

.top-search{
    position: relative;
    .right-position{
      position: absolute;
      right: 0px;
      top: 0px;
    }
  }
</style>
