<template>
  <div style="width: 100%; height: 100%; padding: 20px;">
    <div ref="endElement" style="width:100px;height: 100px;background-color:bisque;position: absolute;top: 60%;z-index: 10" draggable="true"></div>
    <web3d v-if="mode === 'web3d'" ref="web3d" :props="web3dProps" @event="handleEvent" @render="render" @tap="tap"
           @scene-load="sceneLoad" @loader-hide="loaderHide"></web3d>
    <diagram3d v-if="mode === 'diagram3d'" ref="diagram3d" :props="diagram3dProps" @scene-load="sceneLoad"
               @loader-hide="loaderHide" @point-move="pointMove" @tap="tap" @render="render"></diagram3d>
    <div v-for="(devicePoint,i) in devicePoints"
         v-if="mode ==='diagram3d'"
         :style="{left: devicePoint.xy.x - 2 + 'px', top: devicePoint.xy.y - 2 + 'px'}"
         :class="'device-dot device-dot'+devicePoint.id"></div>
    <div  v-if="mode === 'space3d'" style="position:absolute; left:100px; top: 100px; width:1800px; height: 700px;">
      <space3d ref="space3d" :props="space3dProps" v-if="space3dProps" @scene-load="sceneLoad" @loader-hide="loaderHide"
               @tap="tap" @render="render">
        <template v-slot:header>
          <div style="width: 200px;">北京办公室</div>
        </template>
<!--        <template v-slot:inner>-->
<!--          <div v-for="devicePoint in devicePoints"-->
<!--               :style="{ left: devicePoint.xy.x - 1 + 'px', top: devicePoint.xy.y - 1 + 'px' }" class="device-dot device-dot0"></div>-->
<!--        </template>-->
        <template v-slot:footer>
          <div style="width: 200px;">全楼设备总数: {{ deviceCount }}</div>
        </template>
      </space3d>
    </div>

    <canvas v-if="mode === 'jsWeb3d'" id="idWeb3d" style="width: 100%; height: 100%"></canvas>
    <canvas v-if="mode === 'jsDiagram3d'" id="idDiagram3d" style="width: 100%; height: 100%"></canvas>
    <canvas v-if="mode === 'jsSpace3d'" id="idSpace3d" style="width: 100%; height: 100%"></canvas>
  </div>
  <div class="toolbar">
    <button class="action-button" @click="switchMode('ui')">UI</button>
    <button class="action-button" @click="switchMode('web3d')">Web3d</button>
    <button class="action-button" @click="switchMode('diagram3d')">Diagram3d</button>
    <button class="action-button" @click="switchMode('space3d')">Space3d</button>
    <button class="action-button" @click="switchMode('jsWeb3d')">Js-Web3d</button>
    <button class="action-button" @click="switchMode('jsDiagram3d')">Js-Diagram3d</button>
    <button class="action-button" @click="switchMode('jsSpace3d')">Js-Space3d</button>
    <button class="action-button" @click="doTest">Test</button>
    <div style="padding-left: 20px">{{ selectedDevice.deviceName }} {{ selectedDevice.data }}</div>
  </div>
  <!--  <kf-text :props="textProps" style="position: absolute; left: 10px; top: 10px;"></kf-text>-->
  <kf-card v-if="ready && mode === 'ui'" ref="device1" :props="cardProps1"
           style="position: absolute; left: 0px; top: 300px; width: 250px; height: 250px;"></kf-card>
  <kf-cards v-if="ready && mode === 'ui'" ref="device2" :props="cardProps2"
            style="position: absolute; left: 270px; top: 300px; width: 250px; height: 250px;"></kf-cards>
  <kf-switch v-if="ready && mode === 'ui'" ref="device3" :props="switchProps"
             style="position: absolute; left: 550px; top: 300px; width: 50px; height: 30px;"></kf-switch>
  <kf-video v-if="ready && mode === 'ui'" ref="device4" :props="videoProps"
            style="position: absolute; left: 650px; top: 300px; width: 480px; height: 270px;"></kf-video>
  <div>
    <kf-card v-for="(cardProp, index) in cardPropsList" v-if="ready && mode === 'ui'" ref="devices" :props="cardProp"
             :style="{ left: 500 * index + 'px' }"
             style="position: absolute; top: 600px; width: 480px; height: 270px;"></kf-card>
  </div>
  <div v-if="ready && mode === 'ui' && deviceObj.deviceName"
       style="position: absolute; left: 1200px; top: 300px; width: 200px; color: white" @click="doClick">{{
      deviceObj.deviceName }} {{ deviceObj?.getProperty('temperature').label.zhCN }}:
    {{ deviceObj.temperature }} {{ deviceObj?.getProperty('temperature').unit }}
  </div>
  <div v-if="ready && mode === 'ui'" style="position: absolute; left: 1500px; top: 300px; width: 200px; color: white">
    <div style="background-color: #00b8ff; width: 300px; height:200px;">
      <kfVideoItem :props="cameraInfo" ref="video"></kfVideoItem>
    </div>
    <div v-for="dev in deviceObjs">{{ dev.deviceName }}的温度: {{ dev.temperature }}</div>
    <!--    <div style="background-color: #00b8ff; width: 100px; height: 100px;">-->
    <!--      <kfVideoItem :props="cameraInfo" ref="video"></kfVideoItem>-->
    <!--    </div>-->
  </div>

  <div :style="{ left: partPosition.x + 'px', top: partPosition.y + 'px' }"
       style="position: absolute; width: 10px; height: 10px; background-color: #00b8ff"></div>
</template>

<script>
import { onMounted, onUnmounted, ref, watch, nextTick } from 'vue';
import KingfisherUI from './index';
import KingfisherJSUI from './index_js';
import _ from 'lodash'
import HLSCore from '@cloudgeek/playcore-hls'
import LeaderLine from 'leader-line-vue';

export default {
  name: 'App',
  props: {},
  setup(props, { emit }) {
    let endElement= ref(null);

      KingfisherUI.initDataManager((devices) => {
        console.log('设备数据变化', devices);
      }).then(async () => {
        console.log('设备数据管理器初始化完成');
        ready.value = true;
        console.log('项目信息', KingfisherUI.getProject());
        console.log('三维场景', await KingfisherUI.get3dScenes(78035)); // 获取三维场景, 可使用Web3d组件展示
        console.log('系统图场景', await KingfisherUI.getDiagramScenes(78030)); // 获取系统图场景, 可使用Diagram3d组件展示
        console.log('数据连接', KingfisherUI.getConnectors());
        console.log('物模型', KingfisherUI.getTSL());
        let deviceList = KingfisherUI.queryDevices();
        deviceCount.value = deviceList.length;
        console.log('设备清单', deviceList); // 没有参数, 返回所有设备, 数据量比较大
        console.log('窗帘', KingfisherUI.queryDevices({ filter: { deviceType: '窗帘' } }));
        console.log('灯', KingfisherUI.queryDevices({ filter: { deviceType: '灯' } }));
        console.log('A栋F2关着的灯',
            KingfisherUI.queryDevices({ filter: { deviceType: '灯', floor: 'F2', building: 'A栋', 'data.switch': false } }));
        console.log('A栋F1F2关着的灯', KingfisherUI.queryDevices(
            { filter: { deviceType: '灯', floor: ['F1', 'F2'], building: 'A栋', 'data.switch': false } }));
        console.log('A栋F2以上关着的灯', KingfisherUI.queryDevices(
            { filter: { deviceType: '灯', floor: { '>=': 'F2' }, building: 'A栋', 'data.switch': false } }));
        console.log('A栋F4关着的灯', KingfisherUI.queryDevices(
            {
              filter: {
                deviceType: '灯',
                floor: (floor) => { return floor === 'F4'; },
                building: 'A栋',
                'data.switch': false,
              },
            }));
        console.log('灯排序-UUID', KingfisherUI.queryDevices({ filter: { deviceType: '灯' }, order: 'uuid' }));
        console.log('灯排序-DeviceMapId-UUID',
            KingfisherUI.queryDevices({ filter: { deviceType: '灯' }, order: ['deviceMapId', 'uuid'] }));
        console.log('灯反向排序-DeviceMapId',
            KingfisherUI.queryDevices({ filter: { deviceType: '灯' }, order: [['deviceMapId', 'desc']] }));
        console.log('灯反向排序-DeviceMapId, UUID',
            KingfisherUI.queryDevices({ filter: { deviceType: '灯' }, order: [['deviceMapId', 'desc'], ['uuid', 'desc']] }));
        console.log('灯-Top10', KingfisherUI.queryDevices({ filter: { deviceType: '灯' }, top: 10 }));
        console.log('分组-DeviceType', KingfisherUI.queryDevices({ group: 'deviceType' }));
        console.log('灯反向排序-DeviceMapId, UUID, 再分组',
            KingfisherUI.queryDevices(
                { filter: { deviceType: '灯' }, order: [['deviceMapId', 'desc'], ['uuid', 'desc']], group: 'deviceMapId' }));
        console.log('A栋F2灯-状态分组',
            KingfisherUI.queryDevices({ filter: { deviceType: '灯', floor: 'F2', building: 'A栋' }, group: 'deviceStatus' }));
        console.log('设备类型', KingfisherUI.getDeviceTypes());
        let data = KingfisherUI.deviceManager.getDeviceDataForDeviceId('e4d85425bdf7851228c9f006469a9ee0');
        console.log('设备数据', data);
        console.log('设备物模型', KingfisherUI.deviceManager.getDeviceModel(data));
        console.log('设备属性列表', KingfisherUI.deviceManager.getDeviceProperties(data));
        console.log('设备属性', KingfisherUI.deviceManager.getDevicePropertyModel(data, 'temperature'));
        console.log('设备属性标签', KingfisherUI.deviceManager.getPropertyLabel(data, 'temperature'));
        console.log('根据三维模型找到物模型', KingfisherUI.deviceManager.getModelBy3dModelName('water storage tank'));
        let spaceManager = KingfisherUI.spaceManager;
        // let spaceThemes = await spaceManager.querySpaceThemeList({ projectId: 8419, group: "" });
        // console.log('部件主题', spaceThemes);
        // let spaceParts = await spaceManager.getSpacePart();
        // console.log('部件列表', spaceParts);
        // let partTypes = await spaceManager.getPartTypes();
        // console.log('部件类型', partTypes);
        // let buildings = await spaceManager.getBuildings(8419);
        // console.log('区域用途', await spaceManager.findAreaPurpose(8419));
        // console.log('建筑列表', buildings); // 可用于Space3d组件展示
        // let areas = await spaceManager.findSpaceGeo({
        //   projectId: 8403,
        //   buildingId: 'yoasU3vZ0vMN7ciomzL5P',
        //   floorId: 'Ixfd5IOW9qCfxytc4kVlS',
        //   type: 'area',
        // });
        // console.log('区域列表', areas);
        /*let floors = await spaceManager.getFloors(8419, buildings[0].nanoId);
        console.log('楼层列表', floors); // 可用于Space3d组件展示
        let cameraCount = await spaceManager.countByGroup(8419, buildings[0].nanoId, floors[0].nanoId, 'camera');
        console.log('摄像头数量', cameraCount);
        let cameras = await spaceManager.findSpaceGeo({
          projectId: 8419,
          buildingId: buildings[0].nanoId,
          floorId: floors[0].nanoId,
          subType: 'camera',
        });
        console.log('摄像头列表', cameras);


        let areaData = await spaceManager.aggArea(8419, buildings[0].nanoId, floors[0].nanoId, '');
        console.log('统计', areaData);*/

        KingfisherUI.queryAlarm().then(res => {
          console.log('告警列表', res.alarms);
        });

        console.log('组件主题', KingfisherUI.getWidgetThemes());

        let spaceSetting = new KingfisherUI.Space3dProps();
        //8490
        spaceSetting.buildingId = 'hpxh5esgO-MDGBu9d8Gax'; //
        spaceSetting.floorId = 'QO2hUBbXcl8kiAmC3TOrx'; //楼层ID
        //8481
        // spaceSetting.buildingId = "FuNTD7HQjnlGd2B3cIXhV";
        // spaceSetting.floorId = 'qTqi0FCdbZk72JbUfTdHG';
        // spaceSetting.buildingId = 'HZ9kkz74WxgbW6tA2p94D'; //建筑ID
        // //spaceSetting.buildingId = 'mVP3QbklHO5CDXrJBlB2q'; //建筑ID
        // spaceSetting.buildingName = '北京';
        // spaceSetting.floorId = 'nInIJm4wE4gulDvyERU4z'; //
        // spaceSetting.dialogShowNumber ={area:0,device:0};
        // spaceSetting.partType = [
        //   'wall',
        //   // 'pipeline',
        //   'model.window',
        //   'model.door',
        //   'area',
        //   'model.building',
        //   'model.camera',
        //   'model.sensor',
        //   'model.light',
        //   'model.equipment',
        //   'model.furniture',
        //   'model.parking',
        //   'pipeline'
        // ];

        //8403
        // {
        //   "projectId": 8403,
        //     "buildingId": "YAYQ_hLz8s8sAY33dGCxb",
        //     "floorId": "nInIJm4wE4gulDvyERU4z"

        // {
        //   "projectId": 8403,
        //     "buildingId": "yoasU3vZ0vMN7ciomzL5P",
        //     "floorId": "Ixfd5IOW9qCfxytc4kVlS"
        // }
        // spaceSetting.buildingId = 'SrK2p2ZzujRATjlBRKZ-U'; //建筑ID
        // spaceSetting.buildingId = 'mVP3QbklHO5CDXrJBlB2q'; //建筑ID
        // {
        //   "projectId": 8403,
        //     "buildingId": "hpxh5esgO-MDGBu9d8Gax",
        //     "floorId": "QO2hUBbXcl8kiAmC3TOrx"
        // }
        spaceSetting.buildingName = '北京';
        spaceSetting.id = 'webSpace'+new Date();
        //spaceSetting.floorId = '5a5L9vTS6iOf39IIVG8-O'; //楼层ID
        spaceSetting.buildingName = '新建楼层1';
        spaceSetting.floorName = 'F1';
        // spaceSetting.partType = ['wall','area', 'pipeline']; //楼层ID
        spaceSetting.logo='https://img1.baidu.com/it/u=2931243091,718249849&fm=253&fmt=auto&app=120&f=JPEG?w=569&h=427';
        spaceSetting.theme = KingfisherUI.getWidgetThemes()[0]; //主题
        spaceSetting.cameraViewMode = true;
        space3dProps.value = spaceSetting;

        console.log('空间设置', spaceSetting);
        let areas1 = await spaceManager.findSpaceGeo({
          projectId: 8403,
          buildingId: '3XRybotuZqbOpWjh7P45g',
          floorId: 'gkRsb8MEFZR1IgEj4TS1S',
          type: 'area',
        });
        console.log('区域列表', areas1);
      });

    /*KingfisherJSUI.initDataManager().then(async () => {
      /!*console.log('设备数据管理器初始化完成');
      ready.value = true;
      console.log('项目信息', KingfisherJSUI.getProject());
      console.log('三维场景', await KingfisherJSUI.get3dScenes(78035)); // 获取三维场景, 可使用Web3d组件展示
      console.log('系统图场景', await KingfisherJSUI.getDiagramScenes(78030)); // 获取系统图场景, 可使用Diagram3d组件展示
      console.log('数据连接', KingfisherJSUI.getConnectors());
      console.log('物模型', KingfisherJSUI.getTSL());
      let deviceList = KingfisherJSUI.queryDevices();
      deviceCount.value = deviceList.length;
      console.log('设备清单', deviceList); // 没有参数, 返回所有设备, 数据量比较大
      console.log('窗帘', KingfisherJSUI.queryDevices({filter: {deviceType: '窗帘'}}));
      console.log('灯', KingfisherJSUI.queryDevices({filter: {deviceType: '灯'}}));
      console.log('A栋F2关着的灯',
          KingfisherJSUI.queryDevices(
              {filter: {deviceType: '灯', floor: 'F2', building: 'A栋', 'data.switch': false}}));
      console.log('A栋F1F2关着的灯', KingfisherJSUI.queryDevices(
          {filter: {deviceType: '灯', floor: ['F1', 'F2'], building: 'A栋', 'data.switch': false}}));
      console.log('A栋F2以上关着的灯', KingfisherJSUI.queryDevices(
          {filter: {deviceType: '灯', floor: {'>=': 'F2'}, building: 'A栋', 'data.switch': false}}));
      console.log('A栋F4关着的灯', KingfisherJSUI.queryDevices(
          {
            filter: {
              deviceType: '灯',
              floor: (floor) => { return floor === 'F4'; },
              building: 'A栋',
              'data.switch': false,
            },
          }));
      console.log('灯排序-UUID', KingfisherJSUI.queryDevices({filter: {deviceType: '灯'}, order: 'uuid'}));
      console.log('灯排序-DeviceMapId-UUID',
          KingfisherJSUI.queryDevices({filter: {deviceType: '灯'}, order: ['deviceMapId', 'uuid']}));
      console.log('灯反向排序-DeviceMapId',
          KingfisherJSUI.queryDevices({filter: {deviceType: '灯'}, order: [['deviceMapId', 'desc']]}));
      console.log('灯反向排序-DeviceMapId, UUID',
          KingfisherJSUI.queryDevices(
              {filter: {deviceType: '灯'}, order: [['deviceMapId', 'desc'], ['uuid', 'desc']]}));
      console.log('灯-Top10', KingfisherJSUI.queryDevices({filter: {deviceType: '灯'}, top: 10}));
      console.log('分组-DeviceType', KingfisherJSUI.queryDevices({group: 'deviceType'}));
      console.log('灯反向排序-DeviceMapId, UUID, 再分组',
          KingfisherJSUI.queryDevices(
              {filter: {deviceType: '灯'}, order: [['deviceMapId', 'desc'], ['uuid', 'desc']], group: 'deviceMapId'}));
      console.log('A栋F2灯-状态分组',
          KingfisherJSUI.queryDevices(
              {filter: {deviceType: '灯', floor: 'F2', building: 'A栋'}, group: 'deviceStatus'}));
      console.log('设备类型', KingfisherJSUI.getDeviceTypes());
      let data = KingfisherJSUI.deviceManager.getDeviceDataForDeviceId('3b567d4c4c456666e6c95413f4407bec');
      console.log('设备数据', data);
      console.log('设备物模型', KingfisherJSUI.deviceManager.getDeviceModel(data));
      console.log('设备属性列表', KingfisherJSUI.deviceManager.getDeviceProperties(data));
      console.log('设备属性', KingfisherJSUI.deviceManager.getDevicePropertyModel(data, 'temperature'));
      console.log('设备属性标签', KingfisherJSUI.deviceManager.getPropertyLabel(data, 'temperature'));
      console.log('根据三维模型找到物模型', KingfisherJSUI.deviceManager.getModelBy3dModelName('water storage tank'));
      let spaceManager = KingfisherJSUI.spaceManager;
      let spaceParts = await spaceManager.getSpacePart();
      console.log('部件列表', spaceParts);
      let partTypes = await spaceManager.getPartTypes();
      console.log('部件类型', partTypes);
      let buildings = await spaceManager.getBuildings(8419);
      console.log('区域用途', await spaceManager.findAreaPurpose(8419));
      console.log('建筑列表', buildings); // 可用于Space3d组件展示
      let floors = await spaceManager.getFloors(8419, buildings[0].nanoId);
      console.log('楼层列表', floors); // 可用于Space3d组件展示
      let cameraCount = await spaceManager.countByGroup(8419, buildings[0].nanoId, floors[0].nanoId, 'camera');
      console.log('摄像头数量', cameraCount);
      let cameras = await spaceManager.findSpaceGeo({
        projectId: 8419,
        buildingId: buildings[0].nanoId,
        floorId: floors[0].nanoId,
        subType: 'camera',
      });
      console.log('摄像头列表', cameras);


      let areaData = await spaceManager.aggArea(8419, buildings[0].nanoId, floors[0].nanoId, '');
      console.log('统计', areaData);

      KingfisherJSUI.queryAlarm().then(res => {
        console.log('告警列表', res.alarms);
      });*!/
    });*/

    // 监听三维场景的消息
    window.addEventListener('message', (e) => {
      if (e.data && e.data.action === 'kcUiEvent') {
        console.log('收到消息', e.data);
      }
    });

    // 设置三维场景信息
    const web3dSetting = new KingfisherUI.Web3dProps();
    web3dSetting.sceneUrl = '8403/25'; //场景地址
    web3dSetting.debugPuzzle = false;

    const web3dProps = ref(web3dSetting);

    // 设置三维系统图信息
    const diagramSetting = new KingfisherUI.Diagram3dProps();
    diagramSetting.sceneUrl = '8403/2.k3ds'; //场景地址8403/2.k3ds
    diagramSetting.openFocus = false;
    diagramSetting.debugPuzzle = false;
    const diagram3dProps = ref(diagramSetting);

    // 设置三维空间图信息
    const space3dProps = ref();

    const mode = ref('space3d');
    const web3d = ref();
    const diagram3d = ref();
    const space3d = ref();
    const devicePoints = ref([]);
    const selectedDevice = ref({});
    let lines = [];
    const doTest = () => {
      if (mode.value === 'ui') {
        KingfisherUI.updateTheme('light'); // 改变主题
        KingfisherUI.linkToDevice(deviceData4, cardProps1, device1);
        KingfisherUI.linkToDevice([deviceData4], cardPropsList, devices);
        cameraInfo.value.src = "http://kbs-dokdo.gscdn.com/dokdo_300/_definst_/dokdo_300.stream/playlist.m3u8";
      }

      if (mode.value === 'web3d') {
        /*web3dProps.value.camera = '机位.1'; //设置摄像头
        web3dProps.value.event = { //触发事件
          event: '1',
          params: {},
        };
        web3dProps.value.showStats = true;

        let web3dManager = KingfisherUI.getWeb3dManager(web3d); //获取三维管理器
        console.log('web3dManager', web3dManager);
        console.log('Cameras', web3dManager.getAllCameraArgs(null)); //获取所有摄像头
        web3dManager.setActiveCameraArg('机位.1', 2); //设置摄像头
        console.log('events', web3dManager.events); //获取事件
        web3d.value.issueEvent(web3dManager.events[1], []); //触发事件

        KingfisherUI.updateWeb3dProps(web3d, {
          camera: '机位.1',
        });*/
        let web3dManager = KingfisherUI.getWeb3dManager(web3d);
        web3dProps.value.sceneUrl = "8403/27";
        console.log('Cameras', web3dManager.getAllCameraArgs(null)); //获取所有摄像头
        web3dManager.setActiveCameraArg('机位.1', 2); //设置摄像头
        console.log('camera', web3dManager.scene.activeCamera.orbitCameraArgs);
      }

      const updatePosition = function (node, xy,type) {
        console.log('updatePosition', node.id, xy,type);
        if (devicePoints.value) {
          let index = devicePoints.value.findIndex(item => item.id == node.id)
          if (devicePoints.value[index]) {
          devicePoints.value[index].xy = xy;
          }
          if (index<0) {
            devicePoints.value.push({id: node.id, xy:xy})
          }
          //创建连线
          setTimeout(() => {
            //清除连线
            Object.keys(lines).map(key => {
              if (key==node.id &&  lines[node.id]) {
                lines[node.id].position();
              }
              // else{
              //   lines[key].remove();
              //   delete lines[key];
              // }
            })
            if (!lines[node.id]) {
              let startDom = document.querySelector('.device-dot'+node.id);
              lines[node.id] = LeaderLine.setLine(startDom, endElement.value,
                  {startPlug: 'disc', endPlug: 'disc', color: 'red', size: 2});
            }
          }, 0)
        }

      }
      const updatePosition1 = function (node, xy) {
        if (devicePoints.value) {
            devicePoints.value[0].xy = xy;
          //创建连线
          setTimeout(() => {
            //清除连线
            Object.keys(lines).map(key => {
              if (key==node.id &&  lines[node.id]) {
                lines[node.id].position();
              }
              else{
                lines[key].remove();
                delete lines[key];
              }
            })
            if (!lines[node.id]) {
              let startDom = document.querySelector('.device-dot');
              lines[node.id] = LeaderLine.setLine(startDom, endElement.value,
                  {startPlug: 'disc', endPlug: 'disc', color: 'red', size: 2});
            }
          }, 0)
        }

      }

      if (mode.value === 'diagram3d') { // Diagram3d Test
        let diagram3dManager = KingfisherUI.getDiagram3dManager(diagram3d);
        console.log('diagram3dManager', diagram3dManager);
        console.log(diagram3dManager.getPartsBriefInfo(diagram3d)); // 获取场景内所有部件的简要信息
        console.log(diagram3dManager.getPartData('water storage tank')); // 获取某个部件的信息
        diagram3dManager.addEventListener(diagram3dManager.scene, 'mRukTDZQhvkzvfO2cQyCK', (e) => {
          console.log('click', e); // 点击事件处理
        }, selectedDevice);
        let widgetList = diagram3dManager.getDevicePartsBriefInfo(diagram3dManager.scene);
        //监听
        // if (devicePoints.value) {
          // let index = devicePoints.value.findIndex(item => item.id == part.partId)
          // if (index<0) {
          devicePoints.value=[{id:'', xy: ''}]
          // }
        // }
        widgetList.map((part,index) => {
          // diagram3dManager.addEventListener(diagram3dManager.scene, part.partId, (e) => {
          //   console.log('坚听到', e, part)
          // });
          //直连显示多个
          //直连显示多个

           diagram3dManager.getDevicePosition(updatePosition,'onLeave,onEnter,onLoad,onTap');

          //点击事件
           //devicePoints.value=[{id: part.partId, xy: ''}];
           // diagram3dManager.getDevicePosition(updatePosition1,'onTap')
          //     diagram3dManager.addEventListener(diagram3dManager.scene, part.partId, (e) => {
          //       console.log('坚听到', e, part)
          //
          //     });
          //移入事件
          //   diagram3dManager.addMouseEventListeners(diagram3dManager.scene, part.partId, {onEnter: (o) => {console.log(o);
         // diagram3dManager.getDevicePosition(updatePosition1,'onEnter');
         //      }, onLeave: (o) => {console.log(o)}}, true)
        })
        console.log('获取组件数据列表', diagram3dManager.getDataListByPart(diagram3dManager.scene, widgetList[0].partId))
        let result = diagram3dManager.getDataListByPart(diagram3dManager.scene, widgetList[0].partId);
        console.log('获取场景分组信息', diagram3dManager.getGroups(diagram3dManager.scene))
        console.log('获取场景分组简要信息', diagram3dManager.getGroupsBriefInfo(diagram3dManager.scene))
        console.log('获取场景组件简要信息', diagram3dManager.getMiscPartsBriefInfo(diagram3dManager.scene))
        console.log('根据组件Id获取组件简要信息', diagram3dManager.getPartBriefInfoByPartId(diagram3dManager.scene, widgetList[0].partId))
        console.log('获取组件数据列表', diagram3dManager.getPartData(diagram3dManager.scene, widgetList[0].partId))
        console.log('根据key获取组件数据', diagram3dManager.getPartDataByKey(diagram3dManager.scene, widgetList[0].partId, '文字:文字内容'))
        console.log('获取场景中所有组件的简要信息列表', diagram3dManager.getPartsBriefInfo(diagram3dManager.scene))
        console.log('获取设备组件简要信息', diagram3dManager.getDevicePartsBriefInfo(diagram3dManager.scene))
        console.log('获取管线组件简要信息', diagram3dManager.getPipelinePartsBriefInfo(diagram3dManager.scene))
        let con = diagram3dManager.getPartData(diagram3dManager.scene, widgetList[0].partId);
        con['文字:文字内容'] = 'ceshi01'
        console.log('设置组件数据', diagram3dManager.setPartData(diagram3dManager.scene, widgetList[0].partId, con))
        console.log('获取场景面板信息', diagram3dManager.getPanelsInfo(diagram3dManager.scene))
        console.log('根据组件id获取面板信息', diagram3dManager.getPanelsInfoByPartId(diagram3dManager.scene, widgetList[0].partId))

        console.log(widgetList)
        // diagram3dManager.addDevicePoint('mRukTDZQhvkzvfO2cQyCK', partPosition);
      }

      if (mode.value === 'space3d') {
         let space3dManager = KingfisherUI.getSpace3dManager(space3d);
          window.postMessage({action: "kcUiEvent",address:'/space_auto_focus',

              data: false,
            })

         console.log('space3dManager', space3dManager);
        // console.log('buildings', space3dManager.manager.building); // 获取项目下的建筑
        // console.log('floors', space3dManager.manager.floor); // 获取楼层
        // space3dManager.getAllDeviceTypes().then(res => {
        //   console.log("deviceTypes", res);
        // }) // 获取所有设备类型
        // space3dManager.updateDevicePopupHandler((device) => {
        //   return device.deviceTypeCode !== 'light'; //控制弹窗逻辑, 剔除灯, 不自动弹出窗口
        // });
        space3dManager.on3dObjectEnter((e) => {
          // 点击事件处理, 获取设备位置
          console.log('enter', e);
          devicePoints.value = e.info.lines; // 获取点击的设备坐标
          // updatePos(); //更新点位坐标
        });
        space3dManager.on3dObjectClick((e) => {
          // 点击事件处理, 获取设备位置
          console.log('click', e);
          devicePoints.value = e.info.lines; // 获取点击的设备坐标
          if (e.info?.device) {
            selectedDevice.value = e.info.device, // 设置选中的设备
                KingfisherUI.createDeviceData(selectedDevice.value, selectedDevice); // 绑定到相应对象
          }
          // updatePos(); //更新点位坐标
        });
        // const updatePos = () => {
        //   // 更新设备位置
        //   if (devicePoints.value) {
        //     devicePoints.value.map(devicePoint => {
        //       devicePoint.xy = space3dManager.get3dObjectPosition(devicePoint.pos3d);
        //       if (JSON.stringify(devicePoint.lastXy)!=JSON.stringify(devicePoint.xy)
        //           && (!devicePoint.lastUpdate || Date.now() - devicePoint.lastUpdate > 1000)) {
        //         console.log(devicePoint.lastXy, devicePoint.xy, devicePoint.lastUpdate, Date.now());
        //         devicePoint.lastXy = devicePoint.xy;
        //         devicePoint.lastUpdate = Date.now();
        //         //创建连线
        //         setTimeout(() => {
        //            if (lines[0]) {
        //              lines[0].position();
        //            return;
        //            }
        //           let startDom = document.querySelector('.device-dot'+0);
        //           lines[0] = LeaderLine.setLine(startDom, endElement.value,
        //               {startPlug: 'disc', endPlug: 'disc', color: 'red', size: 2});
        //
        //         }, 0)
        //       }
        //     });
        //
        //   }
        // };
        // space3dManager.onCameraChanged(updatePos); // 当摄像头变化时更新点位坐标
        let areas=[]
        space3dManager.setCustomFilter((item,index) => { // 更新自定义过滤器, 只显示灯
         let type=item.name.split(' ')
         let isExist= areas.find(i => i.type === type[0])
         if(isExist){
           isExist.area.push(item)
         }else{
           areas.push({
             type: type[0],
             area: [item]
           })
         }

           console.log(areas,"areas")

          return !item.device || item.device.deviceTypeCode === 'light';
        });

        KingfisherUI.updateProps(space3dProps.value, {
          buildingId: 'WOGWsExlANKgcQBriyqc5',
          floorId: 'WKlSHgJ_kb_i1wZrU0mxY',
        });
        // /*KingfisherUI.updateTheme('light'); // 改变主题
        // console.log('所有全局事件', KingfisherUI.getGlobalEvents()); // 获取所有全局事件
        // console.log('上下文', KingfisherUI.getContext()); // 获取上下文*/
        // KingfisherUI.addGlobalEventListener('/space_select_objects', (data) => {
        //   console.log('对象选中', data);
        // });

        setTimeout(() => {
          // KingfisherUI.updateAlarmList([{
          //   deviceId: "MJ001",
          //   deviceName: "报警",
          //   message: "设备告警"
          // }])
          // console.log(123)
          space3dManager.updateDevicesState([
            {
              deviceId: "2940",
              state: "Elevator stop",
            },
          ])
          space3dManager.refreshGeos();
        }, 1000);
      }
    };

    const sceneLoad = (e) => {
      console.log('场景加载', e);
      if(!web3d.value?.registerWeb3dListener)return
      web3d.value.registerWeb3dListener({
        onTap: (event) => {
          console.log('场景点击', event);
        },
        onLoad: (scene) => {
          console.log('场景下载完成', scene);
          console.log('场景镜头', web3d.getCameras());
          console.log('场景脚本', web3d.puzzleLogic);
          if (web3d.puzzleLogic) {
            console.log('事件列表', web3d.puzzleLogic.loadEvents());
          }
          console.log('API', web3d.puzzle);
        },
        onLoadingHide: (scene) => {
          console.log('隐藏加载动画', scene);
        },
        onRender: () => {
          //console.log('每帧渲染回调');
        },
        onEvent: (event) => {
          console.log('收到消息', event);
        },
      });
      if (mode.value === 'diagram3d') {
        doTest()
      }
    };

    const loaderHide = (e) => {
      console.log('场景加载完成', e);
    };

    const tap = (e) => {
      console.log('点击', e);
    };

    const render = (e) => {
      //console.log('render', e)
    };

    const handleEvent = (e) => {
      console.log('接受事件', e);
    };

    const pointMove = (e) => {
      console.log('点位移动', e);
    };

    const partPosition = ref({});

    const device1 = ref();
    const device2 = ref();
    const device3 = ref();
    const device4 = ref();
    const devices = ref();

    let deviceData = {
      deviceId: '71a053e88f4c295562a409816b1f9237',
      deviceData: 'temperature',
    };
    let deviceData1 = {
      deviceId: '71a053e88f4c295562a409816b1f9237',
      deviceData: 'temperature',
    };
    let deviceData2 = {
      deviceId: '82733841b1de884a613f1562291529cf',
      deviceData: ['temperature', 'humidity'],
    };
    let deviceData3 = {
      deviceId: 'f43eb9142f240916cb243383aaf009e9',
      deviceData: ['url'],
    };
    let deviceData4 = {
      deviceId: '82733841b1de884a613f1562291529cf',
      deviceData: 'temperature',
    };
    const cardProps1 = ref();
    const cardProps2 = ref();
    const switchProps = ref();
    const videoProps = ref();
    const cardPropsList = ref([]);

    let deviceObj = ref({ temperature: 0 });
    const doClick = () => {
      KingfisherUI.controlDevice(deviceObj, 'temperature', 100);
    };

    let deviceObjs = ref([]);

    const switchMode = (value) => {
      if (value === 'ui') {
        // 绑定设备到组件和响应对象
        KingfisherUI.createDeviceWidget('kfCard', {}, deviceData, device1, cardProps1);
        KingfisherUI.createDeviceWidget('kfCards', {}, deviceData2, device2, cardProps2);
        KingfisherUI.createDeviceWidget('kfSwitch', {}, deviceData, device3, switchProps);
        KingfisherUI.createDeviceWidget('kfVideo',
            { src: "" }, deviceData3, device4, videoProps);
        KingfisherUI.createDeviceWidget('kfCard', {}, [deviceData, deviceData1], devices, cardPropsList);
        KingfisherUI.createDeviceData(deviceData, deviceObj);
        KingfisherUI.createDeviceData([deviceData, deviceData2], deviceObjs);
      } else {
        // 取消绑定
        KingfisherUI.unregisterDeviceRef(cardProps1);
        KingfisherUI.unregisterDeviceRef(cardProps2);
        KingfisherUI.unregisterDeviceRef(switchProps);
        KingfisherUI.unregisterDeviceRef(videoProps);
        KingfisherUI.unregisterDeviceRef(cardPropsList);
        KingfisherUI.unregisterDeviceRef(deviceObj);
        KingfisherUI.unregisterDeviceRef(deviceObjs);
        KingfisherUI.updateAlarmList([{
          deviceId: "b3010df365ba6007e6c09a6434e51e4c",
          deviceName: "测试测试",
          message: "Test"
        }])

        setTimeout(() => {
          KingfisherUI.showAlarms(false, space3dProps)
        }, 10000)

        if (value === 'jsWeb3d') {
          setTimeout(() => {
            let web3d = new KingfisherUI.Web3d('idWeb3d', {
              sceneId: ['78035/56'],
            });
            web3d.registerWeb3dListener({
              onTap: (event) => {
                console.log('场景点击', event);
              },
              onLoad: (scene) => {
                console.log('场景下载完成', scene);
                console.log('场景镜头', web3d.getCameras());
                console.log('场景脚本', web3d.puzzleLogic);
                if (web3d.puzzleLogic) {
                  console.log('事件列表', web3d.puzzleLogic.loadEvents());
                }
                console.log('API', web3d.puzzle);
              },
              onLoadingHide: (scene) => {
                console.log('隐藏加载动画', scene);
              },
              onRender: () => {
                //console.log('每帧渲染回调');
              },
              onEvent: (event) => {
                console.log('收到消息', event);
              },
            });
          }, 50);
        } else if (value === 'jsDiagram3d') {
          setTimeout(() => {
            let web3d = new KingfisherUI.Web3d('idDiagram3d', {
              sceneId: ['78030/156.k3ds'],
            });
            web3d.registerWeb3dListener({
              onTap: (event) => {
                console.log('场景点击', event);
              },
              onLoad: (scene) => {
                console.log('场景下载完成', scene);
                console.log('场景镜头', web3d.getCameras());
                console.log('场景脚本', web3d.puzzleLogic);
                if (web3d.puzzleLogic) {
                  console.log('事件列表', web3d.puzzleLogic.loadEvents());
                }
                console.log('API', web3d.puzzle);
              },
              onLoadingHide: (scene) => {
                console.log('隐藏加载动画', scene);
              },
              onRender: () => {
                //console.log('每帧渲染回调');
              },
              onEvent: (event) => {
                console.log('收到消息', event);
              },
            });
          }, 50);
        } else if (value === 'jsSpace3d') {
          KingfisherUI.updateConfig({
            projectId: 8419,
          });
          setTimeout(() => {
            let web3d = new KingfisherUI.Web3d('idSpace3d', {
              buildingId: 'mVP3QbklHO5CDXrJBlB2q',
              floorId: '-FVVn6L_97x2bLlZQGMoA',
              partType: ['wall', 'window', 'door'],
            });
            web3d.registerWeb3dListener({
              onTap: (event) => {
                console.log('场景点击', event);
              },
              onLoad: (scene) => {
                console.log('场景下载完成', scene);
                console.log('场景镜头', web3d.getCameras());
                console.log('场景脚本', web3d.puzzleLogic);
                if (web3d.puzzleLogic) {
                  console.log('事件列表', web3d.puzzleLogic.loadEvents());
                }
                console.log('API', web3d.puzzle);
              },
              onLoadingHide: (scene) => {
                console.log('隐藏加载动画', scene);
              },
              onRender: () => {
                //console.log('每帧渲染回调');
              },
              onEvent: (event) => {
                console.log('收到消息', event);
              },
            });
          }, 50);
        }
      }


          // setTimeout(()=>{
          //   let space3dManager = KingfisherUI.getSpace3dManager(space3d);
          //   space3dManager.updateDevicesState([
          //     {
          //       deviceId: "2940",
          //       state: "Elevator stop",
          //     },
          //   ])
          //   space3dManager.refreshGeos();
          // },8000)
      mode.value = value;
    };

    const deviceCount = ref(0);

    onMounted(() => {
      switchMode('ui');
    });

    onUnmounted(() => {
      //取消监听
      let diagram3dManager = KingfisherUI.getDiagram3dManager(diagram3d);
      let widgetList = diagram3dManager.getDevicePartsBriefInfo(diagram3dManager.scene);
      //监听
      widgetList.map((part) => {
        diagram3dManager.removeEventListene(diagram3dManager.scene, part.partId, (e) => {
          console.log('取消监听', e, part)
        });
      })
      // 销毁时取消绑定
      KingfisherUI.unregisterDeviceRef(cardProps1);
      KingfisherUI.unregisterDeviceRef(cardProps2);
      KingfisherUI.unregisterDeviceRef(switchProps);
      KingfisherUI.unregisterDeviceRef(videoProps);
      KingfisherUI.unregisterDeviceRef(cardPropsList);
      KingfisherUI.unregisterDeviceRef(deviceObj);
      KingfisherUI.unregisterDeviceRef(deviceObjs);
    });

    const ready = ref(false);

    const cameraInfo = ref({
      src:''
      //src: "https://eba.msjnet.cn:9091/stream/live/6076/10001/playlist.m3u8?token=dXJsOk1TQ1A6Ly82MDc2L3N0cmVhbT9zdWJUeXBlPUdCX1QyODE4MSZvYmpJZD02MDc2JmRldkdCSUQ9MzQwMjAwMDAwMDEzMjAwMDAyMDc="
    });

    const video = ref(null);
    watch(video, () => {
      if (video.value) {
        video.value.updateData();
      }
    })

    return {
      video,
      cameraInfo,
      deviceCount,
      switchMode,
      ready,
      device1,
      device2,
      device3,
      device4,
      devices,
      selectedDevice,
      switchProps,
      cardProps1,
      cardProps2,
      videoProps,
      cardPropsList,
      web3dProps,
      diagram3dProps,
      space3dProps,
      deviceObj,
      deviceObjs,
      doClick,
      doTest,
      loaderHide,
      sceneLoad,
      tap,
      render,
      handleEvent,
      pointMove,
      endElement,
      web3d,
      diagram3d,
      space3d,
      mode,
      devicePoints,
      partPosition,
    };
  },
};
</script>

<style>
body {
  margin: 0;
  padding: 0;
  font-family: 'Microsoft Yahei';
  width: 100%;
  height: 100vh;
  overflow: hidden;
  background-color: black;
  color: white;
}

html {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  margin: 0;
  padding: 0;
}

#app {
  display: block;
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  font-family: 'Microsoft Yahei';
}

.toolbar {
  position: absolute;
  top: 20px;
  left: 0;
  width: 100%;
  padding: 5px;
  display: flex;
  align-items: center;
}

.action-button {
  border: 1px solid #7171ea;
  padding: 5px;
  margin-right: 5px;
  border-radius: 5px;
  min-width: 50px;
  background: transparent;
  color: white;
  cursor: pointer;
}

.action-button:hover {
  background: #7171ea;
}

.device-dot {
  position: absolute;
  width: 2px;
  height: 2px;
  background-color: #00b8ff;
  border-radius: 1px;
  border: 1px solid white;
  z-index: 9999;
}
</style>
