<template>
  <div class="main">
    <div class="business-box">
      <div>
        <div class="tree-box">
          <a-input-search v-model:value="searchValue" style="margin-bottom: 8px" placeholder="遥测站搜索" />
          <div class="tree-top-box">
            <a-collapse v-model:activeKey="activeKey3" :bordered="false">
              <template #expandIcon="{ isActive }">
                <caret-right-outlined :rotate="isActive ? 90 : 0" />
              </template>
              <a-collapse-panel @click="rootNode(treeData.allComData)" key="2" header="信道" :style="{ ...customStyle }">
                <ul class="tree-ul">
                  <li :style="activeTree == item.com_name ? activeStyleObj : {}" @click="communication(item)"
                    v-for="(item, index) in treeData.allComData.table_value" :key="index">
                    {{ item.com_name }}({{ item.port }})
                  </li>
                </ul>
              </a-collapse-panel>
            </a-collapse>
          </div>
          <div class="tree-bottom">
            <a-collapse v-model:activeKey="activeKey2" :bordered="false">
              <template #expandIcon="{ isActive }">
                <caret-right-outlined :rotate="isActive ? 90 : 0" />
              </template>
              <!-- treeData.treeNum -->
              <a-collapse-panel key="2" :header="'遥测站'" :style="{ ...customStyle }">
                <a-collapse v-model:activeKey="activeKey" :bordered="false">
                  <template #expandIcon="{ isActive }">
                    <caret-right-outlined :rotate="isActive ? 90 : 0" />
                  </template>
                  <a-collapse-panel v-for="(item, index, i) in treeData.riverTreeData.data_value.station" :key="index"
                    :header="setSiteName(index)" :style="{ ...customStyle }">
                    <a-collapse v-model:activeKey="activeKey1" :bordered="false">
                      <template #expandIcon="{ isActive }">
                        <caret-right-outlined :rotate="isActive ? 90 : 0" />
                      </template>
                      <a-collapse-panel @click="tabCjData(items, index)" v-for="(items, indexs) in item"
                        :key="items.st_name" :header="`${items.st_name}(${items.stcd})`" :style="{ ...customStyle }"
                        :class="{
            'active-style': activeTree == items.stcd,
          }">
                        <ul class="tree-ul">
                          <li :style="activeTree == element.senid ? activeStyleObj : {}"
                            @click.stop="tabCjData(element)" v-for="(element, indexss) in items.sensor" :key="indexss">
                            {{ element.sensor_name }}（{{ element.senid }}）
                          </li>
                        </ul>
                      </a-collapse-panel>
                    </a-collapse>
                  </a-collapse-panel>
                </a-collapse>
              </a-collapse-panel>
            </a-collapse>
          </div>
        </div>
      </div>
      <div>
        <div>
          <div class="message-title">
            {{ messageTitle }}
            <span v-show="activeType == 1" @click="showModalFn" class="more-box">更多》</span>
          </div>
          <a-table class="ant-table-striped" :dataSource="tableData.table_value"
            :rowClassName="(record, index) => (index % 2 === 1 ? 'table-striped' : null)" bordered size="middle"
            :columns="tableData.table_head" :pagination="false" :scroll="{ y: 'calc(50vh - 140px)' }" />
        </div>

        <div class="message-box">
          <div class="message-title"> 报文解析日志 </div>
          <ul>
            <li v-for="(item, index) in treeData.logData" :key="index">
              <div>{{ item.in_time }} {{ item.st_name }}（{{ item.stcd }}）</div>
              <div>
                <div>{{ item.msg_type }}</div>
                <!-- <div>雨量：<span>121.20</span></div> -->
                <div>{{ item.content }}</div>
                <!-- <div>电压：<span>121.20</span></div>
                <div>发信包数：<span>2000</span></div> -->
              </div>
              <div>
                {{ item.msg }}
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <BasicModal :maskClosable="false" :footer="null" @cancel="cancel" :visible="showModal" :width="1200"
      :title="basicModalTitle">
      <div>
        <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="communicationHistory" class="marg-left" type="primary">查询</a-button>
        </div>
        <div class="modal-table">
          <a-table class="ant-table-striped ant-table-striped-modal" :dataSource="tableDataModal.table_value"
            :rowClassName="(record, index) => (index % 2 === 1 ? 'table-striped' : null)" bordered size="middle"
            :pagination="true" :columns="tableDataModal.table_head" :scroll="{ y: '60vh' }" />
        </div>
      </div>
    </BasicModal>
  </div>
</template>
<script lang="ts" setup>
import { defineComponent, ref, watch, onMounted, reactive, onUnmounted } from 'vue';
import {
  getAllCom,
  getRiverTree,
  getAllComData,
  getParseLog,
  getCjData,
} from '/@/api/swHome/index';
import { debounce } from 'lodash';
import { CaretRightOutlined } from '@ant-design/icons-vue';
import { BasicModal } from '/@/components/Modal/index';
const searchValue = ref<string>('');
const activeKey = ref([]);
const activeKey1 = ref([]);
const activeKey2 = ref([]);
const activeKey3 = ref('2');
const customStyle = {
  background: '#fff',
  'border-radius': '4px',
  padding: '0px',
  border: '0',
  overflow: 'hidden',
};
const activeStyleObj = {
  background: 'rgba(6, 113, 221, 0.1)',
};
let messageTitle = ref('信道列表');
let treeData = reactive({
  allComData: [],
  riverTreeData: [],
  treeNum: 0,
  logData: [],
});
let tableData = reactive({
  table_head: [],
  table_value: [],
});
let tableDataModal = reactive({
  table_head: [],
  table_value: [],
});
let activeTree = ref('');
let activeType = ref('1');
let showModal = ref(false);
let basicModalTitle = ref();
let timeData = reactive({
  time: [],
});
function rootNode(table) {
  messageTitle.value = '信道列表';
  let table_head = [];
  table.table_head.forEach((item, index) => {
    for (const key in item) {
      if (Object.prototype.hasOwnProperty.call(item, key)) {
        const element = item[key];
        table_head.push({
          title: element,
          key: key,
          dataIndex: key,
        });
      }
    }
  });
  tableData.table_head = table_head;
  tableData.table_value = table.table_value;
}
function onChange(value, dateString) {
  timeData.time = dateString;
}
// 弹窗
function showModalFn() {
  timeData.time = [];
  showModal.value = true;
  // 查询默认数据
  communicationHistory();
}
let historyFormData = reactive({
  com_name: '',
  start_time: '',
  end_time: '',
});
// 查询历史数据
function communicationHistory() {
  historyFormData.start_time = timeData.time[0] ? timeData.time[0] : '';
  historyFormData.end_time = timeData.time[1] ? timeData.time[1] : '';
  getAllComData(historyFormData).then((res) => {
    let { table_head, table_value } = res.data;
    tableDataModal.table_head = table_head;
    tableDataModal.table_value = table_value;
    // 处理数据
    processingData(tableDataModal.table_head);
  });
}
function cancel(e) {
  showModal.value = false;
}
//数据拍平
function dataFlattening() {
  treeData.treeNum = 0;
  treeData.riverTreeData.data_value.forEach((element) => {
    element.stationArr = [];
    for (let key in element.station) {
      let elements = element.station[key];
      element.stationArr = [...element.stationArr, ...elements];
    }
    element.stationArr.forEach((elements) => {
      treeData.treeNum += elements.sensor.length;
    });
  });
}
function setSiteName(value) {
  let name = '';
  switch (value) {
    case 'st_hydro':
      name = '水文站';
      break;
    case 'st_waterz':
      name = '水位站';
      break;
    case 'st_rain':
      name = '雨量站';
      break;
    case 'st_wea_general':
      name = '一般气象站';
      break;
    case 'st_ts':
      name = '碳水通量站';
      break;
    case 'st_wea_standard':
      name = '标准气象站';
      break;
    default:
      name = value;
      break;
  }
  return name;
}
function processingData(table_head) {
  table_head.forEach((element) => {
    for (let key in element) {
      let item = element[key];
      element.title = item;
      element.key = key;
      element.dataIndex = key;
      if (element.title == '时间') {
        element.width = 200;
      }
    }
  });
}
// 点击信道获取通信子节点
function communication(item) {
  historyFormData.com_name = item.com_name;
  messageTitle.value = `信道列表(${item.com_name})`;
  basicModalTitle.value = `信道报文历史查询(${item.com_name})`;
  activeType.value = '1';
  activeTree.value = item.com_name;
  getAllComData({ com_name: item.com_name }).then((res) => {
    let { table_head, table_value } = res.data;
    tableData.table_head = table_head;
    tableData.table_value = table_value;
    // 处理数据
    processingData(tableData.table_head);
  });
}
// 点击获取测站节点/传感器节点
function tabCjData(item, indexType) {
  activeTree.value = item.senid ? item.senid : item.stcd;
  activeType.value = '2';
  let formData = {
    stcd: '',
    type: '',
  };
  if (item.senid) {
    // 获取sensor传感器
    formData.stcd = item.senid;
    formData.type = 'sensor';
    messageTitle.value = `传感器列表(${item.sensor_name})`;
  } else {
    // 获取测站
    formData.stcd = item.stcd;
    formData.type = 'station';
    messageTitle.value = `测站列表(${item.st_name})`;
  }
  getCjData(formData).then((res) => {
    let { table_head, table_value } = res.data;
    tableData.table_head = table_head;
    tableData.table_value = table_value;
    processingData(tableData.table_head);
  });
}
let treeDataList = null
//获取左侧树桩数据
async function getInitData() {
  // 信道数据
  getAllCom().then((res) => {
    treeData.allComData = res.data;
    treeData.allComData.table_value;
    communication(treeData.allComData.table_value[0]);
  });
  // 遥测站数据
  getRiverTree().then((res) => {
    treeDataList = res.data
    for (const key in treeDataList.data_value.station) {
      if (Object.prototype.hasOwnProperty.call(treeDataList.data_value.station, key)) {
        const element = treeDataList.data_value.station[key];
        element.forEach(elements => {
          elements.isValue = 1
          elements.sensor.forEach(elementss => {
            elementss.isValue = 1
          });
        });
      }
    }
    treeData.riverTreeData = treeDataList;
    dataFlattening();
  });
  // 获取报文解析

}
const getParseLogData = () => {
  getParseLog().then((res) => {
    treeData.logData = res.data;
  });
}
let myInterval = null
onUnmounted(() => {
  clearInterval(myInterval)
})
/**
 * 处理搜索页面
 */
watch(searchValue, debounce((value) => {
  console.log(9900)
  // 将搜索能够搜索到的先打上标签
  let activeKeyArr = []
  let st_nameArr = []
  for (const key in treeDataList.data_value.station) {
    if (Object.prototype.hasOwnProperty.call(treeDataList.data_value.station, key)) {
      const element = treeDataList.data_value.station[key];
      // activeKeyArr.push(key)
      element.forEach(elements => {
        elements.isValue = 0
        if (elements.st_name.indexOf(value) > -1 || (elements.stcd + '').indexOf(value) > -1) {
          elements.isValue = 1
          st_nameArr.push(elements.st_name)
          activeKeyArr.push(key)
        }
        elements.sensor.forEach(elementss => {
          elementss.isValue = 0
          if (elementss.sensor_name.indexOf(value) > -1 || (elementss.senid + '').indexOf(value) > -1) {
            elementss.isValue = 1
          }
        });
        // 判断下级是否有选中，如果有选中将上级默认设置为1
        elements.sensor.forEach(elementss => {
          if (elementss.isValue == 1) {
            elements.isValue = 1
            st_nameArr.push(elements.st_name)
            activeKeyArr.push(key)
          }
        });
      });
    }
  }
  treeData.riverTreeData = treeDataList;
  if (value == '') {
    activeKey2.value = ['2']
    activeKey.value = []
    activeKey1.value = []
    return
  }
  activeKey2.value = ['2']
  activeKey.value = activeKeyArr
  activeKey1.value = st_nameArr
}, 0));
onMounted(() => {
  getInitData();
  getParseLogData()
  myInterval = setInterval(() => {
    getParseLogData()
  }, 15000)
});
</script>

<style lang="scss" scoped>
.business-box {
  display: flex;

  &>div:nth-child(1) {
    min-width: 300px;
    width: 300px;
    background-color: #fff;
    height: calc(100vh - 80px);
    border-radius: 5px;
    padding: 10px;
    overflow: auto;
  }

  &>div:nth-child(2) {
    margin-left: 10px;
    flex: 1;

    &>div:nth-child(1) {
      background-color: #fff;
      height: calc(50vh - 45px);
      padding: 10px;
      border-radius: 5px;
    }

    &>div:nth-child(2) {
      margin-top: 10px;
      background-color: #fff;
      height: calc(50vh - 45px);
      padding: 10px;
      border-radius: 5px;
    }
  }
}

.message-title {
  font-size: 16px;
  position: relative;
}

.message-box {
  ul {
    width: 100%;
    height: calc(100% - 30px);
    overflow: auto;

    li {
      padding: 5px;
      border-radius: 4px;
      background-color: #f8f8f8;
      line-height: 30px;
      margin-bottom: 10px;

      &>div:nth-child(1) {
        color: #0671dd;
        font-size: 14px;
      }

      &>div:nth-child(2) {
        display: flex;
        flex-wrap: wrap;

        &>div {
          margin-right: 40px;
        }

        &>div:last-child {
          // margin-left: auto;
          margin-right: 0;
        }

        span {
          color: #0671dd;
        }
      }
    }
  }
}

::v-deep .ant-collapse-header {
  padding: 0px !important;
  padding-left: 40px !important;
}

::v-deep .ant-collapse-content>.ant-collapse-content-box {
  padding-bottom: 0 !important;
  padding-right: 0px !important;
}

.tree-ul {
  padding-left: 26px;
  margin-bottom: 0px;

  li {
    line-height: 28px;
    cursor: pointer;
  }
}

.active-style {
  background: rgba(6, 113, 221, 0.1) !important;
}

.ant-table-striped :deep(.table-striped) td {
  background-color: #fafafa;
}

.more-box {
  position: absolute;
  right: 0px;
  font-size: 14px;
  color: #0671dd;
  cursor: pointer;
}

.marg-left {
  margin-left: 10px;
}

.ant-table-striped-modal {
  margin-top: 20px;
}
</style>
