<template>
  <div class="safetyList">
    <customHeader>数据中心-设备监测</customHeader>
    <div class="content">
      <a-tabs class="tab-box" v-model:activeKey="activeKey" @change="onChangeTab">
        <a-tab-pane tab="设备监测" key="device" />
        <a-tab-pane tab="历史数据" key="history" />
      </a-tabs>
      <div class="box-content">
        <!-- 分站监测 -->
        <div class="now-content">
          <div class="left-box">
            <div class="device-select">
              <div class="device-select-box">
                <a-tree
                  v-if="treeData && treeData.length > 0"
                  :show-line="true"
                  :tree-data="treeData"
                  v-model:selectedKeys="selectedKeys"
                  v-model:expandedKeys="expandedKeys"
                  :defaultExpandAll="true"
                  @select="onSelect"
                >
                </a-tree>
              </div>
            </div>
          </div>
          <div class="right-box" v-if="activeKey == 'device'">
            <div class="right-title">实时监测：</div>
            <a-table
              size="small"
              :scroll="{ y: 650 }"
              :columns="outerColumns"
              :data-source="deviceList"
              :pagination="false"
              :row-key="(record) => record.id"
              :expand-row-by-click="true"
              :expanded-row-keys="expandedRowKeys"
              @expand="onExpand"
            >
              <!-- 自定义展开图标 -->
              <template #expandIcon="{ expanded, onExpand, record }">
                <a-button
                  type="text"
                  size="small"
                  @click="
                    (e) => {
                      e.stopPropagation();
                      toggleExpand(record.id);
                    }
                  "
                >
                  <DownCircleTwoTone v-if="expandedRowKeys.includes(record.id)" />
                  <RightCircleTwoTone v-else />
                </a-button>
              </template>

              <!-- 嵌套表格 -->
              <template #expandedRowRender="{ record }">
                <a-table
                  size="small"
                  :columns="innerColumns"
                  :data-source="monitorList"
                  :pagination="false"
                  :loading="loadingMap[record.id]"
                  bordered
                  :scroll="{ y: 410 }"
                >
                  <template #bodyCell="{ column, record: innerRecord }">
                    <template v-if="column.dataIndex === 'value'">
                      <span>
                        {{ innerRecord.value }}
                      </span>
                    </template>
                  </template>
                </a-table>
              </template>
            </a-table>
          </div>
          <div class="right-box" v-else-if="activeKey == 'history'">
            <div class="right-title">历史数据：</div>
            <a-table></a-table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, reactive, onMounted, onUnmounted, watch, shallowRef, computed } from 'vue';
import { usePermission } from '/@/hooks/web/usePermission';
import customHeader from '/@/components/vent/customHeader.vue';
import { AesEncryption } from '/@/utils/cipher';
import { loginCipher } from '/@/settings/encryptionSetting';
import { message, TreeProps } from 'ant-design-vue';
import { getDeviceTypeList, getDeviceListByType, getDevMonitorListById } from './device.api';
import { RightCircleTwoTone, DownCircleTwoTone } from '@ant-design/icons-vue';
import { alignElement } from 'dom-align';
import { active } from 'sortablejs';
import { stubTrue } from 'lodash';

const { hasPermission } = usePermission();
let activeKey = ref('device');
const treeData = ref<TreeProps['treeData']>([]);
const selectedKeys = ref<string[]>([]);
const expandedKeys = ref<string[]>([]);
const AllNodeKeys = ref<string[]>([]);
const deviceType = ref(''); // 监测设备类型
const systemType = ref('');
const systemID = ref(''); // 系统监测时，系统id
const dataSource = shallowRef([]); // 实时监测数据
let startMonitorTimer = 0;
const monitorTable = ref();
const isRefresh = ref(true);
const treeNodeTitle = ref(''); // 选中的树形标题
const deviceList = ref<any[]>([]); // 设备列表
const monitorList = ref<any[]>([]); // 监测数据列表
// 当前展开的行key数组
const expandedRowKeys = ref([]);

// 加载状态映射
const loadingMap = reactive({});
// 分页参数
const paginationState = ref({
  current: 1,
  pageSize: 10,
  total: 0,
});
const paginationState2 = ref({
  current: 1,
  pageSize: 10,
  total: 0,
});
// 计算分页后的数据
const paginatedData = computed(() => {
  const start = (paginationState.value.current - 1) * paginationState.value.pageSize;
  const end = start + paginationState.value.pageSize;
  return monitorList.value.slice(start, end);
});
// 计算分页后的数据
const paginatedData2 = computed(() => {
  const start = (paginationState2.value.current - 1) * paginationState2.value.pageSize;
  const end = start + paginationState2.value.pageSize;
  return deviceList.value.slice(start, end);
});
// 分页器配置 - 修复响应式问题
// const paginationConfig = computed(() => {
//   return {
//     current: paginationState.value.current,
//     pageSize: paginationState.value.pageSize,
//     total: monitorList.value.length,
//     showSizeChanger: true,
//     showQuickJumper: true,
//     showTotal: (total) => `共 ${total} 条`,
//     pageSizeOptions: ['10', '20', '50', '100'],
//     size: 'small',
//     onChange: (page, pageSize) => {
//       paginationState.value.current = page;
//       paginationState.value.pageSize = pageSize;
//     },
//     onShowSizeChange: (current, size) => {
//       paginationState.value.current = 1;
//       paginationState.value.pageSize = size;
//     },
//   };
// });
// const paginationConfig2 = computed(() => {
//   return {
//     current: paginationState2.value.current,
//     pageSize: paginationState2.value.pageSize,
//     total: deviceList.value.length,
//     showSizeChanger: true,
//     showQuickJumper: true,
//     showTotal: (total) => `共 ${total} 条`,
//     pageSizeOptions: ['10', '20', '50', '100'],
//     size: 'small',
//     onChange: (page, pageSize) => {
//       paginationState2.value.current = page;
//       paginationState2.value.pageSize = pageSize;
//     },
//     onShowSizeChange: (current, size) => {
//       paginationState2.value.current = 1;
//       paginationState2.value.pageSize = size;
//     },
//   };
// });
// 切换tab页面
async function onChangeTab(tab) {
  activeKey.value = tab;
  if (activeKey.value == 'device') {
    // 获取监测接口
  } else if (activeKey.value == 'history') {
    // 获取历史数据
  }
}
//树形菜单选择事件
const onSelect: TreeProps['onSelect'] = (keys, e) => {
  deviceType.value = '';
  systemID.value = '';
  deviceList.value = [];
  const title = e.node.title;
  if (e.node.parent && e.node.parent.node.type.toString().startsWith('sys')) {
    systemType.value = e.node.parent.node.type;
    if (deviceType.value != e.node.parent.node.type) deviceType.value = e.node.parent.node.type;
    systemID.value = e.node.type;
  } else {
    systemType.value = e.node.type;
    if (deviceType.value != e.node.type) deviceType.value = e.node.type;
  }
  getDeviceList(deviceType.value);
};
// 获取所有节点key的函数
const getAllNodeKeys = (nodes) => {
  const keys = [];
  const traverse = (nodeList) => {
    nodeList.forEach((node) => {
      keys.push(node.key);
      if (node.children && node.children.length > 0) {
        traverse(node.children);
      }
    });
  };
  traverse(nodes);
  return keys;
};

// 获取树形菜单数据
async function getDeviceType() {
  const result = await getDeviceTypeList({});
  if (result.length > 0) {
    const dataSource = [];
    let key = '0';
    const getData = (resultList, dataSourceList, keyVal) => {
      resultList.forEach((item, index) => {
        const children = item.children ? getData(item.children, [], `${keyVal}-${index}`) : [];
        dataSourceList.push({
          children: children,
          title: item.itemText,
          key: `${keyVal}-${index}`,
          type: item.itemValue,
          parentKey: `${keyVal}`,
        });
      });
      return dataSourceList;
    };

    treeData.value = getData(result, dataSource, key);
    // 数据就绪后设置展开key数组
    expandedKeys.value = getAllNodeKeys(treeData.value);
  }
}
// 根据选择设备获取设备列表
async function getDeviceList(deviceTypeVal?) {
  if (!deviceTypeVal) return;
  if (timer) {
    clearInterval(timer);
    timer = undefined;
  }
  const params: any = {
    devKind: deviceTypeVal,
  };
  const result = await getDeviceListByType(params);
  deviceList.value = result.records;
}

// 外层表格列配置
const outerColumns = [
  {
    title: '设备ID',
    dataIndex: 'id',
    key: 'id',
    align: 'center',
  },
  {
    title: '安装位置',
    dataIndex: 'strinstallpos',
    key: 'strinstallpos',
    align: 'center',
  },
  {
    title: '设备类型',
    dataIndex: 'devicekind_dictText',
    key: 'devicekind_dictText',
    align: 'center',
  },
  {
    title: '状态',
    dataIndex: 'netStatus',
    key: 'netStatus',
    align: 'center',
    customRender: ({ text }) => {
      text = '在线';
      return `${text}`;
    },
  },
];

// 内层表格列配置
const innerColumns = [
  {
    title: '地址',
    dataIndex: 'plcAddr',
    key: 'plcAddr',
    align: 'center',
  },
  {
    title: '数据code',
    dataIndex: 'valueCode',
    align: 'center',
    key: 'valueCode',
  },
  {
    title: '数据名称',
    dataIndex: 'valueName',
    align: 'center',
    key: 'valueName',
  },
  {
    title: '数据值',
    dataIndex: 'value',
    align: 'center',
    key: 'value',
  },
  {
    title: '时间',
    dataIndex: 'time',
    align: 'center',
    key: 'time',
  },
];

// 切换展开状态
const toggleExpand = (deviceId) => {
  const index = expandedRowKeys.value.indexOf(deviceId);

  if (index > -1) {
    // 如果已经展开，则关闭
    expandedRowKeys.value.splice(index, 1);
    if (timer) {
      clearInterval(timer);
      timer = undefined;
    }
  } else {
    // 如果未展开，则打开
    expandedRowKeys.value.push(deviceId);
    loadMonitoringData(deviceId);
  }
};
// 加载监测数据
let timer: null | NodeJS.Timeout = null;
async function loadMonitoringData(deviceId: string) {
  // 先清除之前的定时器
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
  // 定时器会在1秒后开始，所以先手动加载一次
  refreshData(deviceId);
  // 设置新的定时器
  timer = setInterval(() => {
    refreshData(deviceId);
  }, 1000);
}
async function refreshData(deviceId: string) {
  // 这里实现具体的请求逻辑
  const device = deviceList.value.find((d) => d.id === deviceId);
  const result = await getDevMonitorListById({ devId: deviceId.toString() });
  monitorList.value = Object.values(result.readData);
}

onMounted(() => {
  getDeviceType();
});
onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
    timer = undefined;
  }
});
// 监听分页变化
watch(
  () => [paginationState.value.current, paginationState.value.pageSize],
  () => {}
);
</script>

<style lang="less" scoped>
.safetyList {
  width: calc(100% - 20px);
  height: calc(100% - 80px);
  position: relative;
  margin: 70px 10px 10px 10px;

  .content {
    position: relative;
    width: 100%;
    height: 100%;

    .tab-box {
      display: flex;
      color: #fff;
      position: relative;
      background: linear-gradient(#001325, #012e4f);

      :deep(.zxm-tabs-nav) {
        margin: 0 !important;

        .zxm-tabs-tab {
          width: 180px;
          height: 45px;
          background: url('/@/assets/images/top-btn.png') center no-repeat;
          background-size: cover;
          display: flex;
          justify-content: center;
          font-size: 16px;
        }

        .zxm-tabs-tab-active {
          width: 180px;
          position: relative;
          background: url('/@/assets/images/top-btn-select.png') center no-repeat;
          background-size: cover;

          .zxm-tabs-tab-btn {
            color: #fff !important;
          }
        }

        .zxm-tabs-ink-bar {
          width: 0 !important;
        }

        .zxm-tabs-tab + .zxm-tabs-tab {
          margin: 0 !important;
        }
      }
    }

    .box-content {
      height: calc(100% - 50px);
      padding-top: 10px;
      box-sizing: border-box;

      .now-content {
        position: relative;
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .left-box {
          width: 20%;
          height: 100%;
          margin-right: 15px;
          padding: 10px;
          box-sizing: border-box;
          background: url('/@/assets/images/fire/bj1.png') no-repeat center;
          background-size: 100% 100%;
        }

        .right-box {
          width: calc(80% - 15px);
          height: 100%;
          padding: 10px;
          box-sizing: border-box;
          background: url('/@/assets/images/fire/bj1.png') no-repeat center;
          background-size: 100% 100%;

          .right-title {
            display: flex;
            height: 30px;
            align-items: center;
            font-size: 14px;
            color: #fff;
            margin-bottom: 10px;
          }
        }
      }
    }
  }
}

.down-btn {
  line-height: 15px;
  height: 20px;
  padding: 0px 17px;
  font-size: 12px;
}

.zxm-form {
  width: 50%;
  height: 100%;
  padding-top: 20px !important;
  box-sizing: border-box;
}

.zxm-picker,
.zxm-input {
  border: 1px solid #3ad8ff77 !important;
  background-color: #ffffff !important;
  color: #fff !important;
}

.card-item.selected {
  border: 2px solid #3ad8ff77;
  /* 选中时的边框颜色 */
}

::v-deep(.zxm-radio-wrapper) {
  font-size: 12px;
}

::v-deep(.zxm-input) {
  font-size: 12px;
}

::v-deep(.zxm-select:not(.zxm-select-customize-input) .zxm-select-selector) {
  border: 1px solid #3ad8ff77 !important;
}

// ::v-deep(.zxm-select-selection-item) {
//   color: #fff ;
// }

// ::v-deep(.zxm-form-item-label > label) {
//   color: #fff !important;
// }
/* 值样式 */
.high-value {
  color: #f5222d;
  font-weight: bold;
}
.low-value {
  color: #1890ff;
  font-weight: bold;
}
.normal-value {
  color: #52c41a;
}

/* 嵌套表格样式 */
:deep(.ant-table-expanded-row) > td {
  background-color: #f9f9f9 !important;
  padding: 0 !important;
}

:deep(.ant-table-expanded-row .ant-table) {
  margin: -10px -8px;
  background: #f9f9f9;
}

/* 自定义展开按钮 */
:deep(.ant-table-row-expand-icon) {
  margin-right: 8px;
}

.device-select-box {
  margin-top: 60px;
  width: 220px;
  height: calc(100% - 70px);
  overflow-y: auto;
  color: #fff;

  :deep(.zxm-tree) {
    background: transparent !important;
    color: #fff !important;

    .zxm-tree-switcher {
      background: transparent !important;
    }

    .zxm-tree-node-content-wrapper.zxm-tree-node-selected {
      background-color: #00b1c8;
    }

    .zxm-tree-node-content-wrapper:hover {
      background-color: #00b1c8;
    }
    input {
      height: 0px !important;
    }
  }

  &::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    border-radius: 10px;
    background: #ededed22;
    height: 100px;
  }

  &::-webkit-scrollbar-thumb {
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #4288a444;
  }
}
.device-select {
  width: 280px !important;
  height: calc(100% - 70px);
  background: var(--image-tree-bg) no-repeat;
  position: fixed;
  top: 100px;
  left: 55px;
  background-size: contain;
  pointer-events: auto;
  padding: 20px 10px 30px 10px;
}
</style>
<style>
div[aria-hidden='true'] {
  display: none !important;
}
</style>
