<template>
  <div class="com-box">
    <!-- {{dataCenter.columns}} -->
    <BasicTable :clickToRowSelect="false" @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>
    <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>
          <a-button class="right-position" type="primary" @click="exportExcel({
          time:'时间',
          factv:dataCenter.cahrtsList.yName
        },dataCenter.cahrtsData,dataCenter.basicModalTitle+'.xlsx')">导出</a-button>
        </div>
        <div class="moddal-box" id="myElement">
          <div class="left-box">
            <a-collapse v-model:activeKey="dataCenter.collapseKey">
              <a-collapse-panel
                v-for="(item, index, i) in dataCenter.activeModal.leftList"
                :key="i"
                :header="index"
              >
                <ul>
                  <li
                    :class="{
                      'active-list': dataCenter.activeModal.senid == items.senid,
                    }"
                    v-for="(items, indexs) in item.value"
                    :key="indexs"
                    @click="setListItem(items, indexs)"
                    >{{ items.sensor_name }}</li
                  >
                </ul>
              </a-collapse-panel>
            </a-collapse>
          </div>
          <div class="center-box" id="charts-box3"></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>
  </div>
</template>
<script lang="tsx" 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, stDetailInfo, getMonitorInfo } from '/@/api/swHome/index';
import { getNowTime } from '/@/utils/fnUtils.ts';
import elementResizeDetectorMaker from 'element-resize-detector';
import { ImpExcel, ExcelData, jsonToSheetXlsx } from '/@/components/Excel';

import * as echarts from 'echarts';
let erd = elementResizeDetectorMaker(); //创建实例
let dataCenter = reactive({
  dchar:'',
  listData: [], //列表数据
  columns: [], //表格头部数据
  searchFormSchema: [], //搜索数据
  optionArr: [], // 选择框数据列表
  formData: {
    value: '',
    senid: [],
  },
  allAll: [],
  showModal: false,
  basicModalTitle: '气象监测过程线',
  timeData: {
    time: [],
  },
  cahrtsList: {
    yName: '',
    time: [],
    data: [],
  },
  activeModal: {
    name: '',
    detailInfo: {},
    senid: '',
    sensor_name: '',
    dchar: '',
    activeData: {},
    leftList: {},
  },
  collapseKey: 0,
  cahrtsData: [],
});
let chart; //charts
function exportExcel(headers,data,names) {
    jsonToSheetXlsx({
      data,
      header: headers,
      filename: names,
    });
  }
// 导出
const exportDataFn = () => {
    let getDataSources = JSON.parse(JSON.stringify(getDataSource()))
    getDataSources.forEach(element => {
      for (const key in element) {
        if (Object.prototype.hasOwnProperty.call(element, key)) {
          if(key.indexOf('Data') != -1 && (key!='groupDataData' || key!='monitorData')){
            element[key] = element[key] + '|' + element[key.split('Data')[0]].time
          }
        }
      }
      delete element.group_idData
    });
    getDataSources.forEach(element => {
      for (const key in element) {
        if (Object.prototype.hasOwnProperty.call(element, key)) {
          if(key.indexOf('Data') == -1){
            delete element[key]
          }
        }
      }
      delete element.group_idData
    });
    let getColumnss = JSON.parse(JSON.stringify(getColumns()))
    getColumnss.splice(0,1)
    exportData(getColumnss,getDataSources,'气象历史查询-碳水通量站.xlsx')
  }
function onChange(value, dateString) {
  dataCenter.timeData.time = dateString;
}
// 弹窗处理
function cancel(e) {
  dataCenter.showModal = false;
}
// 弹窗点击查询
async function getHistoryRain() {
  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.resizable = true;
      element.width = key.indexOf('st_name') != -1 ? 260 : 160;
      element.customRender = (record) => {
        // customRender的返回值要遵循vue-jsx语法,要加()和换行
        let text = record.column.dataIndex.split('Data');
        if (key.indexOf('st_name') != -1) {
          return (
            <div
              class="list-box-carbon-water"
              onClick={handleTitle.bind(record.record, record.column,record)}
            >
              <span>{record.record[record.column.dataIndex]}</span>
              <span>{record.record[record.column.dataIndex]?'|':''}</span>
              <span>{record.record[text[0]].time}</span>
            </div>
          );
        } else {
          return (
            <div onClick={handleTitle.bind(record.record, record.column,record)}>
              <span>{record.text}</span>
            </div>
          );
        }
      };
      element.ellipsis = true;
      if (element.title == '时间') {
        element.width = 200;
      }
    }
  });
  return table_head;
}
function handleTitle(record, column, item) {
  if (record.dataIndex.indexOf('st_name') != -1) {
    dataCenter.basicModalTitle = `气象监测过程线(${record.customTitle})`;
    // 设置时间
    dataCenter.timeData.time = [getNowTime(2), getNowTime(1)];
    dataCenter.activeModal.name = record.customTitle;
    dataCenter.activeModal.detailInfo.forEach((element) => {
      if (element.st_name == dataCenter.activeModal.name) {
        dataCenter.activeModal.activeData = element;
      }
    });
    //排序
    // 所有的都没有数据9065000110
    dataCenter.activeModal.senid = dataCenter.activeModal.activeData.sensor[0].senid;
    dataCenter.activeModal.sensor_name = dataCenter.activeModal.activeData.sensor[0].sensor_name;
    dataCenter.activeModal.dchar = dataCenter.activeModal.activeData.sensor[0].dchar;
    dataCenter.cahrtsList.yName = dataCenter.activeModal.activeData.sensor[0].sensor_name+'('+dataCenter.activeModal.activeData.sensor[0].dchar+')';
    if (dataCenter.activeModal.activeData.st_type == 6) {
      let obj = {};
      dataCenter.activeModal.activeData.sensor?.forEach((i) => {
        if (obj.hasOwnProperty(i.ts_layer)) {
          obj[i.ts_layer].value.push(i);
        } else {
          obj[i.ts_layer] = {};
          obj[i.ts_layer].id = null;
          obj[i.ts_layer].value = [];
          obj[i.ts_layer].value.push(i);

          if (i.ts_layer.includes('m')) {
            obj[i.ts_layer].id = Number(i.ts_layer.split('m')[0])
          } else {
            obj[i.ts_layer].id = 0
          }
        }
      });
      let sortedObjKeys = Object.keys(obj).sort((a, b) => {
        return obj[b].id - obj[a].id
      })
      let arr = {}
      sortedObjKeys.forEach(j => {
        arr[j] = obj[j]
      })
      console.log(arr)
      
      setListItem(arr[Object.keys(arr)[0]].value[0])
      dataCenter.activeModal.leftList = arr;
    }
    getMonitorInfoData();
    dataCenter.showModal = true;
    setTimeout(() => {
      erd.listenTo(document.getElementById('myElement'), () => {
        if (chart) {
          chart.resize();
        }
      });
    }, 300);
  }
}
// 处理列表数据
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]') {
        if (item.v) {
          element[key + 'Data'] = `${item.v}`;
        } else {
          element[key + 'Data'] = '';
        }
      } else {
        element[key + 'Data'] = item;
      }
    }
  });
  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;
}
// 查询测站数据
async function getMonitorInfoData() {
  let historyFormData = {};
  historyFormData.senid = dataCenter.activeModal.senid;
  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);
}
// 处理char数据
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 setListItem(item, index) {
  dataCenter.cahrtsList.yName = item.sensor_name+'('+item.dchar+')'
  dataCenter.activeModal.senid = item.senid;
  getMonitorInfoData();
}
// 获取一般气象站数据
function getListData() {
  getRealWeather({ st_type: 6 }).then((res) => {
    dataCenter.listData = res.data;
    let { table_head, table_value } = res.data;
    dataCenter.allAll = table_value;
    dataCenter.columns = processingData(table_head);
    setColumns(dataCenter.columns);
    setTableData(setTable(table_value));
    dataCenter.optionArr = measuringStation(table_value);
  });
}
// 处理
// 表格数据
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: false,
  // 是否需要表格设置框
  showTableSetting: true,
  tableSetting: {
    redo: false,
    setting: false,
  },
  // rowSelection: { type: 'checkbox' },
  // 是否需要边框
  bordered: true,
  rowKey: 'id',
  ellipsis: false,
  pagination:false,
  resizeHeightOffset:20,
  fetchSetting: {
    listField: 'data.table_value',
  },
});
function submitFunc() {
  screenData();
}
// 筛选数据
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) {
        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 echarts1() {
  chart = echarts.init(document.getElementById('charts-box3'));
  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();
  stDetailInfo().then((res) => {
    dataCenter.activeModal.detailInfo = res.data.st_ts;
  });
});
</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: 200px;
    overflow: auto;
    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;
}
::v-deep .moddal-box .ant-collapse > .ant-collapse-item > .ant-collapse-header {
  padding: 5px 0 5px 0;
  padding-left: 30px;
  border: 0px;
  background-color: #f4f4f4;
}
::v-deep .moddal-box .ant-collapse > .ant-collapse-item {
  border: 0px;
}
::v-deep .moddal-box .ant-collapse {
  border: 0px;
}
::v-deep .moddal-box .ant-collapse-content {
  border: 0px;
  background-color: #f4f4f4;
}
::v-deep .moddal-box .ant-collapse-content > .ant-collapse-content-box {
  padding: 5px;
  padding-left: 16px;
}
.active-list {
  background-color: #ccc;
}
.top-search{
    position: relative;
    .right-position{
      position: absolute;
      right: 0px;
      top: 0px;
    }
  }
</style>
<style lang="less">
.list-box-carbon-water {
  display: flex;
  justify-content: space-between;
  span:nth-child(1){
    font-weight: bold;
  }
}
</style>
