<template>
  <div class="sensor-container">
    <a-tabs class="tabs-box" type="card" v-model:activeKey="activeKey" @change="tabChange">
      <a-tab-pane key="1" tab="实时监测">
        <div class="box-bg table-box" style="margin-bottom: 10px">
          <label style="color: #fff">设备类型：</label>
          <Select
            @change="handleSensorChange"
            :options="deviceTypeOption"
            :fieldNames="{ label: 'itemText', value: 'itemValue' }"
            v-model:value="deviceKind"
            style="width: 200px; margin-bottom: 5px"
            placeholder="请选择设备类型"
            :allowClear="true"
          />
          <MonitorTable
            ref="SensorMonitorRef"
            columnsType="modelsensor_monitor"
            :dataSource="dataSource"
            design-scope="modelsensor_monitor"
            @select-row="getSelectRow"
            :deviceType="deviceKind"
            size="''"
            title="传感器监测"
          >
            <template #filterCell="{ column, record }">
              <a-tag v-if="column.dataIndex === 'warnFlag'" :color="record.warnFlag == 0 ? 'green' : 'red'">{{
                record.warnFlag == 0 ? '正常' : '报警'
              }}</a-tag>
              <a-tag v-if="column.dataIndex === 'netStatus'" :color="record.netStatus == 0 ? 'default' : 'green'">{{
                record.netStatus == 0 ? '断开' : '连接'
              }}</a-tag>
            </template>
          </MonitorTable>
        </div>

        <div class="charts-box box-bg">
          <BarAndLine
            v-if="chartsColumns.length > 0"
            :chartsColumnsType="selectData.deviceType"
            xAxisPropType="readTime"
            :dataSource="detailDataSource"
            height="100%"
            :chartsColumns="chartsColumns"
            chartsType="detail"
            @refresh="refreshEchatrs"
          />
        </div>
      </a-tab-pane>
      <a-tab-pane key="2" tab="历史数据">
        <div class="tab-item table-box box-bg padding-0">
          <HistoryTable
            columns-type="modelsensor_history"
            device-type="modelsensor"
            :device-list-api="baseList"
            @change="historyDataSourceChange"
            designScope="modelsensor-history"
          />
        </div>
        <div class="charts-box box-bg">
          <BarAndLine
            v-if="chartsColumns.length > 0"
            :chartsColumnsType="selectData.deviceType"
            xAxisPropType="gcreatetime"
            :dataSource="historyDataSource"
            height="100%"
            :chartsColumns="chartsColumns"
            chartsType="history"
            @refresh="refreshEchatrs"
          />
        </div>
      </a-tab-pane>
      <a-tab-pane key="3" tab="报警历史">
        <div class="tab-item box-bg">
          <AlarmHistoryTable columns-type="alarm_history" device-type="modelsensor" :device-list-api="baseList" designScope="alarm-history" />
        </div>
      </a-tab-pane>
      <a-tab-pane key="4" tab="操作历史">
        <div class="tab-item box-bg">
          <HandlerHistoryTable columns-type="operatorhistory" device-type="modelsensor" :device-list-api="baseList" designScope="alarm-history" />
        </div>
      </a-tab-pane>
    </a-tabs>
    <div class="title-text">
      {{ selectData.strname }}
    </div>
  </div>
</template>

<script setup lang="ts">
  import BarAndLine from '/@/components/chart/BarAndLine.vue';
  import { Select } from 'ant-design-vue';
  import { onBeforeMount, ref, onMounted, onUnmounted, toRaw, reactive, nextTick } from 'vue';
  import MonitorTable from '../comment/MonitorTable.vue';
  import HistoryTable from '../comment/HistoryTable.vue';
  import AlarmHistoryTable from '../comment/AlarmHistoryTable.vue';
  import HandlerHistoryTable from '../comment/HandlerHistoryTable.vue';
  import { list, getTableList } from './sensor.api';
  import { list as baseList } from '../../deviceManager/sensorTabel/sensor.api';
  import { deviceList } from '../../deviceManager/comment/pointTabel/point.api';

  const SensorMonitorRef = ref();
  const deviceBaseList = ref([]);
  const activeKey = ref('1');
  const deviceKind = ref(null);
  const deviceTypeOption = ref([]);
  // 默认初始是第一行
  const selectRowIndex = ref(0);
  const dataSource = ref([]);
  const detailDataSource = ref<any[]>([]);
  const historyDataSource = ref<any[]>([]);
  const chartsColumns = ref<any[]>([]);
  const selectData = reactive({
    strname: '',
    deviceType: '',
  });

  const tabChange = (activeKeyVal) => {
    activeKey.value = activeKeyVal;
    detailDataSource.value = [];
  };

  // https获取监测数据
  let timer: null | NodeJS.Timeout = null;
  const getMonitor = () => {
    if (Object.prototype.toString.call(timer) === '[object Null]') {
      timer = setTimeout(async () => {
        await getDataSource(deviceKind.value);
        if (timer) {
          timer = null;
        }
        getMonitor();
      }, 1000);
    }
  };

  const getDataSource = async (devicetype) => {
    const type = devicetype ? devicetype : 'modelsensor';
    const res = await list({ devicetype: type, pagetype: 'normal' });
    dataSource.value = res.msgTxt[0].datalist || [];
    dataSource.value.map((data: any) => {
      const readData = data.readData;
      data = Object.assign(data, readData);
      return data;
    });
    const data: any = toRaw(dataSource.value[selectRowIndex.value]); //maxarea
    Object.assign(selectData, data);

    if (chartsColumns.value.length <= 0 && selectData.deviceType) {
      handleChange(selectData.deviceType);
    }

    // 如果当前为监测tab
    if (activeKey.value === '1') {
      const isHas = detailDataSource.value.find((item) => item['readTime'] === selectData['readTime']);
      // 获取选中数据
      if (!isHas) {
        if (detailDataSource.value.length < 15) {
          detailDataSource.value.push({ ...selectData });
        } else {
          detailDataSource.value.shift();
          detailDataSource.value.push({ ...selectData });
        }
      }
    }
    return data;
  };

  const getSelectRow = (selectRow, index) => {
    if (!selectRow) return;
    selectRowIndex.value = index;
    const baseData: any = deviceBaseList.value.find((baseData: any) => baseData.id === selectRow.deviceID);
    Object.assign(selectData, selectRow, baseData);
    if (selectData.deviceType) {
      if (timer) {
        clearTimeout(timer);
        timer = undefined;
      }
      if (activeKey.value === '1') detailDataSource.value = [];
      if (activeKey.value === '2') historyDataSource.value = [];
      handleChange(selectData.deviceType);
    }
  };

  // 获取设备基本信息列表
  const getDeviceBaseList = () => {
    getTableList({ pageSize: 1000 }).then((res) => {
      deviceBaseList.value = res.records;
    });
  };

  function handleChange(type) {
    if (type === 'modelsensor_multi') {
      chartsColumns.value = [
        {
          legend: '气压值',
          seriesName: '(Pa)',
          ymax: 50,
          yname: 'Pa',
          linetype: 'bar',
          yaxispos: 'left',
          color: '#37BCF2',
          sort: 1,
          xRotate: 0,
          dataIndex: 'pa',
        },
        {
          legend: '温度',
          seriesName: '(℃)',
          ymax: 50,
          yname: '℃',
          linetype: 'bar',
          yaxispos: 'right',
          color: '#FC4327',
          sort: 2,
          xRotate: 0,
          dataIndex: 'temperature',
        },
      ];
    } else if (type === 'modelsensor_smoke') {
      chartsColumns.value = [
        {
          legend: '烟雾浓度',
          seriesName: '(%)',
          ymax: 20,
          yname: '%',
          linetype: 'bar',
          yaxispos: 'left',
          color: '#37BCF2',
          sort: 1,
          xRotate: 0,
          dataIndex: 'windSpeed',
        },
      ];
    } else if (type === 'modelsensor_speed') {
      chartsColumns.value = [
        {
          legend: '风速',
          seriesName: '(m/s)',
          ymax: 20,
          yname: 'm/s',
          linetype: 'bar',
          yaxispos: 'left',
          color: '#37BCF2',
          sort: 1,
          xRotate: 0,
          dataIndex: 'windSpeed',
        },
      ];
    } else if (type === 'modelsensor_gas') {
      chartsColumns.value = [
        {
          legend: '甲烷',
          seriesName: '(%)',
          ymax: 20,
          yname: '%',
          linetype: 'bar',
          yaxispos: 'left',
          color: '#37BCF2',
          sort: 1,
          xRotate: 0,
          dataIndex: 'windSpeed',
        },
      ];
    }

    console.log('[ type ] >', type, chartsColumns.value);
  }

  function handleSensorChange(type) {
    setTimeout(() => {
      handleChange(type);
      if (timer) {
        clearTimeout(timer);
        timer = null;
      }
      dataSource.value = [];
      detailDataSource.value = [];
      getMonitor();
    }, 50);
  }

  function refreshEchatrs() {
    timer = null;
    getMonitor();
    console.log('echarts 刷新');
  }
  function historyDataSourceChange(dataSource) {
    historyDataSource.value = dataSource;
    if (historyDataSource.value.length > 0) handleChange(historyDataSource.value[0].gdevicetype);
  }

  onBeforeMount(() => {
    getDeviceBaseList();
  });

  onMounted(async () => {
    getMonitor();
    const res = await deviceList({ devicetype: 'modelsensor' });
    const obj = res.find((item) => item.itemValue === 'modelsensor');
    deviceTypeOption.value = obj ? obj.children : [];
  });
  onUnmounted(() => {
    if (timer) {
      clearTimeout(timer);
      timer = undefined;
    }
  });
</script>
<style lang="less" scoped>
  @import '/@/design/vent/color.less';
  @import '/@/design/vent/modal.less';
  .padding-0 {
    padding: 10px 0 !important;
  }
  .sensor-container {
    position: relative;
    top: 20px;
    padding: 10px;
    z-index: 999;
    max-height: calc(100vh - 150px);
    .@{ventSpace}-tabs {
      max-height: calc(100vh - 100px);
      .tab-item {
        max-height: calc(100vh - 170px);
        overflow-y: auto;
      }
    }
    .title-text {
      position: absolute;
      top: -14px;
      left: 0;
      width: 100%;
      text-align: center;
      color: #fff;
    }
    .table-box {
      height: calc(60vh - 150px);
      padding: 20px 10px;
      overflow-y: auto;
    }

    .box-bg {
      border: 1px solid #4d7ad855;
      border-radius: 2px;
      // background-color: #001d3055;
      -webkit-backdrop-filter: blur(8px);
      backdrop-filter: blur(8px);
      box-shadow: 0 0 10px #5984e055 inset;
      background-color: #00b3ff12;
    }
    .charts-box {
      height: calc(40vh - 80px);
      padding: 5px 10px;
      margin-top: 10px;
    }
  }
  :deep(.@{ventSpace}-tabs-tabpane-active) {
    overflow: auto;
  }
  :deep(.@{ventSpace}-tabs-card) {
    .@{ventSpace}-tabs-tab {
      background: linear-gradient(#2cd1ff55, #1eb0ff55);
      border-color: #74e9fe;
      border-radius: 0%;
      &:hover {
        color: #64d5ff;
      }
    }
    .@{ventSpace}-tabs-tab.@{ventSpace}-tabs-tab-active .@{ventSpace}-tabs-tab-btn {
      color: aqua;
    }
    .@{ventSpace}-tabs-nav::before {
      border-color: #74e9fe;
    }
    .@{ventSpace}-picker,
    .@{ventSpace}-select-selector {
      width: 100% !important;
      background: #00000017 !important;
      border: 1px solid @vent-form-item-boder !important;
      input,
      .@{ventSpace}-select-selection-item,
      .@{ventSpace}-picker-suffix {
        color: #fff !important;
      }
      .@{ventSpace}-select-selection-placeholder {
        color: #b7b7b7 !important;
      }
    }
    .@{ventSpace}-pagination-next,
    .action,
    .@{ventSpace}-select-arrow,
    .@{ventSpace}-picker-separator {
      color: #fff !important;
    }
    .@{ventSpace}-table-cell-row-hover {
      background: #264d8833 !important;
    }
    .@{ventSpace}-table-row-selected {
      background: #00c0a311  !important;
      td {
        background-color: #00000000 !important;
      }
    }
    .@{ventSpace}-table-thead {
      // background: linear-gradient(#004a8655 0%, #004a86aa 10%) !important;
      background: #3d9dd45d!important;

      & > tr > th,
      .@{ventSpace}-table-column-title {
        // color: #70f9fc !important;
        border-color: #84f2ff  !important;
        border-left: none !important;
        border-right: none !important;
        padding: 7px;
      }
    }

    .@{ventSpace}-table-tbody {
      tr > td {
        padding: 12px;
      }
    }
    .@{ventSpace}-table-tbody > tr:hover.@{ventSpace}-table-row > td {
      background-color: #26648855 !important;
    }

    .jeecg-basic-table-row__striped {
      // background: #97efff11 !important;
      td {
        background-color: #97efff11 !important;
      }
    }
  }
</style>
