<template>
  <div class="com-box">
    <BasicTable :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="dataCenter.formData.value"
                placeholder="支持流域搜索"
              />
            </a-col>
            <a-col :span="12">
              <span class="span-label"> 监测站点: </span>
              <!-- {{ dataCenter.optionArr }} -->
              <a-select
                class="custom-input sitemore"
                mode="multiple"
                placeholder="监测站点(可多选)"
                :maxTagCount="2"
                :maxTagTextLength="4"
                v-model:value="dataCenter.formData.senid"
                label-in-value
                :options="dataCenter.optionArr"
              />
            </a-col>
          </a-row>
        </div>
      </template>
      <template #toolbar>
        <Authority>
          <a-button type="primary" @click="exportDataFn()">导出</a-button>
        </Authority>
      </template>
    </BasicTable>
  </div>
  <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="myElement3">
        <div class="left-box">
          <!-- {{ dataCenter.table_head }} -->
          <ul>
            <template v-for="(item, index) in dataCenter.table_head" :key="item">
              <template v-for="(items, indexs, is) in item" :key="indexs">
                <!-- v-if="
                    indexs == 'voltage' ||
                    indexs == 'rain' ||
                    indexs == 'wd' ||
                    indexs == 'ws' ||
                    indexs == 'hum' ||
                    indexs == 'temp' ||
                    indexs == 'pa'
                  " -->
                <li v-if="items != '测站分区' &&
                  items != '测站' &&
                  items != '时间'
                  " :class="{ 'active-tab': dataCenter.activeSenName == indexs }" @click="setListItem(items, indexs)">
                  {{ items }}
                </li>
              </template>
            </template>
          </ul>
        </div>
        <div class="center-box" id="charts-box2"></div>
        <div class="right-box">
          <div>
            <ul>
              <li>
                <div>时间</div>
                <div>{{ dataCenter.cahrtsList.yName }}</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>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { exportData } from '/@/utils/fnUtils.ts';
  import { defineComponent, ref, watch, onMounted, reactive } from 'vue';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicModal } from '/@/components/Modal/index';
  import { getRealWeather, getMonitorInfo } from '/@/api/swHome/index';
  import { getNowTime } from '/@/utils/fnUtils.ts';
  import elementResizeDetectorMaker from 'element-resize-detector';
  let erd = elementResizeDetectorMaker(); //创建实例
  import * as echarts from 'echarts';
  let dataCenter = reactive({
    listData: [], //列表数据
    columns: [], //表格头部数据
    searchFormSchema: [], //搜索数据
    optionArr: [], // 选择框数据列表
    formData: {
      value: '',
      senid: [],
    },
    allAll: [],
    showModal: false,
    basicModalTitle: '气象监测过程线',
    timeData: {
      time: [],
    },
    table_head: [],
    activeSenid: '',
    activeSenName: '',
    activeItem: {},
    cahrtsData: [],
    cahrtsList: {
      time: [],
      data: [],
      yName: '',
    },
  });
  let chart; //charts
  const exportDataFn = () => {
    let getDataSources = JSON.parse(JSON.stringify(getDataSource()))
    getDataSources.forEach(element => {
      console.log(element)
      for (const key in element) {
        if (Object.prototype.hasOwnProperty.call(element, key)) {
          if(key.indexOf('Data') == -1){
            delete element[key]
          }
        }
      }
    });
    console.log(getDataSources)
    let getColumnss = JSON.parse(JSON.stringify(getColumns()))
    getColumnss.splice(0,1)
    exportData(getColumnss,getDataSources,'气象历史查询-标准气象站.xlsx')
  }
  function onChange(value, dateString) {
    dataCenter.timeData.time = dateString;
  }
  //点击弹窗的左侧列表
  function setListItem(item, index) {
    dataCenter.activeSenName = index;
    dataCenter.cahrtsList.yName = item;
    dataCenter.activeSenid = dataCenter.activeItem[index].senid;
    getMonitorInfoData();
  }
  // 处理表头
  function processingData(table_head) {
    table_head.forEach((element) => {
      for (let key in element) {
        let item = element[key];
        element.title = item;
        element.key = key + 'Data';
        element.dataIndex = key + 'Data';
        element.ellipsis = true;
        // if (element.title == '时间') {
        //   element.width = 200;
        // }
        if (element.title != '时间' && element.title != '序号' && element.title != '测站' && element.title != '测站分区') {
          element.width = element.title.length*15;
        }
      }
    });
    return table_head;
  }
  // 处理列表数据
  function setTable(table_value) {
    table_value.forEach((element) => {
      for (let key in element) {
        let item = element[key];
        if (Object.prototype.toString.call(item) === '[object Object]') {
          element[key + 'Data'] = item.v;
        } else {
          element[key + 'Data'] = item;
        }
      }
    });
    console.log(table_value);
    return table_value;
  }
  // 筛选出所有测站
  function measuringStation(table_value) {
    let measuringStationArr = [];
    table_value.forEach((element) => {
      measuringStationArr.push({
        label: element.st_name,
        key: element.st_name,
        value: element.st_name,
      });
    });
    return measuringStationArr;
  }
  // 获取一般气象站数据
  function getListData() {
    getRealWeather({ st_type: 7 }).then((res) => {
      dataCenter.listData = res.data;
      let { table_head, table_value } = res.data;
      dataCenter.table_head = JSON.parse(JSON.stringify(table_head));
      dataCenter.allAll = table_value;
      dataCenter.columns = processingData(table_head);
      setColumns(dataCenter.columns);
      setTableData(setTable(table_value));
      dataCenter.optionArr = measuringStation(table_value);
    });
  }
  // 弹窗处理
  function cancel(e) {
    dataCenter.showModal = false;
  }
  // 表格数据
  const [registerTable, { reload, getDataSource, getColumns, setColumns, setTableData }] = useTable({
    // 表格头部
    title: '标准气象站',
    inset: true,
    // api: realWsaters,
    columns: dataCenter.columns,
    showIndexColumn: true,
    clickToRowSelect: false,
    beforeFetch: (T) => {
      console.log(T);
    },
    // 搜索表格
    formConfig: {
      labelWidth: 120,
      schemas: dataCenter.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',
    },
  });
  // 提交逻辑
  function submitFunc() {
    screenData();
  }
  // 弹窗点击查询
  async function getHistoryRain() {
    getMonitorInfoData();
  }
  // 筛选数据
  function screenData() {
    let arr = [];
    // 都有数据进行两次筛选
    if (dataCenter.formData.value != '' && dataCenter.formData.senid.length > 0) {
      dataCenter.allAll.forEach((element) => {
        dataCenter.formData.senid.forEach((elements) => {
          if (
            elements.label == element.st_name &&
            element.basin_name.indexOf(dataCenter.formData.value) != -1
          ) {
            arr.push(element);
          }
        });
      });
    } else if (dataCenter.formData.value != '') {
      dataCenter.allAll.forEach((element) => {
        if (element.basin_name.indexOf(dataCenter.formData.value) != -1) {
          console.log(element);
          arr.push(element);
        }
      });
    } else if (dataCenter.formData.senid.length > 0) {
      dataCenter.allAll.forEach((element) => {
        dataCenter.formData.senid.forEach((elements) => {
          if (elements.label == element.st_name) {
            arr.push(element);
          }
        });
      });
    } else {
      arr = dataCenter.allAll;
    }
    setTableData(setTable(arr));
  }
  // 重置逻辑
  function resetFunc() {
    dataCenter.formData.value = '';
    dataCenter.formData.senid = [];
  }
  //点击行
  function rowCLick(item) {
    dataCenter.basicModalTitle = `气象监测过程线(${item.st_name})`;
    // 默认24小时
    dataCenter.timeData.time = [getNowTime(2), getNowTime(1)];
    // 设置默认senid
    dataCenter.activeSenid = item['10'].senid;
    dataCenter.activeSenName = '10';
    dataCenter.table_head.forEach((element) => {
      if (element['10']) {
        dataCenter.cahrtsList.yName = element['10'];
      }
    });
    dataCenter.showModal = true;
    dataCenter.activeItem = item;
    getMonitorInfoData();
    setTimeout(() => {
      erd.listenTo(document.getElementById('myElement3'), () => {
        if (chart) {
          chart.resize();
        }
      });
    }, 300);
  }
  // 查询测站数据
  async function getMonitorInfoData() {
    let historyFormData = {};
    historyFormData.senid = dataCenter.activeSenid;
    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;
    setCharts();
  }
  // 处理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 echarts1() {
    chart = echarts.init(document.getElementById('charts-box2'));
    var option = {
      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  + Number(params[i].value)
          }
          return relVal;
        },
      },
      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.cahrtsList.yName,
        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);
  }
  onMounted(() => {
    getListData();
  });
</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 {
      width: 140px;
      overflow: hidden;
      height: 100%;
      background-color: #f4f4f4;
      ul {
        padding: 10px;
        li {
          line-height: 40px;
          padding-left: 10px;
          cursor: pointer;
        }
      }
    }
    .center-box {
      flex: 1;
      overflow: hidden;
      height: 100%;
      margin-left: 20px;
    }
    .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;
        }
      }
    }
  }
  .top-search {
    padding-bottom: 10px;
  }
  .active-tab {
    background-color: #ccc;
  }
</style>
