<template>
  <div>
    <BasicTable class="basic-table-cl" :clickToRowSelect="false" @row-click="rowCLick" @register="registerTable">
      <template #form-formHeader="{ model, field }">
        <div class="form-box">
          <a-row>
            <a-col :span="12">
              <span class="span-label"> 关键字: </span>
              <a-input class="custom-input" v-model:value="formState.value" placeholder="支持流域搜索" />
            </a-col>
            <a-col :span="12">
              <span class="span-label"> 监测站点: </span>
              <a-select class="custom-input sitemore" mode="multiple" placeholder="监测站点(可多选)" :maxTagCount="2"
                :maxTagTextLength="4" v-model:value="formState.senid" label-in-value :options="optionArr" />
            </a-col>
          </a-row>
        </div>
      </template>
      <template #toolbar>
        <Authority>
          <a-button type="primary" @click="exportDataFn('水情查询.xlsx')">导出</a-button>
        </Authority>
      </template>
    </BasicTable>
    <BasicModal :clickToRowSelect="false" :footer="null" @cancel="cancel" :visible="showModal" :width="1200"
      :minHeight="600" :title="basicModalTitle">
      <div class="box-basic">
        <div class="top-search">
          时间范围：
          <a-range-picker :value="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 class="left-box">
            <div id="charts-box" style="width: 100%; height: 100%"> </div>
          </div>
          <div class="right-box">
            <div>
              <ul>
                <li>
                  <div>时间</div>
                  <div>水位(m)</div>
                  <div>流量(m³/s)</div>
                </li>
                <li v-for="(item, index) in modalData.optimizeData" :key="index">
                  <div>{{ item.time }}</div>
                  <div>{{ item.z }}</div>
                  <div>{{ item.q }}</div>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </BasicModal>
  </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 { BasicModal } from '/@/components/Modal/index';
import { exportData } from '/@/utils/fnUtils.ts';
import * as echarts from 'echarts';
import { ImpExcel, ExcelData, jsonToSheetXlsx } from '/@/components/Excel';
import {
  realWsaters,
  // waterRegimen,
  // getMonitorInfo,
  // getRiverTree,
  // historyRain,
  postRealWaterZq
} from '/@/api/swHome/index';
import { getNowTime } from '/@/utils/fnUtils.ts';
let columns = [];
let searchFormSchema = [];
let chart;
const [registerTable, { reload, setColumns, setTableData }] = useTable({
  // 表格头部
  title: '水情查询',
  inset: true,
  // api: realWsaters,
  columns,
  showIndexColumn: true,
  clickToRowSelect: false,
  beforeFetch: (T) => {
    console.log(T);
  },
  // 搜索表格
  formConfig: {
    labelWidth: 120,
    schemas: searchFormSchema,
    // 自定义提交逻辑
    submitFunc: submitFunc,
    // 自定义重置逻辑
    resetFunc: resetFunc,
  },
  // 是否需要搜索框
  useSearchForm: true,
  // 是否需要表格设置框
  showTableSetting: true,
  tableSetting: {
    redo: false,
    setting: false,
  },
  // rowSelection: { type: 'checkbox' },
  // 是否需要边框
  bordered: true,
  rowKey: 'id',
  ellipsis: false,
  fetchSetting: {
    listField: 'data.table_value',
  },
  pagination: false
});
// 表单数据
let formState = reactive({
  value: '',
  senid: [],
});
// 所有的数据
let allAll = [];
// 弹窗控制
let basicModalTitle = ref('');
let showModal = ref(false);
let timeData = reactive({
  time: [],
});
// 导出
const exportDataFn = (name) => {
  let exportColumns = JSON.parse(JSON.stringify(dataCenter.exportColumns))
  let exportdataSource = JSON.parse(JSON.stringify(dataCenter.exportdataSource))
  exportdataSource.forEach(element => {
    delete element.q
    delete element.z
  });
  exportData(exportColumns, exportdataSource, name)
}
function onChange(value, dateString) {
  timeData.time = dateString;
}
function cancel(e) {
  showModal.value = false;
}
// rowCLick
let activeItem = {};
function rowCLick(item) {
  timeData.time = [getNowTime(2), getNowTime(1)];
  activeItem = item;
  basicModalTitle.value = `水位流量过程线(${item.st_name})`;
  showModal.value = true;
  getHistoryRain();
  setTimeout(() => {
    erd.listenTo(document.getElementById('myElement'), () => {
      if (chart) {
        chart.resize();
      }
    });
  }, 300);
}
// 查询雨情历史数据
let historyFormData = reactive({
  stcd: '',
  start_time: '',
  end_time: '',
});
let modalData = reactive({
  data: {},
  optimizeData: {},
});
//q：流量，z：水位
async function getHistoryRain() {
  echartsData.time = []
  echartsData.q = []
  echartsData.z = []
  historyFormData.stcd = activeItem.stcd;
  historyFormData.start_time = timeData.time[0] ? timeData.time[0] : '';
  historyFormData.end_time = timeData.time[1] ? timeData.time[1] : '';
  //查询水位，流量过程线
  let qwData = await postRealWaterZq(historyFormData).then(res => {
    console.log(res)
    modalData.optimizeData = res.data
    res.data.forEach(element => {
      echartsData.time.push(element.time)
      echartsData.q.push(element.q)
      echartsData.z.push(element.z)
    });
  })
  // 查询流量过程线
  // let qData = await getMonitorInfo(historyFormData).then((res) => {
  //   return res.data;
  // });
  // // 查询水位过程线
  // historyFormData.senid = activeItem.z.senid;
  // let zData = await getMonitorInfo(historyFormData).then((res) => {
  //   return res.data;
  // });
  // modalDataFn(qData, zData);
  echarts1();
}
let echartsData = reactive({
  time: [],
  q: [],
  z: [],
});
// 弹窗数据处理
function modalDataFn(qData, zData) {
  modalData.optimizeData = [];
  echartsData.time = [];
  echartsData.q = [];
  echartsData.z = [];
  for (let index = 0; index < qData.length; index++) {
    let itemData = {};
    const elementq = qData[index];
    const elementz = zData[index];
    itemData.time = elementq.time;
    itemData.q = elementq.factv;
    itemData.z = elementz.factv;
    echartsData.time.push(elementq.time);
    echartsData.q.push(elementq.factv);
    echartsData.z.push(elementz.factv);
    modalData.optimizeData.push(itemData);
  }
}
// 计算最大值
function getMaxValue(arr) {
  const max = Math.max(...arr);
  // 这样处理是为了不让最大值刚好到坐标轴最顶部
  return Math.ceil(max / 9.5) * 10;
}
// 计算最小值
function getMinValue(arr) {
  const min = Math.min(...arr);
  // 这样处理是为了不让最大值刚好到坐标轴最底部
  return Math.floor(min / 12) * 10;
}
// 图表
function echarts1() {
  // const min1 = getMinValue(echartsData.q);
  // const min2 = getMinValue(echartsData.z);
  // const max1 = getMaxValue(echartsData.q);
  // const max2 = getMaxValue(echartsData.z);
  chart = echarts.init(document.getElementById('charts-box'));
  console.log(basicModalTitle)
  var option = {
    toolbox: {
      feature: {
        saveAsImage: {
          name: basicModalTitle.value
        }
      }
    },
    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 + params[i].seriesName + ' : ' + Number(params[i].value)
        }
        return relVal;
      },
      // formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    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: echartsData.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,
        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,
        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: echartsData.q,
        type: 'line',
        smooth: true,
      },
      {
        name: '水位',
        yAxisIndex: 1,
        // data: [82, 92, 901, 934, 1290, 130, 11320],
        data: echartsData.z,
        type: 'line',
        smooth: true,
      },
    ],
  };
  option && chart.setOption(option);
}
// 所有雨量站数据
let optionArr = ref([]);
// 重置逻辑
function resetFunc() {
  formState.value = '';
  formState.senid = [];
}
// 提交事件
function submitFunc() {
  screenData();
}
// 筛选数据
function screenData() {
  console.log(formState);
  console.log(allAll);
  let arr = [];
  // 都有数据进行两次筛选
  if (formState.value != '' && formState.senid.length > 0) {
    allAll.forEach((element) => {
      formState.senid.forEach((elements) => {
        if (
          elements.label == element.st_name &&
          element.basin_name.indexOf(formState.value) != -1
        ) {
          arr.push(element);
        }
      });
    });
  } else if (formState.value != '') {
    allAll.forEach((element) => {
      if (element.basin_name.indexOf(formState.value) != -1) {
        console.log(element);
        arr.push(element);
      }
    });
  } else if (formState.senid.length > 0) {
    allAll.forEach((element) => {
      formState.senid.forEach((elements) => {
        if (elements.label == element.st_name) {
          arr.push(element);
        }
      });
    });
  } else {
    arr = allAll;
  }
  setTableData(setTableUpDown(arr));
}
//处理数据上升或者下降
function setTableUpDown(arr) {
  arr.forEach((element) => {
    // if (element.up_down == 0) {
    //   element.up_down = '落↓';
    // }
    // if (element.up_down == 1) {
    //   element.up_down = '涨↑';
    // }
    // if (element.up_down == 2) {
    //   element.up_down = '平-';
    // }
    element.qData = element.q.v;
    element.zData = element.z.v;
  });
  return arr;
}
// 处理表头
function processingData(table_head) {
  table_head.forEach((element) => {
    for (let key in element) {
      if (key == 'q' || key == 'z') {
        let item = element[key];
        element.title = item;
        element.key = key + 'Data';
        element.dataIndex = key + 'Data';
      } else {
        let item = element[key];
        element.title = item;
        element.key = key;
        element.dataIndex = key;
      }
      element.ellipsis = true;
      if (element.title == '时间') {
        // element.width = 200;
      }
      if (element.title == '站码') {
        // element.width = 160;
      }
    }
  });
  return table_head;
}
let dataCenter = reactive({
  exportdataSource: [],
  exportColumns: []
})
// 获取请求头
async function getRealRainData() {
  await realWsaters().then((res) => {
    let { table_head, table_value } = res.data;
    dataCenter.exportdataSource = allAll = table_value;

    dataCenter.exportColumns = columns = processingData(table_head);
    setColumns(columns);
    setTableData(setTableUpDown(table_value));
    optionArr.value = measuringStation(table_value);
  });
}
// 筛选出所有测站
function measuringStation(table_value) {
  let measuringStationArr = [];
  table_value.forEach((element) => {
    measuringStationArr.push({ label: element.st_name, key: element.stcd, value: element.stcd });
  });
  return measuringStationArr;
}
onMounted(async () => {
  await getRealRainData();
});
</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 {
    flex: 1;
    overflow: hidden;
    height: 100%;
  }

  .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;
      }
    }
  }
}

.vben-basic-table-form-container {
  padding: 0px;
}

</style>
