<template>
  <div class="main">
    <div class="top-form">
      <a-row>
        <a-col class="form-box" :span="8">
          <div> 监测站点：</div>
          <div>
            <a-select
              class="custom-input sitemore"
              placeholder="监测站点"
              :maxTagCount="2"
              :maxTagTextLength="4"
              mode="multiple"
              @change="changeStid"
              v-model:value="dataCenter.formData.station"
              :options="dataCenter.st_options"
            />
          </div>
        </a-col>
        <a-col class="form-box" :span="8">
          <div> 要素： </div>
          <div>
            <a-select
              class="custom-input sitemore"
              placeholder="监测站点"
              :maxTagCount="2"
              :maxTagTextLength="4"
              v-model:value="dataCenter.formData.dchar"
              :options="dataCenter.ys_options"
              @change="selectChange"
            />
          </div>
        </a-col>
        <a-col class="form-box" :span="8">
          <div> 查询时间： </div>
          <div>
            <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"
            />
          </div>
        </a-col>
        <a-col class="form-box" :span="8">
          <div> 时段类型： </div>
          <div>
            <a-radio-group @change="changeDchar" v-model:value="dataCenter.formData.step_size">
              <a-radio
                v-for="(item, index) in dataCenter.sd_options"
                :key="index"
                :value="item.value"
                >{{ item.label }}</a-radio
              >
            </a-radio-group>
          </div>
        </a-col>
        <a-col class="form-box" :span="8">
          <div> 统计特征： </div>
          <div>
            <a-radio-group
              :disabled="dataCenter.attrDisable"
              v-model:value="dataCenter.formData.attr"
            >
              <a-radio
                v-for="(item, index) in dataCenter.tz_options"
                :key="index"
                :value="item.value"
                >{{ item.label }}</a-radio
              >
            </a-radio-group>
          </div>
        </a-col>
        <a-col class="btn-list" :span="8">
          <a-button @click="resetting">重置</a-button>
          <a-button class="cha" type="primary" @click="queryData">查询</a-button>
        </a-col>
      </a-row>
    </div>
    <div class="content-box">
      {{dataCenter.echartsTitle}}多站点对比分析图
      <div class="sub-title"
        >分析结果
        <AreaChartOutlined @click="setTable(1)" :class="{ 'active-icon': dataCenter.type == 1 }" />
        <TableOutlined @click="setTable(2)" :class="{ 'active-icon': dataCenter.type == 2 }" />
      </div>
    </div>
    <div class="box-content">
      <div id="chartsbox-mul" v-show="dataCenter.type == 1"> </div>
      <div v-show="dataCenter.type == 2">
        <a-table
          :scroll="{ y: `calc(100vh - 300px)` }"
          :dataSource="dataCenter.tableDataModal.table_value"
          :columns="dataCenter.tableDataModal.table_head"
          :pagination="false"
          bordered
          size="middle"
        />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { defineComponent, ref, watch, onMounted, reactive } from 'vue';
  import { BasicTable, useTable } from '/@/components/Table';
  import * as echarts from 'echarts';
  import { getRiverTree, getDataAllElements, getManyStAnalyze } from '/@/api/swHome/index';
  import { getNowTime } from '/@/utils/fnUtils.ts';
  import { AreaChartOutlined, TableOutlined } from '@ant-design/icons-vue';
  let dataCenter = reactive({
    unit:'',
    dchar_type:'',
    echartsTitle:'',
    echartsTitleCopy:'',
    attrDisable: false,
    type: 1,
    st_options: [],
    ys_options: [],
    tableDataModal: {
      table_head: [],
      table_value: [],
    },
    sd_options: [
      { label: '实时', value: 'R' },
      { label: '小时', value: 'H' },
      { label: '日', value: 'D' },
      { label: '月', value: 'M' },
      { label: '年', value: 'Y' },
      
    ],
    tz_options: [
      { label: '平均值', value: 'avgv' },
      { label: '最大值', value: 'maxv' },
      { label: '最小值', value: 'minv' },
    ],
    timeData: {
      time: [getNowTime(2), getNowTime(1)],
    },
    chartsData: {},
    formData: {
      step_size: 'H',
      dchar: '',
      attr: 'avgv',
      start_time: '',
      end_time: '',
      station: [],
    },
  });
  function selectChange(val,e){
    dataCenter.unit = e.unit
    dataCenter.echartsTitleCopy = e.label
  }
  function setTable(e) {
    dataCenter.type = e;
  }
  function onChange(value, dateString) {
    dataCenter.timeData.time = dateString;
  }
  function queryData() {
    getHistoryWaterData();
  }
  function changeDchar({ target }) {
    if (target.value == 'R') {
      dataCenter.attrDisable = true;
      dataCenter.formData.attr = '';
    } else {
      dataCenter.attrDisable = false;
      dataCenter.formData.attr = 'avgv';
    }
  }
  // 查询展示数据
  function getHistoryWaterData() {
    dataCenter.formData.start_time = dataCenter.timeData.time[0];
    dataCenter.formData.end_time = dataCenter.timeData.time[1];
    getManyStAnalyze(dataCenter.formData).then((res) => {
      dataCenter.dchar_type = res.data.dchar_type
      processingData(res.data);
    });
  }
  function processingData(data) {
    // 处理表格数据
    data.table_head.forEach((element) => {
      for (let key in element) {
        let item = element[key];
        element.title = item;
        element.key = key;
        element.dataIndex = key;
      }
    });
    dataCenter.tableDataModal.table_head = data.table_head;
    dataCenter.tableDataModal.table_value = data.table_value;

    let innerData = {};
    innerData.chartsName = [];
    data.table_head.forEach((element) => {
      let key = Object.keys(element)[0];
      let arrData = [];
      data.table_value.forEach((elements) => {
        if (elements.time != '最大值' && elements.time != '最小值') {
          arrData.push(elements[key]);
        }
      });

      if (key != 'time') {
        innerData[Object.values(element)[0]] = arrData;
        innerData.chartsName.push(Object.values(element)[0]);
      } else {
        innerData[key] = arrData;
      }
    });
    dataCenter.chartsData = innerData;
    if (data.table_head.length != 0) {
      if (chart) {
        chart.dispose();
        setTimeout(() => {
          sheCharst();
        }, 100);
      }else{
        sheCharst();
      }
      
      dataCenter.echartsTitle = dataCenter.echartsTitleCopy
    } else {
      if (chart) {
        chart.dispose();
      }
    }
  }
  const changeStid = (e) => {
    getDataAllElementsFn(e)
  }
  // 查询所有站点
  async function getDataData() {
    await getRiverTree().then((res) => {
      let arr = [];
      console.log(res.data.data_value.station);
      for (const key in res.data.data_value.station) {
        if (Object.prototype.hasOwnProperty.call(res.data.data_value.station, key)) {
          const element = res.data.data_value.station[key];
          element.forEach((element) => {
            arr.push({
              label: element.st_name,
              value: element.stcd,
            });
          });
        }
      }
      dataCenter.st_options = arr;
      dataCenter.formData.station = [dataCenter.st_options[0].value,dataCenter.st_options[1].value];
      getDataAllElementsFn([dataCenter.st_options[0].value,dataCenter.st_options[1].value])
    });
    
  }
  async function getDataAllElementsFn(ids) {
    await getDataAllElements({station:ids}).then((res) => {
      res.data.forEach((element) => {
        element.label = element.dchar_name;
        element.value = element.dchar;
      });
      dataCenter.ys_options = res.data;
      dataCenter.unit = dataCenter.ys_options[0].unit;
      dataCenter.formData.dchar = dataCenter.ys_options[0].value;
      dataCenter.echartsTitle = dataCenter.ys_options[0].label;
      dataCenter.echartsTitleCopy = dataCenter.ys_options[0].label;
    });
    getHistoryWaterData();
  }
  let chart = null;
  function sheCharst() {
    console.log(dataCenter.chartsData);
    chart = echarts.init(document.getElementById('chartsbox-mul'));
    let option = {
      title: {
        text: `${dataCenter.echartsTitle}(${dataCenter.unit})`,
        left:25,
        top:20,
        textStyle: {
          fontSize: 14,
          color: '#333',
        },
      },
      tooltip: {
        trigger: 'axis',
      },
      legend: {
        data: dataCenter.chartsData.chartsName,
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      toolbox: {
        feature: {
          saveAsImage: {
            name:`${dataCenter.echartsTitle}多站点对比分析图`
          }
          
        },
      },
      xAxis: {
        type: 'category',
        boundaryGap: true,
        data: dataCenter.chartsData.time,
      },
      yAxis: {
        type: 'value',
        scale:true
      },
      series: [
        // {
        //   name: 'Email',
        //   type: 'line',
        //   stack: 'Total',
        //   data: [120, 132, 101, 134, 90, 230, 210],
        // },
      ],
    };
    dataCenter.chartsData.chartsName.forEach((element) => {
      let item = dataCenter.chartsData[element];
      option.series.push({
        name: element,
        type: dataCenter.dchar_type,
        data: item,
      });
    });
    option && chart.setOption(option);
  }
  function resetting() {
    getDataData();
  }
  onMounted(async () => {
    await getDataData();
  });
</script>
<style scoped lang="less">
  .main {
    margin: 10px;
    height: calc(100% - 20px);
    background-color: #fff;
  }
  .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;
    height: calc(100% - 150px);
    & > div {
      width: 100%;
    }
  }
  .right-box {
    width: 400px;
    height: 100%;
    overflow: auto;
    margin-left: 20px;
    position: relative;
    ul {
      // position: relative;
      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%;
      }
      li:nth-child(2) {
        padding-top: 45px;
      }
    }
  }
  .form-box {
    margin-bottom: 10px;
  }
  .content-box {
    text-align: center;
    font-size: 18px;
    border-top: 1px solid #dedede;
    position: relative;
    padding-top: 10px;
    .sub-title {
      padding-left: 10px;
      border-left: 4px solid #2d74e7;
      text-align: left;
      font-size: 10px;
      position: absolute;
      left: 0px;
      top: 15px;
      color: #999;
      span {
        margin-left: 10px;
        font-size: 18px;
        position: relative;
        top: 2px;
        cursor: pointer;
      }
      .active-icon {
        color: #377dff !important;
      }
    }
  }
</style>
