<template>
  <div class="main">
    <div class="top-form">
      <a-row>
        <a-col class="form-box" :span="4">
          <div> 监测站点： </div>
          <div>
            <a-select
              class="custom-input sitemore"
              placeholder="监测站点"
              :maxTagCount="2"
              :maxTagTextLength="4"
              v-model:value="dataCenter.formData.senid"
              :options="dataCenter.options"
              @change="changeSt"
            />
          </div>
        </a-col>
        <a-col class="form-box" :span="6">
          <div style="margin-left: 10px;"> 时段类型： </div>
          <div>
            <a-radio-group @change="changeGroup" v-model:value="dataCenter.formData.step_size">
              <a-radio value="R">实时</a-radio>
              <a-radio value="H">小时</a-radio>
              <a-radio value="D">日</a-radio>
              <a-radio value="M">月</a-radio>
              <a-radio value="Y">年</a-radio>
            </a-radio-group>
          </div>
        </a-col>
        <a-col class="form-box" :span="10">
          <div> 查询时间： </div>
          <div>
            <a-range-picker
              v-if="dataCenter.formData.step_size == 'H'||dataCenter.formData.step_size == 'R'"
              :value="dataCenter.timeData.time"
              :show-time="{ format: 'HH:mm:ss' }"
              format="YYYY-MM-DD HH:mm:ss"
              :placeholder="['开始时间', '结束时间']"
              @change="onChange"
              :allowClear="true"
            />
            <a-range-picker
              v-if="dataCenter.formData.step_size == 'D'"
              :value="dataCenter.timeData.time"
              format="YYYY-MM-DD"
              :placeholder="['开始时间', '结束时间']"
              @change="onChange"
              :allowClear="true"
            />
            <a-range-picker
              v-if="dataCenter.formData.step_size == 'M'"
              :value="dataCenter.timeMonth"
              format="YYYY-MM"
              valueFormat="YYYY-MM"
              :placeholder="['开始时间', '结束时间']"
              @change="onChange"
              :mode="['month', 'month']"
              @panelChange="monthPanelChange"
              :allowClear="true"
            />
            <a-range-picker
              v-if="dataCenter.formData.step_size == 'Y'"
              :value="dataCenter.timeYear"
              format="YYYY"
              valueFormat="YYYY"
              :placeholder="['开始时间', '结束时间']"
              @panelChange="yearPanelChange"
              :mode="['year', 'year']"
              :allowClear="true"
            />
          </div>
        </a-col>
        <a-col class="btn-list" :span="4">
          <a-button @click="resetting">重置</a-button>
          <a-button class="cha" type="primary" @click="queryData">查询</a-button>
        </a-col>
      </a-row>
    </div>
    <div class="title-name"> {{ dataCenter.titleName }}水情历史数据查询 </div>
    <div class="box-content">
      <div id="charts-box"></div>
      <div class="right-box">
        <div>
          <a-button type="primary" @click="exportExcel">导出excel</a-button>
        </div>
        <div>
          <ul>
            <li>
              <div>时间</div>
              <div>水位(m)</div>
              <div>流量(m³/s)</div>
            </li>
            <li v-for="(item, index) in dataCenter.listData" :key="index">
              <div>{{ item.time }}</div>
              <div>{{ item.z }}</div>
              <div>{{ item.q }}</div>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { defineComponent, ref, watch, onMounted, reactive } from 'vue';
  import { BasicTable, useTable } from '/@/components/Table';
  import elementResizeDetectorMaker from 'element-resize-detector';
  let erd = elementResizeDetectorMaker(); //创建实例
  import * as echarts from 'echarts';
  import { getDataHistRainStatios, getHistoryWater, getWaterStations } from '/@/api/swHome/index';
  import { getNowTime } from '/@/utils/fnUtils.ts';
  import { ImpExcel, ExcelData, jsonToSheetXlsx } from '/@/components/Excel';
  import moment from 'moment';
  let dataCenter = reactive({
    timeYear: [],
    timeMonth: [],
    options: [],
    formData: {
      senid: '',
      step_size: 'H',
    },
    timeData: {
      time: [],
    },
    titleName: '',
    chartsData: {},
    listData: [],
  });
  function exportExcel() {
    let name = null;
    let header = {
      time:'时间',
      z:'水位(m)',
      q:'流量(m³/s)'
    };
    let data = dataCenter.listData;
    jsonToSheetXlsx({
      data,
      header: header,
      filename: `${dataCenter.titleName}水情历史数据查询.xlsx`,
    });
  }
  function changeGroup() {
    dataCenter.timeData.time = [];
  }
  function changeSt(value, item) {
    console.log(item);
    dataCenter.titleName = item.st_name;
  }
  // 年份选择
  function yearPanelChange(value) {
    dataCenter.timeData.time = [moment(value[0]).format('YYYY'), moment(value[1]).format('YYYY')];
    dataCenter.timeYear = [moment(value[0]).format('YYYY'), moment(value[1]).format('YYYY')];
  }
  // 月份选择
  function monthPanelChange(value) {
    dataCenter.timeData.time = [
      moment(value[0]).format('YYYY-MM'),
      moment(value[1]).format('YYYY-MM'),
    ];
    dataCenter.timeMonth = [moment(value[0]).format('YYYY-MM'), moment(value[1]).format('YYYY-MM')];
  }
  // 获取查询树状数据
  function getRiveTreeData() {
    getWaterStations().then((res) => {
      res.data.forEach((element) => {
        element.label = element.st_name;
        element.value = element.stcd;
      });
      dataCenter.options = res.data;
      dataCenter.formData.senid = dataCenter.options[0].stcd;
      dataCenter.titleName = dataCenter.options[0].st_name;
      dataCenter.timeData.time = [getNowTime(2), getNowTime(1)];
      getHistoryWaterData();
    });
  }
  function onChange(value, dateString) {
    dataCenter.timeData.time = dateString;
  }
  function queryData() {
    getHistoryWaterData();
  }
  function resetting() {
    dataCenter.formData.senid = dataCenter.options[0].senid;
    dataCenter.formData.step_size = 'H';
    dataCenter.timeData.time = [getNowTime(2), getNowTime(1)];
    getHistoryWaterData();
  }
  let chart;
  //图表方法
  function setCherts() {
    chart = echarts.init(document.getElementById('charts-box'));
    var option = {
      toolbox: {
        feature: {
          saveAsImage: {
            name:`${dataCenter.titleName}水情历史数据查询`
          }
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
        formatter(params) {
          var relVal = params[0].name;
          for (var i = 0, l = params.length; i < l; i++) {
              //遍历出来的值一般是字符串，需要转换成数字，再进项tiFixed四舍五入
              relVal += `<br/>${params[i].marker}${params[i].seriesName}:${params[i].value == '--'? '--' : Number(params[i].value)}`
              // relVal += '<br/>' + params[i].marker + params[i].seriesName + ' : ' + Number(params[i].value)
          }
          return relVal;
        },
      },
      dataZoom: [
        {
          // 这个dataZoom组件，默认控制x轴。
          type: 'inside', // 这个 dataZoom 组件是 slider 型 dataZoom 组件
        },
        {
          // 这个dataZoom组件，也控制x轴。
          type: 'inside', // 这个 dataZoom 组件是 inside 型 dataZoom 组件
        },
      ],
      grid: {
        left: '4%', //默认10%
        right: '4%', //默认10%
        bottom: '4%', //默认60
        containLabel: true,
        //grid区域是否包含坐标轴的刻度标签
      },
      legend: {
        top: 20,
        data: ['流量', '水位'],
        textStyle: {
          fontSize: 14, //字体大小
          color: '#333', //字体颜色
        },
        // itemStyle: {
        //   color: '#fff',
        // },
      },
      xAxis: {
        type: 'category',
        data: dataCenter.chartsData.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: [
        {
          name: '流量：m³/s',
          type: 'value',
          // min: min1,
          // max: max1,
          // interval: (max1 - min1) / 2,
          // splitNumber: 2,
          boundaryGap:[0.1,0.1],
          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, //隐藏或显示
          },
          nameTextStyle: {
            color: 'rgba(0, 0, 0, 0.8)', //颜色
          },
          scale: true,
        },
        {
          type: 'value',
          name: '水位：m',
          // min: min2,
          // interval: (max2 - min2) / 2,
          // max: max2,
          // splitNumber: 2,
          boundaryGap:[0.1,0.1],
          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, //隐藏或显示
          },
          nameTextStyle: {
            color: 'rgba(0, 0, 0, 0.8)', //颜色
            padding: [0, 0, 0, 30],
          },
          scale: true,
        },
      ],
      series: [
        {
          name: '流量',
          // data: [820, 932, 901, 934, 1290, 1330, 1320],
          data: dataCenter.chartsData.q,
          type: 'line',
          smooth: true,
        },
        {
          name: '水位',
          yAxisIndex: 1,
          // data: [82, 92, 901, 934, 1290, 130, 11320],
          data: dataCenter.chartsData.z,
          type: 'line',
          smooth: true,
        },
      ],
    };
    option && chart.setOption(option);
  }
  // 查询测站数据
  function getHistoryWaterData() {
    dataCenter.formData.start_time = dataCenter.timeData.time[0];
    dataCenter.formData.end_time = dataCenter.timeData.time[1];
    getHistoryWater(dataCenter.formData).then((res) => {
      dataCenter.chartsData.q = [];
      dataCenter.chartsData.z = [];
      dataCenter.chartsData.time = [];
      res.data.forEach((element) => {
        if (element.time != '最大值' && element.time != '最小值') {
          dataCenter.chartsData.q.push(element.q);
          dataCenter.chartsData.z.push(element.z);
          dataCenter.chartsData.time.push(element.time);
        }
      });
      dataCenter.listData = res.data;
      setCherts();
    });
  }
  onMounted(async () => {
    getRiveTreeData();
  });
</script>
<style scoped lang="less">
  .main {
    padding: 10px;
  }
  .top-form {
    background-color: #fff;
    padding: 12px 10px 12px 10px;
  }
  .btn-list {
    text-align: right;
  }
  .cha {
    margin-left: 10px;
  }
  .form-box {
    display: flex;
    & > div:nth-child(1) {
      width: 90px;
      text-align: right;
      line-height: 32px;
    }
    & > div:nth-child(2) {
      flex: 1;
    }
  }
  ::v-deep .top-form .ant-select {
    width: 100%;
  }
  ::v-deep .top-form .ant-radio-group {
    line-height: 32px;
  }
  .title-name {
    text-align: center;
    font-size: 18px;
    line-height: 40px;
  }
  .box-content {
    display: flex;
    & > div:nth-child(1) {
      flex: 1;
      height: calc(100vh - 180px);
      background-color: #fff;
    }
    & > div:nth-child(2) {
      width: 400px;
      margin-left: 10px;
      height: calc(100vh - 180px);
      background-color: #fff;
    }
  }
  .right-box {
    width: 400px;
    height: 100%;
    margin-left: 20px;
    position: relative;
    &>div:nth-child(1){
      text-align: right;
      padding-top: 5px;
      padding-right: 5px;
    }
    &>div:nth-child(2){
      height: calc(100% - 40px);
      overflow: auto;
    }
    ul {
      // position: relative;
      height: calc(100% - 40px);
      overflow: auto;
      li {
        display: flex;
        line-height: 45px;
        & > 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%;
        top: 36px;
        background-color: #fff;
      }
      li:last-child{
        position: absolute;
        width: 100%;
        bottom: 0px;
        background-color: #fff;
      }
      li:nth-last-child(2){
        position: absolute;
        width: 100%;
        bottom: 45px;
        background-color: #fff;
      }
      li:nth-last-child(3){
        padding-bottom: 90px;
      }
      li:nth-child(2) {
        padding-top: 45px;
      }
    }
  }
</style>
