<template>
  <Card :bordered="false" style="height: 100%" class="device-tree">
    <Spin :spinning="loading">
      <div class="title">设备列表</div>
      <template v-if="treeData.length > 0">
        <Tree
          :fieldNames="fieldNames"
          :icon="getIcon"
          :clickRowToExpand="false"
          :treeData="treeData"
          :selectedKeys="selectedKeys"
          :load-data="loadChildrenTreeData"
          v-model:expandedKeys="expandedKeys"
          @select="onSelect"
        >
          <template #title="item">
            <span>
              <span v-if="item.type === 0 && item.online" title="在线设备"></span>
              <span v-if="item.type === 0 && !item.online" title="离线设备"></span>
              <span v-if="item.type === 2 && item.online" title="目录"></span>
              <span v-if="item.type === 2 && !item.online" title="目录"></span>
              <span v-if="item.type === 3 && item.online" title="在线通道"><video-camera-outlined /></span>
              <span v-if="item.type === 3 && !item.online" title="在线通道"></span>
              <span v-if="item.type === 4 && item.online" title="在线通道-球机"></span>
              <span v-if="item.type === 4 && !item.online" title="在线通道-球机"></span>
              <span v-if="item.type === 5 && item.online" title="在线通道-半球"></span>
              <span v-if="item.type === 5 && !item.online" title="在线通道-半球"></span>
              <span v-if="item.type === 6 && item.online" title="在线通道-枪机"></span>
              <span v-if="item.type === 6 && !item.online" title="在线通道-枪机"></span>
              <span v-if="item.online" class="device-online">{{ item.name }}</span>
              <span v-if="!item.online" class="device-offline">{{ item.name }}</span>
              <span>
                <i v-if="item.hasGPS && item.online" style="color: #9d9d9d"></i>
                <i v-if="item.hasGPS && !item.online" style="color: #9d9d9d"></i>
              </span>
            </span>
          </template>
        </Tree>
      </template>
      <Empty v-else description="暂无数据" />
    </Spin>
  </Card>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { getDeviceList, getTreeInfo } from './DeviceService';
  import { VideoCameraOutlined } from '@ant-design/icons-vue';
  import { Card, Spin, Tree, Empty } from 'ant-design-vue';

  const emit = defineEmits(['select']);

  const loading = ref<boolean>(false);
  // 设备树列表数据
  const treeData = ref<any[]>([]);
  // 当前展开的项
  const expandedKeys = ref<any[]>([]);
  // 当前选中的项
  const selectedKeys = ref<any[]>([]);
  // 当前选中的设备
  const currentDevice = ref<any>(null);

  const fieldNames = ref({
    key: 'id',
    title: 'name',
    children: 'children'
  });

  getAllDeviceList();

  /**
   * 加载顶级设备信息
   */
  async function getAllDeviceList() {
    let currentPage = 1;
    let count = 100;
    let deviceList = [];
    await getAllDeviceListIteration(deviceList, currentPage, count);
  }

  function getAllDeviceListIteration(deviceList, currentPage, count) {
    getDeviceList(currentPage, count)
      .then((res) => {
        if (res.list) {
          for (let i = 0; i < res.list.length; i++) {
            res.list[i].id = res.list[i].deviceId;
            res.list[i].isLeaf = false;
            res.list[i].type = res.list[i].online;
            res.list[i].online = res.list[i].online === 1;
          }
          loading.value = true;
          treeData.value = [];
          treeData.value = deviceList.concat(res.list);
          if (treeData.value.length < res.total) {
            currentPage++;
            getAllDeviceListIteration(treeData.value, currentPage, count);
          }
        }
      })
      .finally(() => (loading.value = false));
  }

  /**
   * 加载子级设备信息
   */
  async function loadChildrenTreeData(treeNode) {
    let deviceId = treeNode.deviceId;
    let parentId = treeNode.eventKey;
    let onlyCatalog = false;
    let currentPage = 1;
    let count = 100;
    let childDeviceList = [];
    getTreeIteration(treeNode, deviceId, parentId, onlyCatalog, childDeviceList, currentPage, count);
  }

  function getTreeIteration(treeNode, deviceId, parentId, onlyCatalog, childDeviceList, currentPage, count) {
    getTreeInfo(deviceId, parentId, onlyCatalog, currentPage, count).then((res) => {
      if (res.list) {
        channelDataHandler(res.list);
        childDeviceList = childDeviceList.concat(res.list);
        if (childDeviceList.length == 0) {
          treeNode.dataRef.isLeaf = true;
        } else {
          treeNode.dataRef.children = childDeviceList;
          if (expandedKeys.value.length > 0) {
            // 判断获取的子级是否有当前展开的项
            let subKeys: any[] = [];
            for (let key of expandedKeys.value) {
              if (childDeviceList.findIndex((item) => item.deviceId === key) !== -1) {
                subKeys.push(key);
              }
            }
            if (subKeys.length > 0) {
              expandedKeys.value = [...expandedKeys.value];
            }
          }
        }
        treeData.value = [...treeData.value];
        return Promise.resolve();
      }
    });
  }

  function channelDataHandler(data) {
    if (data.length > 0) {
      for (let i = 0; i < data.length; i++) {
        let item = data[i];
        let type = 3;
        if (item.id.length <= 10) {
          type = 2;
        } else {
          if (item.id.length > 14) {
            let channelType = item.id.substring(10, 13);
            if (channelType === '215' || channelType === '216') {
              type = 2;
            }
            console.log(type);
            if (item.basicData.ptztype === 1) {
              // 1-球机;2-半球;3-固定枪机;4-遥控枪机
              type = 4;
            } else if (item.basicData.ptztype === 2) {
              type = 5;
            } else if (item.basicData.ptztype === 3 || item.basicData.ptztype === 4) {
              type = 6;
            }
          } else {
            if (item.basicData.subCount > 0 || item.basicData.parental === 1) {
              type = 2;
            }
          }
        }
        data.name = item.name || item.basicData.channelId;
        data.isLeaf = type !== 2;
        data.type = type;
        data.online = item.basicData.status === 1;
        data.hasGPS = item.basicData.longitude * item.basicData.latitude !== 0;
      }
    }
  }

  /**
   * 树选择事件
   */
  function onSelect(selKeys, event) {
    if (selKeys.length > 0 && selectedKeys.value[0] !== selKeys[0]) {
      setSelectedKey(selKeys[0], event.selectedNodes[0], event.node.basicData, event.node.type === 2);
    } else {
      // 这样可以防止用户取消选择
      setSelectedKey(selectedKeys.value[0]);
    }
  }

  /**
   * 设置当前选中的行
   */
  function setSelectedKey(key: string, data?: object, basicData?: object, isCatalog?: boolean) {
    selectedKeys.value = [key];
    if (data) {
      currentDevice.value = data;
      emit('select', data, basicData, isCatalog);
    }
  }

  function getIcon(props) {
    console.log('props', props);
  }
</script>
<style lang="less" scoped>
  .device-tree {
    :deep(.ant-card-body) {
      padding: 25px 25px 25px 15px;
    }
  }

  .title {
    font-size: 16px;
    margin-bottom: 10px;
  }
</style>
