<template>
  <div id="spaceDom" ref="container" :class="'space-container vivify ' + buttonClass" :style="cardStyle">

    <canvas ref="domCanvas" style="height: 100%;width: 100%" @load="eventHandler.load"
            @loadingHide="eventHandler.loadingHide" @render="eventHandler.render" @tap="eventHandler.tap" />

    <div v-if="!isShowFooter && props.showToolBar" style="position: absolute;bottom: 7px;right:16px"
         @click="isOpenFooter">
      <i class="iconfont icon-jiantou_liebiaoshouqi"></i>
    </div>

    <div v-for="(item, index) in dialogDatas" :id="'dialog-line-' + index" :key="'dialog-line-' + index">
      <div v-for="(line, index1) in item.lines" :key="'item-line-' + index1">
        <div v-if="line.show" :style="{
          width: line.width + 'px',
          height: '1px',
          left: line.x + 'px',
          top: line.y + 'px',
          rotate: line.rotate + 'deg',
          background: index === dialogDatas.length - 1 ? '#305792' : '#80808080',
          position: 'absolute',
          zIndex: '9',
          'pointer-events': 'none'
        }" />
      </div>
    </div>

    <div v-if="props.showToolBar" class="scoped-web3dspace-header">
      <div class="scoped-web3dspace-header-breadcrumbs">
        <i class="iconfont  icon-liti" style="display: inline-block;margin-left: 16px"></i>
        <div v-for="(breadcrumb, index) in breadcrumbs.filter(x => x)" :key="'scoped-space' + index"
             class="kf-space-title" style="margin-right: 18px" @click="spaceTools.clickBreadcrumb(breadcrumb, index)">
          <div v-if="index !== 0" class="kf-space-title1"> ></div>
          <div class="kf-space-title1">{{
              !index && customBuildName ? customBuildName : breadcrumb.name
            }}
          </div>
        </div>

      </div>
      <slot name="header"></slot>
      <div class="scoped-web3dspace-header-toolBar">
        <i :class="[currDropDownType==='warnningMsg'?'kf-header-i-active':'']"  title="警告列表" class="iconfont icon-ziyuanxhdpi"
           @click="setDataList('warnningMsg')"></i>
        <i :class="[props.isFullScreen?'icon-suoxiao':'icon-quanping1']" :title="[props.isFullScreen?'缩小':'放大']" class="iconfont icon-quanping1"
           @click="switchFullScreen(!props.isFullScreen)"></i>
        <i :class="[currDropDownType==='search'?'kf-header-i-active':'']" title="搜索设备" class="iconfont icon-jiansuo"
           @click="setDataList('search')">
        </i>
        <i :class="[currDropDownType==='modelType'?'kf-header-i-active':'']" title="组件列表"  class="iconfont icon-liebiao1"
           @click="setDataList('modelType')"></i>
        <i :class="[currDropDownType==='floor'?'kf-header-i-active':'']"  title="楼层列表" class="iconfont icon-caidanhezi"
           @click="setDataList('floor')"></i>
      </div>

      <div v-if="currDropDownType === 'warnningMsg'" class="scoped-web3dspace-header-toolBar-msg">
        <div class="scoped-web3dspace-msg-items">
          <div v-for="(msg, index) in alertMsgList" :key="'alertMsgList' + index"
               :class="['scoped-web3dspace-header-toolBar-msg-item', 'level-' + msg.level]">
            <div class="kf-toolbar-msg-info">
              <span :title="msg?.deviceName" class="msg-name">{{ msg?.deviceName ? msg.deviceName : '' }}</span>
              <span :class="['msg-message',]" :title="msg?.message">{{ msg?.message ? msg.message : '' }}</span>
            </div>
            <div :class="['kf-toolbar-msg-detail', 'level-' + msg.level]" :title="warnningLevel[msg.level]"
                 @click="selectWarnningMsg(msg)">
              {{ warnningLevel[msg.level] }}
            </div>
          </div>
        </div>
      </div>

      <div v-if="currDropDownType === 'floor' || currDropDownType === 'modelType'"
           class="scoped-web3dspace-header-toolBar-dropDown">
        <template v-for="(group,index) in datalist">
          <div v-if="group.show" :key="index" class="scoped-web3dspace-header-toolBar-dropDown-group"
               @click.stop.prevent="updateDataItem(group)">
            <div class="scoped-web3dspace-header-toolBar-dropDown-header">
              <div style="width: 52px">{{ group.label?group.label[local]:group.name }}</div>
              <el-checkbox v-model="group.active"></el-checkbox>
            </div>
            <div class="scoped-web3dspace-header-toolBar-dropDown-body" :style="group.active?'opacity:1':'opacity:0.4'">
              <template v-for="(item,index) in group.list">
                <div v-if="item.show" :key="'toolBar' + index"
                     class="scoped-web3dspace-header-toolBar-dropDown-item"
                     @click.stop.prevent="updateDataItem(item,group)">
                  <div class="scoped-check margin4">
                    <el-checkbox v-model="item.active" :disabled="!group.active"></el-checkbox>
                  </div>
                  <div class="margin4">
                    <span>{{ item.label?item.label[local]:item.name }}</span>
                  </div>
                </div>
              </template>
            </div>
          </div>
        </template>
      </div>
      <div v-if="currDropDownType === 'search'" class="scoped-web3dspace-header-toolBar-search">
        <div class="scoped-self-input">
          <el-input v-model="searchValue" :placeholder="$t('PleaseChoose')" clearable type="text"
                    @input="searchChange"></el-input>
          <!--                    <i class="iconfont icon-close-fill" @click="searchValue =''"></i>-->
        </div>
        <div class="scoped-web3dspace-search-items">
          <div v-for="(item, index) in searchResult" :key="'search' + index"
               class="scoped-web3dspace-header-toolBar-search-item">
            <div class="kf-toolbar-item4">
              <div :title="item.type" class="kf-toolbar-item1"> {{ item.type }}</div>
              <div :title="item.name" class="kf-toolbar-item2"> {{ item.name }}</div>
            </div>
            <div class="kf-toolbar-item3"><i class="iconfont icon-dingwei" @click="spaceTools.selectObjects(item)"></i>
            </div>
          </div>
        </div>
      </div>

    </div>
    <div v-if="isShowFooter && props.showToolBar" class="scoped-web3dspace-footer">
      <div class="scoped-web3dspace-footer-left">
        <div class='scoped-web3dspace-boolean-button'>
          <div :class="{ 'scoped-web3dspace-boolean-button-active': cameraPerspective }" :title="perspectiveMode[local]"
               class="kf-space-btn1" @click="switchCameraPerspective(true)">
            <i class="iconfont icon-toushitu"></i>
            <!--                        {{perspectiveMode[local]}}-->
          </div>
          <div :class="{ 'scoped-web3dspace-boolean-button-active': !cameraPerspective }" :title="topMode[local]"
               class="kf-space-btn1" @click="switchCameraPerspective(false)">
            <i class="iconfont icon-dingshitu"></i>
            <!--                        {{topMode[local]}}-->
          </div>
        </div>
        <div>
        </div>
      </div>
      <slot name="footer"></slot>
      <div class="scoped-web3dspace-footer-right">
        <div class="scoped-web3dspace-footer-right-item">
          <div class="scoped-web3dspace-footer-right-item-title margin4">
            {{ focusLabel[local] }}
          </div>
          <div :class="[openFocus ? 'scoped-web3dspace-footer-right-item-model-active' : '']"
               :title="openFocus ? $t('CloseFocus') : $t('TurnOnTheFocus')"
               class="scoped-web3dspace-footer-right-item-model margin4" @click="isOpenFocus(!openFocus)">
            <div class="kf-switch-box">
              <div v-show="!openFocus" class="kf-switch-con"></div>
            </div>
            <div class="kf-switch-box">
              <div v-show="openFocus" :class="['kf-switch-con', openFocus ? 'kf-switch-con-active' : '']"></div>
            </div>
          </div>
        </div>
        <div class="scoped-web3dspace-footer-right-item" @click.stop="reset">
          <i class="iconfont icon-shuaxin"></i>
        </div>
        <div class="scoped-web3dspace-footer-right-item" @click="isOpenFooter">
          <i v-if="isShowFooter" class="iconfont icon-jiantou_liebiaozhankai"></i>
        </div>
      </div>

    </div>


    <kf-dialog :alertVideos="alertVideos" :dialogVersion="dialogVersion" :list="dialogDatas" :props="props"
               @selectObjects="selectObjects" @switchDialogFullScreen="switchDialogFullScreen"
               @updateLine="updateLine"></kf-dialog>
  </div>
  <slot name="inner"></slot>
</template>
<script>
import {computed, getCurrentInstance, isRef, onMounted, onUnmounted, ref, watch} from 'vue';
import Const from '@/utils/const';
import Stats from 'stats.js';
import {isRestSceneModeFromScene, sceneMode} from '@/model/globalData';
import {copy, each, eachObject, isArray, isDefined, isObject, loopFactory} from '@/utils/tools';
import {initCamerasThumbnails, isRestCamerasThumbnailsFromScene} from '@/model/cameras';
import envModel from '@/model/env';
import oemManager from '@/utils/oem';
import ProjectService from '@/service/project';
import Axios from 'axios';
import styleManager from '@/components/ui/utils/style.vue';
import SpaceService from '@/service/space';
import SpaceTools from '@/components/ui/widgets/kfWeb3dSpaceImpl';
import pageModel from '../model/page';
import serviceModel, {psmInstancer} from '@/components/ui/model/service';
import {scaleData} from '@/components/ui/model/domNode';
import globalEventManager from '@/utils/globalEvent';
import kfVideoItem from '@/components/ui/widgets/kfVideoItem.vue';
import dataMappingService from '@/service/dataMapping';
import alertModel from '@/components/ui/model/alert';
import dataModel from '@/components/ui/model/data';
import freePanel from '@/components/uiWidget/freePanel/freePanel.vue';
import kfDialog from './kfDialog.vue';
import videoModel from '@/components/ui/model/video';
import {monitoringDialogData} from '@/components/ui/model/dialog';
import detailPanel from '@/components/ui/model/detailPanel';
import context from '@/components/ui/model/context';
import spaceThemeModel from '@/components/ui/model/spaceTheme';
import KingfisherService from "/src/utils/request.js";

export default {
  name: 'kfWeb3dSpace',
  components: {
    kfVideoItem, freePanel, kfDialog,
  },
  props: {
    props: {
      type: Object,
      default: () => {
        return {
          id: "web3dSpace" + new Date().getTime(),
        }
      }
    },
    eventScript: {
      type: String,
    },
  },
  emits: ['sceneLoad', 'loaderHide', 'render', 'tap'],
  setup(props, { emit }) {
    let local = window.Kf.locale.value.replace('-', '');
    // local = 'en'; // 暂时 马来demo项目
    const perspectiveMode = {
      zhCN: '透视图',
      en: 'Perspective view',
    };
    const topMode = {
      zhCN: '顶视图',
      en: 'Top view',
    };
    const focusLabel = {
      zhCN: ' 点击聚焦',
      en: 'Click focus',
    };

    let kingfisherService = new KingfisherService();
    let cardStyle = ref({});
    let buttonClass = ref('');
    let videoBox = ref(null);
    window.onresize = function () {
      // console.log("agag")
      if (!props.props.isFullScreen) {
        cardStyle.value.width = '100%';
        cardStyle.value.height = '100%';
        cardStyle.value.position = 'relative';
      } else {
        cardStyle.value.width = window.innerWidth + 'px';
        cardStyle.value.height = window.innerHeight + 'px';
        cardStyle.value.position = 'fixed ';
        cardStyle.value.top = 0;
        cardStyle.value.left = 0;
        cardStyle.value['z-index'] = 999;
      }
    };
    const switchFullScreen = function (val, isGlobal) {
      let isFullScreen = !props.props.isFullScreen;
      if (val != undefined) {
        isFullScreen = val;
      }
      if (!val) {
        cardStyle.value.width = '100%';
        cardStyle.value.height = '100%';
        cardStyle.value.position = 'relative';
      } else {
        cardStyle.value.width = window.innerWidth + 'px';
        cardStyle.value.height = window.innerHeight + 'px';
        cardStyle.value.position = 'fixed ';
        cardStyle.value.top = 0;
        cardStyle.value.left = 0;
        cardStyle.value['z-index'] = 999;
      }
      if (!isGlobal) {
        globalEventManager.issueEvent('/space_fullscreen', {
          componentKey: props.props.id,
          data: isFullScreen,
        });
      }
    };
    let isInitOK = false;

    let tempPosition = {
      x: props.props.x,
      y: props.props.y,
      width: props.props.width,
      height: props.props.height,
    };

    let localIsFullScreen = props.props.isFullScreen;
    let expectedLoadingTime = 0;
    let loadingTextTimer = null;
    let loadingTextIndex = 0;
    let stats = null;
    let loaded = false;
    let puzzle = null;
    let netMsgRouter = null;
    let handleVueEvent = null;
    let tapHandlers = [];
    let currSceneId = 0;
    let loadStartTime = 0;
    const domCanvas = ref();
    let defaultHandler = ref({
      load: () => {
        console.log('场景加载完成', currScene);
        emit('sceneLoad', {scene: currScene});
      },
      tap: (pointerInfo) => {
        console.log('触发点击', pointerInfo);
        emit('tap', {point: pointerInfo});
      },
      loadingHide: () => {
        console.log('隐藏加载界面', currScene);
        emit('loaderHide', {scene: currScene});
      },
      render: (engine, sceneManager) => {
        emit('render', {engine, sceneManager, scene: currScene});
      },
    });
    let container = ref(null);
    let currScene = null;
    let sceneManager = null;
    let floors = ref(props.props.floors ? props.props.floors : []);
    let isFullScreen = ref(
        props.props.isFullScreen ? props.props.isFullScreen : false,
    );
    let breadcrumbs = ref([]);
    let customBuildName = computed(() => props.props.customBuildName);
    let currDropDownType = ref('');
    let searchResult = ref([]);
    let domainModel = ref(null);
    let dialogDatas = detailPanel.dialogSettings;
    let dialogVersion = detailPanel.dialogVersion;
    let openFocus = ref(true);
    let cameraPerspective = ref(props.props.cameraViewMode);
    let selectedModel = ref({}); // current selected device model
    let isShowFooter = ref(true);
    let showAlarms = props.props.showAlarms == undefined ? true : props.props.showAlarms;

    let spaceTools = new SpaceTools(
        domainModel,
        pageModel.currProject.value.uuid,
        floors,
        detailPanel.onDeviceChange,
        searchResult,
        breadcrumbs,
        openFocus,
        cameraPerspective,
        props,
        selectedModel,
        isShowFooter,
        showAlarms
    );
    let datalist = ref([]);
    let searchValue = ref('');
    const eventCallbacks = {};
    //根据partType设置模型显示
    const contralModel=()=>{
      if(props.props.partType!==undefined && props.props.partType.length>0){
        spaceTools.typeList.map((item,i)=>{
          item.active=false;
          props.props.partType.map((part,index)=>{
            if(item.type == part){
              item.active = true;
            }
          })
        })
      }
    }
    contralModel();
    let currSelSpaceDeviceData = ref(null); // 当前选中的空间中设备模型绑定的 device data

    let dataVersion = ref(0);

    let themePath = '';
    let themeId = -1;
    const updateData = function () {
      dataVersion.value++;
    };

    const computeBindingData = computed(() => {
      if (dataVersion.value > 0) {
        // console.log(currSelSpaceDeviceData.value);
        // //  const props = {deviceId: currSelSpaceDeviceData.value.deviceId}
        // let newData = dataModel.getData(props.props, false, true);
        //     debugger
        // if(currSelSpaceDeviceData.value){
        // }
      }
    });

    const eventHandler = computed(() => defaultHandler.value);
    let containerStyle = ref({});
    const { proxy } = getCurrentInstance();
    const getHardwareScalingLevel = function (width, height) {
      const k = 2.5;
      const w = 1920 * k;
      const h = 1080 * k;
      if (width <= w && height <= h) {
        return 1 / window.devicePixelRatio;
      }
      if (width / height > w / h) {
        return width / w;
      } else {
        return height / h;
      }
    };
    const getCanvas = function () {
      window.Kc = window.Kc || {};
      return window.Kc[props.props.id + '_canvas'];
    };

    const getEngine = function () {
      window.Kc = window.Kc || {};
      return window.Kc[props.props.id + '_engine'];
    };
    const initLoader = function () {
      let canvas = getCanvas();
      let engine = getEngine();

      let loadingScreen = new (window.Kingfisher.Runtime.LoadingScreenV2 || window.Kingfisher.Runtime.LoadingScreen)(
          canvas);
      if (props.props.logo) {
        loadingScreen.customLogoSrc = props.props.logo;
        loadingScreen.style = 'custom';
        if (props.props.logoSize) {
          let size = props.props.logoSize.split(',');
          if (size.length === 2) {
            loadingScreen.logoSize = {
              width: size[0],
              height: size[1],
            };
          }
        }
        loadingScreen.hideMiniLogo = true;
      } else if (!oemManager.beSame('product', 'logo')) {
        loadingScreen.logoSrc = oemManager.getImage('product', 'logo', '3dc');
        loadingScreen.hideMiniLogo = true;
      }
      engine.loadingScreen = loadingScreen;
      loadingScreen.onHide = onLoaderHide;
    };
    const showLoadingText = function () {
      if (props.props.showPoem) {
        loadingTextIndex++;
        if (loadingTextIndex === lines.length * 5) {
          loadingTextIndex = 0;
        }
      }

      let engine = getEngine();
      if (engine != null && engine.loadingScreen != null) {
        let loadingTime = new Date().getTime() - loadStartTime;
        let percentage = (loadingTime / expectedLoadingTime).toFixed(2);
        if (percentage > 0.99) {
          percentage = 0.99;
        }
        if (engine.loadingScreen.updateProgress) {
          engine.loadingScreen.updateProgress(
              Math.floor(percentage * 100),
          );
        }
      }
    };

    const loadSceneById = function (sceneUrl, animation, loadListener, tapListener) {
      loadSceneFromUrl(sceneUrl, animation, loadListener, tapListener);
    };

    const createEngine = function () {
      let global = window.Kc || {};
      window.Kc = global;

      let canvas = domCanvas.value;
      if(canvas){
        canvas.oncontextmenu = function (e) {
          e.preventDefault();
          e.stopPropagation();
        };
        canvas.toBase64Image = () => {
          return new Promise((resolve, reject) => {
            if (currScene && sceneManager && sceneManager.rootScene.subScenes.length) {
              sceneManager.rootScene.subScenes[0].getScreenshot({ precision: 0.2 }, 'image/png', (res) => {
                resolve(res);
              });
            } else {
              resolve('');
            }
          });
        };
      }

      global[props.props.id + '_canvas'] = canvas;
      let engine = new window.Kingfisher.Engine(canvas, true);
      console.log('create engine.');
      engine.netMsgRouter = netMsgRouter;
      try {
        window.Kf.requireLib(engine);
      } catch (e) {
        console.log(e);
      }
      global[props.props.id + '_engine'] = engine;
      let scalingLevel = getHardwareScalingLevel(
          canvas.clientWidth,
          canvas.clientHeight,
      );
      engine.setHardwareScalingLevel(scalingLevel);

      function resizeHandler() {
        let scaling = getHardwareScalingLevel(
            canvas.clientWidth,
            canvas.clientHeight,
        );
        engine.setHardwareScalingLevel(scaling);
        engine.resize(canvas.clientWidth, canvas.clientHeight);
      }

      initLoader();
    };
    const initScene = function () {
      window.Kingfisher.sceneLoadedCallback = function (scene, parsedData) {
        setTimeout(function () {
          if (isRestSceneModeFromScene.value) {
            sceneMode.value = parsedData.sceneMode ? parsedData.sceneMode : 'scene3D';
            isRestSceneModeFromScene.value = false;
          }
        }, 1000);
        scene.k3dc = scene.k3dc ? scene.k3dc : { panels: {} };
        scene.k3dc.serialize = function () {
          const check = function (_loopData, targetData, store) {
            let loopData = _loopData;
            if (isObject(loopData)) {
              if (!isDefined(targetData)) {
                targetData = {};
              }
              eachObject(loopData, (item, i, key) => {
                if (isObject(item)) {
                  item = isRef(item) ? item.value : item;
                  targetData[key] = {};
                  store.push({
                    loopData: item,
                    targetData: targetData[key],
                  });
                } else if (isArray(item)) {
                  targetData[key] = [];
                  store.push({
                    loopData: item,
                    targetData: targetData[key],
                  });
                } else if (key !== 'serialize') {
                  targetData[key] = item;
                }
              });
            }
            if (isArray(loopData)) {
              if (!isDefined(targetData)) {
                targetData = [];
              }
              each(loopData, (item, i) => {
                if (isObject(item)) {
                  item = isRef(item) ? item.value : item;
                  targetData[i] = {};
                  store.push({
                    loopData: item,
                    targetData: targetData[i],
                  });
                } else if (isArray(item)) {
                  targetData[i] = [];
                  store.push({
                    loopData: item,
                    targetData: targetData[i],
                  });
                } else {
                  targetData[i] = item;
                }
              });
            }
          };
          let target = {};
          let loop = loopFactory([{ loopData: scene.k3dc, targetData: target }], function (data, store) {
                let { loopData, targetData } = data;
                if (isRef(loopData)) {
                  check(loopData.value, targetData, store);
                } else {
                  check(loopData, targetData, store);
                }
              },
          );
          loop.loopFn();
          return target;
        };
        scene.k3dc = ref(scene.k3dc).value;
        scene.k3dc.panels = scene.k3dc.panels ? scene.k3dc.panels : {};
        scene.k3dc.dataMaps = scene.k3dc.dataMaps || {};
        initCamerasThumbnails(parsedData.camerasThumbnail);

        spaceTools.setBuilding({
          projectId: props.props.projectId,
          buildingId: props.props.buildingId,
          name: props.props.buildingName,
        });

        spaceTools.setFloor({
          nanoId: props.props.floorId,
          name: props.props.floorName,
        });

        envModel.afterLoading();
      };
      if (props.props.disabled) {
        loaded = true;
        return;
      }
      window.Kingfisher.Runtime.Puzzle =
          window.Kingfisher.Runtime.PuzzleInterface;
      puzzle = window.Kingfisher.Runtime.Puzzle;
      if (props.props.msgSync) {
        try {
          netMsgRouter = new window.Kingfisher.Runtime.NetMsgRouter(props.props.group, props.props.role, findWsUrl());
          handleVueEvent = new window.Kingfisher.Runtime.HandleVueEvent(netMsgRouter, undefined, { context: proxy });
        } catch (e) {
          console.error(e);
        }
      }

      createEngine();
      sceneManager = window.Kc[props.props.id + '_sceneManager'] || new window.Kingfisher.SceneManager(getEngine());
      window.sceneManager = sceneManager;
      window.Kc[props.props.id + '_sceneManager'] = sceneManager;

      window.Kingfisher.Database.IDBStorageEnabled = true;
      let engine = getEngine();

      let theme = props.props.theme || spaceThemeModel.defaultSpaceTheme.value;

      if (theme) {
        console.log("采用主题", theme)
      }

      themePath = theme ? `${theme.projectId}/${theme.sceneId}.json` : '';
      themeId = theme ? theme.uuid : -1;
      loadSceneFromUrl(themePath);
      engine.runRenderLoop(() => {
        try {
          let currEngine = getEngine();
          if (currEngine && !currEngine.isDisposed) {
            try {
              if (eventHandler.value.render) {
                eventHandler.value.render(engine, sceneManager);
              }
            } catch (e) {
              console.error(e);
            }
            sceneManager.rootScene.render();
          }
        } catch (e) {
          console.error(e);
        }
        if (stats) {
          stats.update();
        }
      });
    };
    const initStats = function () {
      if (Const.develop && props.props.showFps) {
        stats = new Stats();
        stats.setMode(0);
        stats.domElement.style.position = 'absolute';
        stats.domElement.style.left = '5px';
        stats.domElement.style.top = '5px';
        domCanvas.value.parentNode.appendChild(stats.domElement);
      }
    };
    let setDataList = function(type) {
      if (currDropDownType.value === type) {
        currDropDownType.value = '';
        return;
      }
      currDropDownType.value = type;
      let data = [];
      if (type === 'floor') {
        datalist.value = floors.value;
        each(datalist.value, (_item) => {
          _item.active = _item.nanoId === props.props.floor.nanoId;
        });
      }
      if (type === 'modelType') {
        // datalist.value = spaceTools.typeList;
        datalist.value = spaceTools.typeGroups;
      }
      if (type === 'warnningMsg') {
        getAlertsData();
      }
    };

    let updateDataItem = function(item, group) {
      if (currDropDownType.value === 'floor') {
        each(datalist.value, (_item) => {
          _item.active = item === _item;
        });
        item.forUITempId = item.nanoId;
        props.props.floor = item;
        spaceTools.setFloor(item);
        pageModel.setPropValue(
            props.props,
            props.props.key,
            'floor',
            props.props.floor,
        );
      }
      if (currDropDownType.value === 'modelType') {
        if ((group && group.active === false)) {
          return;
        }
        //关闭全部选中
        // if (item?.list) {
        //   item.list.forEach(it => it.active = true);
        // }
        item.active = !item.active;
        spaceTools.updateRender();
      }
      console.log(item.list,datalist.value);
      datalist.value = [...datalist.value];
    };
    const onLoaderHide = function () {
      clearInterval(loadingTextTimer);
      localStorage.setItem(
          props.props.sceneUrl + '_loadingtime',
          new Date().getTime() - loadStartTime - 1000,
      );
      if (window.onSceneLoaded) {
        window.onSceneLoaded();
      }
      if (eventHandler.value.loadingHide) {
        eventHandler.value.loadingHide();
      }
    };

    const switchCameraPerspective = function (isPerspective) {
      globalEventManager.issueEvent('/space_camera_perspective', {
        componentKey: props.props.id,
        data: isPerspective,
      });
    };

    const registerContext = function (scene) {
      let register = scene && scene.puzzleLogic ? scene.puzzleLogic.registerContext : window.registerContext;
      if (register) {
        register('contextPath', '');
        register('context', Object.assign({
              registerContext: registerContext,
              puzzleParams: { SpaceService },
              project: pageModel.currProject.value,
            }, proxy),
        );

        register('canvas', getCanvas());
        register('axios', Axios);
        register('kingfisher', window.Kingfisher);
        register('scene', scene);
      }
    };
    const loadScene = function (id, scenePath, animation, onLoad, onTap) {
      currSceneId = id;
      tapHandlers = tapHandlers || {};
      tapHandlers[id] = onTap;

      let rootUrl = scenePath.substring(
          0,
          scenePath.lastIndexOf('/') + 1,
      );
      let sceneFile = scenePath.substring(scenePath.lastIndexOf('/') + 1);

      loadingTextTimer = setInterval(showLoadingText, 50);
      loadStartTime = new Date().getTime();

      let formatSceneFile = function (sceneFile) {
        if (sceneFile.includes('version')) {
          let version = sceneFile.split('=')[1];
          let id = sceneFile.split('.')[0];
          let suffix = sceneFile.split('.')[1].split('&')[0];
          return `${id}_${version}.${suffix}`;
        }
        return sceneFile;
      };
      sceneFile = formatSceneFile(sceneFile);
      if (currScene) {
        // window.Kc[props.props.id + "_sceneManager"].disposeAllScene();
      }
      let _themeId = themeId;
      puzzle.switchScene(
          currScene,
          sceneManager,
          id,
          rootUrl,
          sceneFile,
          1,
          1,
          (loadedScene, isFirstTime) => {
            isRestCamerasThumbnailsFromScene.value = true;
            isRestSceneModeFromScene.value = true;
            currScene = loadedScene.subScene;
            window.scene = currScene;
            window.needFireAfterLoad = true;
            window.Kc[props.props.id + '_scene'] = currScene;

            if (currScene) {
              if (props.props.showInspector && window.Kingfisher.Inspector && Const.develop) {
                window.Kingfisher.Inspector.Show(currScene, { overlay: true });
              }

              if (isFirstTime) {
                currScene.activeCamera.attachControl(
                    getCanvas(),
                    true,
                );
                currScene.activeCamera.panningSensibility = 0;
                currScene.onBeforeRenderObservable.add((data, state) => {
                      detailPanel.updateAllLine(currScene,
                          props.props.width ? props.props : domCanvas.value.getBoundingClientRect());
                      if (handleCameraChange.value) {
                        handleCameraChange.value();
                      }
                    },
                );
              }
              let loadLogic = (code) => {
                try {
                  window.onSceneLoaded = null;
                  //if(sceneType.value === 'k3dc'){
                  let logicStr = code.replace(
                      '__sceneId',
                      sceneFile,
                  );
                  //}

                  window.scene = currScene;
                  eval(logicStr);
                  currScene.puzzleLogic = window.puzzleLogic;
                  delete window.puzzleLogic;
                  delete window.scene;
                  registerContext(currScene);
                  // scene.puzzleLogic._pGlob.editState = fa;
                  // scene.puzzleLogic._pGlob.autoFocus = openFocus.value;
                  if (currScene.puzzleLogic.onSceneLoaded) {
                    currScene.puzzleLogic.onSceneLoaded(isFirstTime);
                  }
                    spaceTools.setScene(currScene);
                  //afterSceneLoaded();
                  if (onLoad) {
                    onLoad(currScene, isFirstTime);
                  }
                  // resolve();
                } catch (e) {
                  console.error([code]);
                  console.error(e);
                  // resolve();
                }
              };
              if (scene.logicJS !== undefined) {
                 loadLogic(scene.logicJS);
              } else {
                let logic = '';

                logic = window.Kingfisher.FileTools.GetAbsoluteUrl(
                    rootUrl + sceneFile.replace('.json', '_logic.js') + '&timestamp=' + new Date().getTime());

                kingfisherService.get(logic).then(res => {
                  if (res) {
                    try {
                      window.Kingfisher.Runtime.Puzzle = window.Kingfisher.Runtime.PuzzleInterface;
                      window.Kingfisher.Runtime.Part = window.Kingfisher.Runtime.PartInterface;
                      window.onSceneLoaded = null;
                      //if(sceneType.value === 'k3dc'){
                      let logicStr = res.replace(
                          '__sceneId',
                          sceneFile,
                      );
                      //}

                      window.scene = currScene;
                      eval(logicStr);

                      currScene.puzzleLogic = window.puzzleLogic;
                      delete window.puzzleLogic;
                      registerContext(currScene);
                      let _pGlob = currScene.puzzleLogic._pGlob;
                      if (!_pGlob.params) {
                        _pGlob.params = {};
                      }
                      _pGlob.componentKey = props.props.id;
                      if (currScene.puzzleLogic.onSceneLoaded) {
                        currScene.puzzleLogic.onSceneLoaded();
                      }
                      _pGlob.componentKey = props.props.id;
                      if (currScene.puzzleLogic.onSceneLoaded) {
                        currScene.puzzleLogic.onSceneLoaded();
                      }
                      if (_pGlob.callbacks.updateTheme) {
                        _pGlob.params.themeId = _themeId;
                        _pGlob.callbacks.updateTheme();
                      }
                      let value = Number(props.props.offsetX);
                      if (isNaN(value)) {
                        value = 0;
                      }
                      currScene.activeCamera.setProjectOffsetX(value * 0.01);
                      value = Number(props.props.offsetY);
                      if (isNaN(value)) {
                        value = 0;
                      }
                      currScene.activeCamera.setProjectOffsetY(value * 0.01);
                      value = Number(props.props.ratioScale);
                      if (!value || isNaN(value)) {
                        value = 100;
                      }
                      spaceTools.ratioScale = value * 0.01;
                      spaceTools.setScene(currScene);
                    } catch (e) {
                      console.error([res.data]);
                      console.error(e);
                    }

                    if (onLoad) {
                      onLoad(currScene, isFirstTime);
                    }
                  }
                }).catch(function () {
                  if (onLoad) {
                    onLoad(currScene, isFirstTime);
                  }
                });
              }

              isInitOK = true;
            }
          },
      );
    };

    let modelsMap = {
      light: 'lighting',
    };
    //let videoList = ref([]);
    const handleMessage = function (params) {
      if (params?.data?.address === '/space_fullscreen') {
        if (params.data?.data?.componentKey && params.data?.data?.componentKey !== props.props.id) {
          return;
        }
        pageModel.setPropValue(
            props.props,
            props.props.key,
            'isFullScreen',
            params.data.data.data !== undefined ? params.data.data.data : params.data.data === 'true',
        );
      }
      if (params?.data?.event?.name === 'SPACE_ON_ENTER') {
        if (params.data.event.componentKey && params.data.event.componentKey !== props.props.id) {
          return;
        }
        let geoModel = params.data.event.args.data;
        globalEventManager.issueEvent('/space_on_enter', {
          componentKey: props.props.id,
          data: [geoModel.properties || geoModel.nanoId],
          operateType: 'enterModel',
        });
      }
      if (params?.data?.event?.name === 'SPACE_ON_LEAVE') {
        if (params.data.event.componentKey && params.data.event.componentKey !== props.props.id) {
          return;
        }
        let geoModel = params.data.event.args.data;
        globalEventManager.issueEvent('/space_on_leave', {
          componentKey: props.props.id,
          data: [geoModel.properties || geoModel.nanoId],
          operateType: 'leaveModel',
        });
      }
      if (params?.data?.event?.name === 'SPACE_CLICK') {
        if (params.data.event.componentKey && params.data.event.componentKey !== props.props.id) {
          return;
        }
        let geoModel = params.data.event.args.data;
        if (eventHandler.value.tap) {
          eventHandler.value.tap(geoModel);
        }
        let type = geoModel.type;
        if (type === 'model') {
          globalEventManager.issueEvent('/space_select_devices', {
            componentKey: props.props.id,
            data: [geoModel.properties.deviceId || geoModel.nanoId],
            operateType: 'selectModel',
          });
        } else if (type === 'area') {
          globalEventManager.issueEvent('/space_select_area', {
            componentKey: props.props.id,
            data: [geoModel.nanoId],
            operateType: 'selectArea',
          });
        }
      }
    };

    const loadSceneFromUrl = function (sceneUrl, animation, loadListener, tapListener) {
      let p = sceneUrl.indexOf('/');
      let scenePart = [
        sceneUrl.substring(0, p),
        sceneUrl.substring(p + 1),
      ];
      const root = window.Kf.config.server + '/cloud/';
      ProjectService.getSceneById(scenePart[1]).then(function (res) {
        window.Kingfisher.FileTools.RegisterSchemes({
          'root://': root + 'api/repo/kf-scene/find-resources?path=' + scenePart[0],
          'lib://': root + '3dc/static/','resources://': root + 'resources/',
          'space://': root + 'api/repo/kf-space/find-file?path=' +  serviceModel.componentLib.value.uuid,
        });
        let url = 'root://' + scenePart[1];
        if (url.indexOf('.') < 0) {
          url += '.json';
        }

        loadScene(sceneUrl, url, '', function (scene) {
              try {
                if (window.puzzleDispose) {
                  window.puzzleDispose();
                }
                if (eventHandler.value.load) {
                  eventHandler.value.load(scene);
                }
                if (loadListener) {
                  loadListener();
                }
              } catch (e) {
                console.error(e);
              }
            },
            tapListener,
        );
      });
    };

    const resizeEngine = () => {
      getEngine() && getEngine().resize();
    };

    let modelCache = {};
    const getModel = (connId, type) => {
      if (!type) {
        return {};
      }
      if (modelCache[connId] && modelCache[connId][type]) {
        return modelCache[connId][type];
      }
      let serviceMappingConfig = psmInstancer.serviceMappingConfig;

      let mapType = modelsMap[type];
      if (serviceMappingConfig.has(connId)) {
        for (let model of serviceMappingConfig.get(connId).models) {
          if (model.name === type || model.name === mapType) {
            if (!modelCache[connId]) {
              modelCache[connId] = {};
            }
            modelCache[connId][type] = model;
            return model;
          }
        }
      }
    };

    const registerCallbacks = () => {
      //移入、移出
      eventCallbacks['/space_on_enter'] =
          globalEventManager.addCallback('/space_on_enter', (args) => {
            if ((args.data.componentKey && args.data.componentKey !== props.props.id) || !args.data.data[0].deviceId) {
              return;
            }
            let dialogData = {lines: '',
            device: dataModel.getDataSourceByDeviceId(args.data.data[0].deviceId)};
            let model = args.data.data[0];
            if (model) {
              let pos = model.position;
              if (pos) {
                dialogData.lines = [
                  {
                    pos3d: new Kingfisher.Vector3(pos[0] * 0.001, pos[1] * 0.001, pos[2] * 0.001),
                  }];
              }
            }
            if (handler3dObjectEnter.value) {
              handler3dObjectEnter.value({
                type: 'device',
                device: dialogData && dialogData.device?dialogData.device:selectedModel.value,
                info : dialogData
              })
            }
          });
eventCallbacks['/space_on_leave'] =
          globalEventManager.addCallback('/space_on_leave', (args) => {
            if ((args.data.componentKey && args.data.componentKey !== props.props.id) || !args.data.data[0].deviceId) {
              return;
            }
            let dialogData = {lines: '',
            device: dataModel.getDataSourceByDeviceId(args.data.data[0].deviceId)};
            if (handler3dObjectLeave.value) {
              handler3dObjectLeave.value({
                type: 'device',
                device: dialogData && dialogData.device?dialogData.device:selectedModel.value,
                info : dialogData
              })
            }
          });
      eventCallbacks['/space_select_devices'] =
          globalEventManager.addCallback('/space_select_devices', (args) => {
            if (args.data.componentKey && args.data.componentKey !== props.props.id) {
              return;
            }

            let sList = serviceModel.serviceList.value;
            if (!sList) {
              return;
            }
            let dialogData = {lines: ''};
            let geoModel = selectedModel.value;
            let pos = geoModel.properties.position;
            if (pos) {
              dialogData.lines = [
                {
                  pos3d: new Kingfisher.Vector3(pos[0] * 0.001, pos[1] * 0.001, pos[2] * 0.001),
                }];
            }
            if (args.data.operateType === 'warnningMsgClick' && selectedModel.value?.nanoId) {
              alertVideos.value = [];
              if (geoModel?.properties) {
                const param = {
                  position: geoModel.properties.position,
                  around: 5,
                  floorId: geoModel.floorId,
                  projectId: geoModel.projectId,
                  subType: 'camera',
                    };
                    dataMappingService.queryAroundDevices(param).then((result) => {
                      if (result?.length > 0) {
                        alertVideos.value = result;
                      } else {
                        alertVideos.value = [];
                      }
                    });
                    dialogData = {
                      uuid: selectedModel.value?.nanoId,
                      name: geoModel?.name,
                      type: 'warnningInfo',
                      currWarnningInfo: currWarnningInfo.value,
                      fullScreen: false,
                    };
                  }
                } else {
                  let selected = args.data.data || [];
                  for (let deviceId of selected) {
                    if (!deviceId) {
                      continue;
                    }
                    for (let device of sList) {
                      if (device.deviceId === deviceId) {
                        let _dialogContent = SpaceTools.findDialog(device.deviceTypeCode);
                        monitoringDialogData(deviceId, _dialogContent);
                        currSelSpaceDeviceData.value = device;
                        let oldDialog = detailPanel.findDialogByUuid(deviceId);
                        if (oldDialog) {
                          if (_dialogContent?.uuid) {
                            oldDialog.panelPageId = _dialogContent.uuid;
                            oldDialog.panelContent = _dialogContent.content;
                            oldDialog.pageName = _dialogContent.name;
                          }
                          detailPanel.moveDialog2Front(oldDialog);
                        } else {
                          let type = device.deviceTypeCode;
                          let model = getModel(device.connId, type);
                          // debugger
                          if (model?.properties?.length) {
                            let panelEvent = null;
                            try {
                              panelEvent = model.panelEvent ? JSON.parse(model.panelEvent) : '';
                            } catch (e) {
                            }
                            dialogData = {
                              uuid: deviceId,
                              target: 'space',
                              name: device.deviceName || model.label?.zhCN || model.name || '未知设备',
                              model: device,
                              data: copy(model.properties || []),
                              type: type,
                              fullScreen: false,
                              deviceId: deviceId,
                              panelEvent: panelEvent,
                              panelPageId: _dialogContent && _dialogContent.uuid ? _dialogContent.uuid : null,
                              panelContent: _dialogContent && _dialogContent.content ? _dialogContent.content : null,
                              pageName: _dialogContent.name ? _dialogContent.name : null,
                            };
                            dialogData.height = type === 'camera' ? 265 : 0;
                            dialogData.minHeight = type === 'camera' ? 265 : 40;
                            let deviceState = spaceTools.devicesState[deviceId];
                            for (let propData of dialogData.data) {
                              propData.value = deviceState && deviceState.data[propData.name] !== undefined
                                  ? deviceState.data[propData.name]
                                  : propData.defaultValue;
                              propData.time = new Date().getTime();
                            }
                            let geoList = spaceTools.geoDeviceIdMap[deviceId];
                            if (geoList && geoList.length > 1) {
                              dialogData.name += ' (' + geoList.length + ')';
                            }
                            if (geoList && geoList[0] && geoList[0].properties && geoList[0].properties.position) {
                              dialogData.lines = geoList.filter((x) => x.properties && x.properties.position).map((x) => {
                                let pos = x.properties.position;
                                return {pos3d: new Kingfisher.Vector3(pos[0] * 0.001, pos[1] * 0.001, pos[2] * 0.001)};
                              });
                              spaceTools.dialogData = dialogData;
                              detailPanel.updateLine(dialogData, null, currScene,
                                  props.props.width ? props.props : domCanvas.value.getBoundingClientRect());
                            }
                          }
                        }
                        if (handleDevicePopup.value(device)){
                          detailPanel.showDialog(dialogData, null, props.props.modules, currScene,props.props.dialogShowNumber,'device',container.value);
                        }
                        break;
                      }
                    }
                  }
                }
                if (handler3dObjectClick.value) {
                  handler3dObjectClick.value({
                    type: 'device',
                    device: dialogData && dialogData.device?dialogData.device:selectedModel.value,
                    info : dialogData
                  })
                }
                if (!handleDevicePopup.value){
                  detailPanel.showDialog(dialogData, null, props.props.modules, currScene,props.props.dialogShowNumber,'device',container.value);
                }

              },
          );
      // 空间 选中 区域
      eventCallbacks['/space_select_area'] =
          globalEventManager.addCallback(
              '/space_select_area',
              (args) => {
                if (args.data.componentKey && args.data.componentKey !== props.props.id) {
                  return;
                }
                let selected = args.data.data[0];
                let exist = detailPanel.moveDialog2Front(selected);
                if (!exist) {
                  let areaObject = spaceTools.getObjectByNanoId(selected);
                  if (!areaObject) {
                    console.error('cannot find area: ' + selected);
                    return;
                  }

                  let idList = (areaObject.childModelNanoIds || []).map(
                      x => spaceTools.getObjectByNanoId(x)?.properties?.deviceId || x);
                  let deviceList = [...new Set(idList)].map((id) => {
                    let dev = id
                        ? ((spaceTools.getObjectByDeviceId(id) || [])[0] || spaceTools.getObjectByNanoId(id))
                        : null;
                    if (!dev) {
                      return;
                    }
                    if (dev) {
                      const type = spaceTools.typeMap.get(`${dev.type}.${dev.subType}`)?.name || '未知';
                      return {
                        name: dev.name,
                        nanoId: dev.nanoId,
                        type,
                        obj: dev,
                      };
                    }
                  }).filter((x) => x);
                  // 区域内没有设备数据就 不 出现弹窗
                  if (deviceList.length < 1) {
                    return;
                  }
                  const dialogData = {
                    name: areaObject.name,
                    uuid: areaObject.nanoId,
                    type: 'selectArea',
                    deviceList: deviceList,
                    fullScreen: false,
                    lines: [
                      {
                        pos3d: new Kingfisher.Vector3(
                            areaObject.properties.textPos[0] *
                            0.001,
                            2.6,
                            areaObject.properties.textPos[1] *
                            0.001,
                        ),
                      }],
                  };

                  if (deviceList.length > 1) {
                    dialogData.name += ' (' + deviceList.length + ')';
                  }
                  if (handleAreaPopup.value(areaObject)) {
                    detailPanel.showDialog(dialogData, 300, props.props.modules, currScene,props.props.dialogShowNumber,'area',container.value);
                  }

                  if (handler3dObjectClick.value) {
                    handler3dObjectClick.value({
                      type: 'area',
                      area: areaObject,
                      info: dialogData
                    })
                  }

                }
              });
    };
   let init=() => {
     if (window.Kf && window.Kf.login && window.Kf.ssoReady && window.Kingfisher) {
       console.log('进入3D组件');
       if(!props.props.id){
         props.props.id="web3dSpace" + new Date().getTime();
       }
       initStats();
       let loadingTime = localStorage.getItem(
           props.props.id + '_loadingtime',
       );
       if (loadingTime == null) {
         loadingTime = 10 * 1000;
       }
       expectedLoadingTime = loadingTime;
       let initSceneID = 'initScene' + props.props.id;
       window[initSceneID] = () => {
         initScene();
         registerCallbacks();
         setTimeout(() => {
           delete window[initSceneID];
         }, 2000);
       };
       /*window.Kf.loadLib(
           'static/kingfisher.lib',
           'static/kingfisher.lic',
           initSceneID,
       );*/
       window[initSceneID]();
       containerStyle.value = styleManager.updateStyle(proxy);
       window.addEventListener('message', handleMessage);
       let observer = new ResizeObserver(function (entries) {
         for (let entry of entries) {
           if (entry.contentRect.width > 0) {
             let canvas = domCanvas.value;
             let containerDom = container.value;
             let scaling = getHardwareScalingLevel(canvas.clientWidth, canvas.clientHeight);
             if (getEngine()) {
               getEngine().setHardwareScalingLevel(scaling);
               getEngine().resize(containerDom.clientWidth, containerDom.clientHeight);
             }
           }
         }
       });
       observer.observe(container.value);
       videoModel.queryDevices();
     } else {
       window.setTimeout(init, 50);
     }
    };
    onMounted(() => {
      init();
      window.addEventListener('resize', resizeEngine);
      cardStyle.value = styleManager.updateStyle(proxy);
      if (!props.props.isFullScreen) {
        cardStyle.value.width = '100%';
        cardStyle.value.height = '100%';
        cardStyle.value.position = 'relative';
      }
      buttonClass.value = styleManager.updateClass(proxy);
    });
    const isOpenFocus = function (bool) {
      globalEventManager.issueEvent('/space_auto_focus', {
        componentKey: props.props.id,
        data: bool,
      });
    };

    const isOpenFooter = function () {
      // isShowFooter.value = !isShowFooter.value;
      globalEventManager.issueEvent('/space_footer', {
        componentKey: props.props.id,
        data: !isShowFooter.value,
      });
    };

    const searchChange = function (e) {
      spaceTools.search(searchValue.value);
      globalEventManager.issueEvent('/space_search', {
        componentKey: props.props.id,
        data: searchValue.value,
      });
    };

    const updateStateToGeo = (devices) => {
      spaceTools.updateStateToGeo(devices)
    }

    onUnmounted(() => {
      detailPanel.cleanDialogSettings();
      spaceTools.dispose();
      for (let key in eventCallbacks) {
        globalEventManager.removeCallbackById(eventCallbacks[key]);
      }

      window.removeEventListener('message', handleMessage);
      window.removeEventListener('resize', resizeEngine);
      //setWeb3dModelNull();
      try {
        console.log(Kf.t('DestructionOf3dComponents'));
        let engine = getEngine();
        if (engine) {
          if (loadingTextTimer) {
            clearInterval(loadingTextTimer);
          }
          if (engine.loadingScreen) {
            engine.loadingScreen.hideLoadingUI();
          }
          engine.dispose();
          console.log(Kf.t('TheEngineHasBeenDestroyed'));
          delete window.Kc[props.props.id + '_engine'];
          delete window.Kc[props.props.id + '_scene'];
          delete window.Kc[props.props.id + '_sceneManager'];
          delete window.Kc[props.props.id + '_container'];
        }

        console.log(Kf.t('TheComponentsHaveBeenDestroyed'));
      } catch (e) {
        console.error(e);
      }
    });

    watch(() => props.props.showAlarms, () => {
      if (spaceTools && props.props.showAlarms != undefined) {
        spaceTools.updateShowAlarms(props.props.showAlarms);
      }
    });

    pageModel.watchProps(props, watch, proxy, async (changes) => {
      if (!changes) {
        return;
      }
      containerStyle.value = styleManager.updateStyle(proxy);
      let theme = props.props.theme || spaceThemeModel.defaultSpaceTheme.value;
      let _themePath = theme ? `${theme.projectId}/${theme.sceneId}.json` : '';
      if (themePath !== _themePath) {
        themePath = _themePath;
        themeId = theme ? theme.uuid : -1;
        loadSceneFromUrl(_themePath);
      }
      if (styleManager.styleChanged('kfWeb3dSpace', changes)) {
        cardStyle.value = styleManager.updateStyle(proxy);
        cardStyle.value.width = '100%';
        cardStyle.value.height = '100%';
      }
      if (styleManager.classChanged('kfWeb3dSpace', changes)) {
        buttonClass.value = styleManager.updateClass(proxy);
      }
      let keysOfChanges = new Set(Object.keys(changes));
      if (keysOfChanges.has('sceneData')) {
        detailPanel.hideAllDialog();
      }

      if (keysOfChanges.has('buildingId')) {
        let buildings = await SpaceService.getBuildings(Kf.config.projectId);
        let building = buildings.find(x => {
          return x.nanoId === props.props.buildingId || x.name === props.props.building;
        });
        if (building) {
          let floors = await SpaceService.getFloors(Kf.config.projectId, building.nanoId);
          let floor = floors.find(x => {
            return x.nanoId === props.props.floorId || x.name === props.props.floor;
          });
          if (floor) {
            props.props.buildingName = building.name;
            props.props.building = building;
            spaceTools.setBuilding(building, true, () => {
              props.props.floorName = floor.name;
              props.props.floor = floor;
              spaceTools.setFloor(floor);
            });
          }
        }
      } else if (keysOfChanges.has('floorId')) {
        let floors = await SpaceService.getFloors(Kf.config.projectId, props.props.buildingId);
        let floor = floors.find(x => {
          return x.nanoId === props.props.floorId || x.name === props.props.floor;
        });
        if (floor) {
          props.props.floorName = floor.name;
          props.props.floor = floor;
          spaceTools.setFloor(floor);
        }
      }else if (keysOfChanges.has('floor')) {
        if (currDropDownType.value === 'floor') {
          each(datalist.value, (_item) => {
            _item.active =
                _item.nanoId === props.props.floor.nanoId;
          });
          datalist.value = [...datalist.value];
        }
        if(changes['floor']&& props.props.floorId && changes['floor'].nanoId != props.props.floorId){
          spaceTools.setFloor({
            nanoId: props.props.floorId,
            name: props.props.floorName,
          });
        }

      }else if (!keysOfChanges.has('sceneData')) {
        spaceTools.setBuilding({
          projectId: props.props.projectId,
          buildingId: props.props.buildingId,
          name: props.props.buildingName,
        });
      }


      if (currScene && currScene.activeCamera) {
        if (keysOfChanges.has('offsetX')) {
          let value = Number(props.props.offsetX);
          if (isNaN(value)) {
            value = 0;
          }
          currScene.activeCamera.setProjectOffsetX(value * 0.01);
        }
        if (keysOfChanges.has('offsetY')) {
          let value = Number(props.props.offsetY);
          if (isNaN(value)) {
            value = 0;
          }
          currScene.activeCamera.setProjectOffsetY(value * 0.01);
        }
        if (keysOfChanges.has('ratioScale')) {
          let value = Number(props.props.ratioScale);
          if (!value || isNaN(value)) {
            value = 100;
          }
          spaceTools.ratioScale = value * 0.01;
          spaceTools.resetCamera(cameraPerspective.value);
        }
        if (keysOfChanges.has('cameraViewMode')) {
          let value = !!props.props.cameraViewMode;
          cameraPerspective.value = value;
          spaceTools.resetCamera(cameraPerspective.value);
        }
      }
      if (keysOfChanges.has('partType')) {
        contralModel();
        spaceTools.updateRender();
      }
      if (keysOfChanges.has('isFullScreen')) {
        if (props.props.isFullScreen) {
          tempPosition = {
            x: props.props.x,
            y: props.props.y,
            width: props.props.width,
            height: props.props.height,
            zIndex: 'auto',
          };
          let rect =
              container.value.parentElement.parentElement.getBoundingClientRect();
          props.props.x = 0;
          props.props.y = 0;
          props.props.zIndex = 5;
          props.props.width = rect.width / scaleData.value.scale;
          props.props.height = rect.height / scaleData.value.scale;
        } else {
          pageModel.setPropValue(
              props.props,
              props.props.key,
              'height',
              tempPosition.height,
              null,
              null,
              false,
          );
          pageModel.setPropValue(
              props.props,
              props.props.key,
              'width',
              tempPosition.width,
              null,
              null,
              false,
          );
          pageModel.setPropValue(
              props.props,
              props.props.key,
              'zIndex',
              tempPosition.zIndex,
              null,
              null,
              false,
          );
          container.value.style.display = 'none';
          setTimeout(() => {
            pageModel.setPropValue(
                props.props,
                props.props.key,
                'x',
                tempPosition.x,
                null,
                null,
                false,
            );
            pageModel.setPropValue(
                props.props,
                props.props.key,
                'y',
                tempPosition.y,
                null,
                null,
                false,
            );
            container.value.style.display = 'block';
          }, 100);
        }
        localIsFullScreen = props.props.isFullScreen;
      }
    });

    const getValue = function (item) {
      let value = item.value;
      if (item?.enumItems?.length > 0) {
        let _item = item.enumItems.find((i) => {
          return value === i.value;
        });
        if (_item?.label?.zhCN) {
          value = _item.label.zhCN;
        }
      }
      if (item?.unit) {
        value = value + ' ' + item.unit;
      }
      // console.log(value);
      return value;
    };

    const touchDialog = function (item) {
      let dialogData = item;
      if (dialogData.fullScreen) {
        return;
      }
      detailPanel.moveDialog2Front(dialogData);
    };

    const queryDevices = () => {
      if (videoList.value.length > 0) {
        return;
      }
      let videos = [];
      if (serviceList.value) {
        videos = serviceList.value.filter((device) => {
          return device.deviceTypeCode === 'camera';
        });
        let index = 0;
        videos.map((video) => {
          if (!video.data?.url || video.data.url.indexOf('://') === -1) {
            //video.data.url = `rtsp://admin:Ventu2048SHA!@192.168.1.64:554/h264/ch1/main/av_stream`;
            video.data.group = '分组' + (index % 4);
            index++;
          }
          if (video.data.url && (video.data.url.startsWith('rtsp://') || video.data.url.startsWith('rtmp://'))) {
            video.data.server =
                pageModel.currProject.value.settings?.streamServer;
          }
        });
        videoList.value = videos;
        // debugger
      }
      // dataMappingService.getDataMapSourceInitList({projectId: pageModel.currProject.value.uuid,}).then((res) => {

      //     });
    };

    const getVideo = function (property) {
      if (videoList.value?.length <= 0) {
        return { deviceName: 'camera', data: { url: 'url' } };
      }
      let _data = {
        deviceName: property.name || '未知设备',
        data: {},
      };
      let _video = {};
      if (property?.model) {
        if (!property.videoData) {
          if (property?.model?.deviceId) {
            _video = videoList.value.find((video) => {
              return video.deviceId === property.model.deviceId;
            });
            if (_video) {
              _data.data = _video.data;
            }
          }
          property.videoData = _data;
        } else {
          _data = property.videoData;
        }
      } else {
        if (property.subType === 'camera' && !property?.model &&
            (property?.deviceId || property?.properties?.deviceId)) {
          let _deviceId = property?.deviceId || property?.properties?.deviceId;
          _video = videoList.value.find((video) => {
            return video.deviceId === _deviceId;
          });
          if (_video && _video?.data) {
            _data.data = _video.data;
          }
        }
      }
      return _data;
    };

    const switchChange = (value, device, property) => {
      const props = {
        props: { deviceId: device.deviceId },
      };
      dataModel.doControl(
          props,
          device.model,
          null,
          value,
          property.name,
      );
    };

    /**
     * 空间组件报警信息盒子
     */
    const alertMsgList = ref([]);
    let currWarnningInfo = ref({});
    const warnningLevel = [Kf.t('Normal2'), Kf.t('Emergency'), Kf.t('Serious'), Kf.t('Dangerous')];
    let alertVideos = ref([]);

    const getAlertsData = function () {
      if (alertModel.alerts.value.length > 0) {
        alertModel.alerts.value.length = 50; // 告警数据数量太多为了测试
        // 为了马来demo项目 告警信息改成英文
        alertMsgList.value = alertModel.alerts.value.filter((alert) => alert?.deviceName && alert?.message).map(it => {
          it.message = 'equipment alarm';
          return it;
        });
      }
    };

    const selectWarnningMsg = (msg) => {
      // console.log(msg, "设备告警信息");
      if (msg && msg?.deviceId) {
        currWarnningInfo.value = msg;
        globalEventManager.issueEvent('/locate_device', {
          deviceId: msg.deviceId,
          type: 'warnningMsgClick',
        });
      }
    };

    const reset = function () {
      // 重置按钮生效：执行恢复默认相机位置，关闭所有开启的弹窗，清理过滤设置
      currDropDownType.value = '';
      searchValue.value = '';
      searchResult.value = [];
      cameraPerspective.value = false;
      switchCameraPerspective(false);
      switchFullScreen(false);
      let needUpdate = false;
      for (let item of spaceTools.typeList) {
        if (!item.active) {
          item.active = true;
          needUpdate = true;
        }
      }
      if (needUpdate) {
        spaceTools.updateRender();
      }
      let selctedFloor =
          floors.value.find((item) => item.name === 'F1') ||
          floors.value[0];
      if (props.props.floor !== selctedFloor) {
        for (let item of floors.value) {
          (item.active == selctedFloor) === item;
        }
        selctedFloor.forUITempId = selctedFloor.nanoId;
        props.props.floor = selctedFloor;
        spaceTools.setFloor(selctedFloor);
        pageModel.setPropValue(
            props.props,
            props.props.key,
            'floor',
            props.props.floor,
        );
      }
      detailPanel.hideAllDialog();
      spaceTools.selectObjects();
      dialogVersion.value++;
    };
    const close = function (item, index) {
      if (dialogDatas.value?.length > 0) {
        if (index === 0 && dialogDatas.value.length === 1) {
          spaceTools.selectObjects();
        }
        detailPanel.hideDialog(item);
      }
    };

    const switchDialogFullScreen = function (item, index, val, event) {
      event.stopPropagation();
      detailPanel.moveDialog2Front(item);
      item.fullScreen = val;

      if (val) {
        let pps = props.props;
        let modules =
            pageModel.pageModulesBounds.value[pps.modules] ||
            pageModel.pageModulesBounds.value['main'];
        item.leftStyle = -pps.x + 'px';
        item.topStyle = -pps.y + 'px';
        item.widthStyle = modules.width + 'px';
        item.heightStyle = modules.height + 'px';
      } else {
        item.leftStyle = item.left + 'px';
        item.topStyle = item.top + 'px';
        item.widthStyle = item.width + 'px';
        item.heightStyle = item.height + 'px';
      }
    };

    const initFunc = (funStr) => {
      let func = new Function('return ' + funStr);
      let pageName = func()();
      const targetPage = pageModel.pageList.value.find(p => p.name === pageName);
      if (targetPage) {
        pageModel.loadPage(targetPage.uuid, null, null);
      }

    };

    const selectObjects = function (activeObj) {
      spaceTools.selectObjects(activeObj);
    };

    const updateLine = (dialog) => {
      detailPanel.updateLine(dialog, null, currScene, props.props);
    };

    const get3dObjectPosition = (pos) => {
      let camera = currScene.activeCamera;
      let view = camera._getViewMatrix();
      let project = camera.getProjectionMatrix();
      let vp = view.multiply(project);
      let v3 = Kingfisher.Vector3._Tmp;
      Kingfisher.Vector3.TransformCoordinatesToRef(
          pos,
          vp,
          v3,
      );
      let bound = domCanvas.value.getBoundingClientRect();
      let x1 = ((v3.x + 1) / 2) * bound.width;
      let y1 = ((-v3.y + 1) / 2) * bound.height;
      return { x: x1, y: y1 };
    };

    const handler3dObjectClick = ref((param) => {
     // console.log('三维对象点击', param);
    });
    const handler3dObjectEnter= ref((param) => {
      //console.log('三维对象移入', param);
    });
    const handler3dObjectLeave= ref((param) => {
      //console.log('三维对象移出', param);
    });
    const on3dObjectClick = (handler) => {
      handler3dObjectClick.value = handler;
    };
    const on3dObjectEnter = (handler) => {
      handler3dObjectEnter.value = handler;
    };
    const on3dObjectLeave = (handler) => {
      handler3dObjectLeave.value = handler;
    };

    const handleCameraChange = ref(null);

    const onCameraChanged = (handler) => {
      handleCameraChange.value = handler;
    };

    const handleDevicePopup = ref((device) => {
      return true;
    });

    const updateDevicePopupHandler = (handler) => {
      handleDevicePopup.value = handler;
    };

    const handleAreaPopup = ref((area) => {
      return true;
    });

    const updateAreaPopupHandler = (handler) => {
      handleAreaPopup.value = handler;
    };

    const focusToObject = async function (param) {
      let target;
      if (typeof param === 'string') { // 如果传递的是设备Id
        target = spaceTools.getObjectByDeviceId(param)?spaceTools.getObjectByDeviceId(param):spaceTools.getObjectByNanoId(param);
        if (target?.length > 0) {
          target = target[0];
        }
        if (!target) {
          target = serviceModel.serviceList.value.find(
              x => x.deviceName === param || x.sn === param || x.deviceId === param);

          if (target) {
            target = spaceTools.getObjectByDeviceId(target.deviceId);
            if (target?.length > 0) {
              target = target[0];
            }
          }
        }
      } else if (param.type && param.subType) { // 传递的是SpaceGeo对象
        target = {
          buildingId: param.buildingId,
          floorId: param.floorId,
          nanoId: param.nanoId,
        };
      } else {
        target = param;
      }

      if (target) {
        let diffBuilding = !context.context.building.value ||
            (target.buildingId ? target.buildingId !== context.context.building.value.buildingId : target.building !==
                context.context.building.value.name);
        let diffFloor = !context.context.floor.value ||
            (target.floorId ? target.floorId !== context.context.floor.value.nanoId : target.floor !==
                context.context.floor.value.name);
        if (diffBuilding) {
          let buildings = await SpaceService.getBuildings(Kf.config.projectId);
          let building = buildings.find(x => {
            return x.nanoId === target.buildingId || x.name === target.building;
          });
          if (building) {
            let floors = await SpaceService.getFloors(Kf.config.projectId, building.nanoId);
            let floor = floors.find(x => {
              return x.nanoId === target.floorId || x.name === target.floor;
            });
            if (floor) {
              spaceTools.changeFloorCallback = () => {
                setTimeout(() => {
                  spaceTools.changeFloorCallback = null;
                  locateObject(target);
                }, 200);
              };
              spaceTools.setBuilding(building, true, () => {
                spaceTools.setFloor(floor);
              });
            } else {
              console.warn('未找到目标楼层', target.floor || target.floorId);
            }
          } else {
            console.warn('未找到目标楼宇', target.building || target.buildingId);
          }
        } else if (diffFloor) {
          let floor = floors.value.find(x => {
            x.name === target.floor || x.nanoId === target.floorId;
          });
          if (floor) {
            spaceTools.changeFloorCallback = () => {
              setTimeout(() => {
                spaceTools.changeFloorCallback = null;
                locateObject(target);
              }, 100);
            };
            spaceTools.setFloor(floor);
          }
        } else {
          locateObject(target);
        }
      } else {
        console.warn('未找到目标对象');
      }
    };

    const locateObject = (target) => {
      if (!target.nanoId && target.deviceId) {
        target = spaceTools.getObjectByDeviceId(target.deviceId);
      }
      if (target) {
        globalEventManager.issueEvent('/space_select_devices', {
          componentKey: props.props.id,
          data: [target.nanoId],
          operateType: 'selectModel',
        });
      } else {
        console.warn('未找到目标对象', target);
      }
    };

    const getAllDeviceTypes = () => {
      return spaceTools.getAllDeviceTypes();
    }

    return {
      updateDevicesState: updateStateToGeo,
      getAllDeviceTypes,
      switchDialogFullScreen,
      close,
      dialogDatas,
      touchDialog,
      domCanvas,
      container,
      containerStyle,
      eventHandler,
      floors,
      breadcrumbs,
      customBuildName,
      spaceTools,
      currDropDownType,
      setDataList,
      updateDataItem,
      switchCameraPerspective,
      datalist,
      cameraPerspective,
      isOpenFocus,
      openFocus,
      isShowFooter,
      searchValue,
      isOpenFooter,
      searchChange,
      searchResult,
      domainModel,
      switchFullScreen,
      buttonClass,
      cardStyle,
      getValue,
      reset,
      alertMsgList,
      selectWarnningMsg,
      currWarnningInfo,
      warnningLevel,
      alertVideos,
      switchChange,
      updateData,
      computeBindingData,
      initFunc,
      perspectiveMode, topMode, local, focusLabel,
      updateLine, selectObjects, dialogVersion,
      get3dObjectPosition,
      on3dObjectClick,
      on3dObjectEnter,
      on3dObjectLeave,
      onCameraChanged,
      updateDevicePopupHandler,
      updateAreaPopupHandler,
      focusToObject,
    };
  },
  widgetConfig: {
    rank: 3,
    label: {
      zh: Kf.t('3dSpace'),
    },
    category: Kf.t('3d'),
    component: 'kfWeb3dSpace',
    display: true,
    version: 1,
    icon: 'icon-anniu',
    defaultSize: {
      x: 800,
      y: 600,
    },
    minSize: {
      width: 400,
      height: 400,
    },
    imgName: 'kfWeb3dSpace',
    state: {
      isAdd: false,
      isCondition: false,
    },
  },
};
</script>


<style lang="scss">
.scoped-web3dspace-boolean-button {
  width: 58px;
  border-radius: 6px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  border: 1px solid rgba(255, 255, 255, 0.05);
  padding: 2px;

  .kf-space-btn1 {
    height: 24px;
    line-height: 24px;
    text-align: center;
    flex: 1 1 50%;
    font-size: 12px;
    color: rgba(255, 255, 255, 0.8);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .scoped-web3dspace-boolean-button-active {
    border-radius: 4px;
    border: 1px solid rgba(255, 255, 255, 0.12);
    background: rgba(#305792, 0.5);
  }
}

.scoped-web3dspace-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  width: calc(100%);
  height: 32px;
  background-color: #282828;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 2px 8px;
  font-size: 12px;
  box-sizing: border-box;
  /*z-index:1;*/
  border-bottom: 1px solid rgba(255, 255, 255, 0.05);
  border-left: 1px solid rgba(255, 255, 255, 0.05);

  .scoped-web3dspace-footer-left {}

  .scoped-web3dspace-footer-right {
    height: 28px;
    line-height: 28px;
    color: #ffffff88;
    display: flex;

    .margin4 {
      margin: 0 4px;
    }

    .scoped-web3dspace-footer-right-item {
      display: flex;
      margin: 0 4px;
      align-items: center;

      /*> div {
  margin: 0 4px;
}*/
      i {
        width: 16px;
        height: 24px;
      }

      .scoped-web3dspace-footer-right-item-title {
        height: 28px;
        line-height: 28px;
      }

      .scoped-web3dspace-footer-right-item-model {
        width: 36px;
        height: 18px;
        border-radius: 12px;
        display: flex;
        box-sizing: border-box;
        align-items: center;
        background: rgba(255, 255, 255, 0.05);

        .kf-switch-box {
          flex: 1 1 50%;
          cursor: pointer;

          .kf-switch-con {
            width: 10px;
            height: 10px;
            border-radius: 6px;
            background: #868686;
            margin: 4px 6px;
            cursor: pointer;
          }

          .kf-switch-con-active {
            background: rgba(#305792, 0.6);
          }
        }
      }

      .scoped-web3dspace-footer-right-item-model-active {
        background: rgba(#305792, 0.5);

        .kf-switch-box {
          .kf-switch-con.kf-switch-con-active {
            background: #868686;
          }
        }
      }
    }
  }
}

.scoped-web3dspace-header {
  height: 32px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #282828;
  position: absolute;
  /* z-index:1;*/
  top: 0;
  left: 0;
  width: calc(100%);
  padding: 10px 0;
  border-top: 1px solid rgba(255, 255, 255, 0.05);
  border-left: 1px solid rgba(255, 255, 255, 0.05);

  .scoped-web3dspace-header-breadcrumbs {
    display: flex;
    height: 20px;
    line-height: 20px;
    font-size: 12px;
    color: rgba(255, 255, 255, 0.8);

    .kf-space-title {
      display: flex;

      .kf-space-title1 {
        margin: 0 1px;
        padding: 0 6px;

        pointer-events: auto;
      }
    }
  }

  .scoped-web3dspace-header-toolBar {
    display: flex;
    justify-content: space-between;
    padding-right: 20px;
    width: 143px;

    .iconfont {
      display: block;
      padding: 2px;
      pointer-events: auto;
      border-radius: 5px;
      border: 2px solid transparent;
      background: transparent;
      cursor: pointer;
      color: rgba(#fff, 0.8);
      pointer-events: inherit;
      font-size: 14px;

      &:hover {
        border-color: transparent;
        background: rgba(#fff, 0.06);
      }

      &:visited {
        border-color: rgba(#006ee1, 0.6);
        background: transparent;
      }

      &:active {
        border-color: transparent;
        background: rgba(#fff, 0.12);
      }
    }

    .kf-header-i-active {
      border-color: rgba(#006ee1, 0.6);
      background: transparent;
      height: 24px;
      width: 24px;
      text-align: center;
      line-height: 16px;

      &:hover {
        border-color: rgba(#006ee1, 0.6);
        background: transparent;
      }

      &:active {
        border-color: rgba(#006ee1, 0.6);
        background: transparent;
      }
    }
  }

  .scoped-web3dspace-header-toolBar-dropDown {
    min-height: 128px;
    //width: 100%;
    overflow: auto;
    position: absolute;
    top: 40px;
    //display: flex;
    padding: 6px 12px;
    background-color: #0e0e0e;
    flex-wrap: wrap;
    //flex-direction: row;
    z-index: 10;

    .scoped-web3dspace-header-toolBar-dropDown-group {
      display: flex;
      flex-direction: column;

      .scoped-web3dspace-header-toolBar-dropDown-header {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: stretch;
        div {
          margin-right:10px;
          font-size: 13px;
        }
      }

      .scoped-web3dspace-header-toolBar-dropDown-body {
        display: flex;
        justify-content: flex-start;
      }
    }
  }

  .scoped-web3dspace-header-toolBar-msg {
    position: absolute;
    right: 5px;
    top: 40px;
    width: 249px;
    height: 340px;
    font-size: 12px;
    z-index: 10;

    .scoped-web3dspace-msg-items {
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 100%;
      overflow-x: hidden;
      overflow-y: auto;
      border-radius: 3px;
      box-shadow: 0px 0px 3px 1px rgba(255, 255, 255, 0.1);
      background-color: rgba(20, 20, 20, 0.8);
      padding: 5px 0;

      .scoped-web3dspace-header-toolBar-msg-item {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        padding: 5px;

        .kf-toolbar-msg-info {
          width: 80%;
          display: flex;

          span {
            display: inline-block;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .msg-name {
            flex: 1;
            color: #ddd;
            border-left: 3px solid yellowgreen;
            padding-left: 5px;
            width: 100px;
            display: inline-block;
            white-space: nowrap;
            line-height: 18px;
            font-size: 12px;
            overflow: hidden;
            text-overflow: ellipsis;
            cursor: pointer;
          }

          .msg-message {
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            line-height: 18px;
          }
        }

        .kf-toolbar-msg-detail {
          width: 20%;
          display: flex;
          justify-content: center;
          align-items: center;
          cursor: pointer;
          // border: 1px solid rgba(255, 255, 255,0.2);
          // border-radius: 3px;
          padding: 1px 0;
          // color: #e4e402;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          /* &:hover {
               color: #fbfbfb;
           }*/
        }
      }
    }
  }
}

.scoped-web3dspace-header-toolBar-search {
  position: absolute;
  right: 0;
  top: 40px;
  z-index: 10;

  display: flex;
  width: 249px;
  height: 340px;
  min-height: 240px;
  max-height: 340px;
  padding-bottom: 8px;
  flex-direction: column;
  align-items: flex-start;

  border-radius: 4px;
  border: 1px solid #373737;
  background: linear-gradient(0deg,
      rgba(0, 0, 0, 0.6) 0%,
      rgba(0, 0, 0, 0.6) 100%,
      #161616);
  /* 右键菜单 */
  box-shadow: 0 4px 10px 0 rgba(0, 0, 0, 0.3);
  overflow-y: auto;
  overflow-x: hidden;

  .scoped-self-input {
    border-top: 1px solid #373737;
    border-bottom: 1px solid #373737;
    display: flex;
    height: 40px;

    .el-input {
      .el-input__wrapper {
        outline: none;
        box-shadow: none;
        padding: 0;
        padding-right: 8px;
        background: transparent;

        .el-input__inner {
          width: calc(100% - 40px);
          height: 40px;
          border: none;
          color: #ffffff;
          padding: 0 8px;
          outline: none;
          box-shadow: none;
        }
      }
    }

    .iconfont {
      width: 32px;
      height: 100%;
      display: flex;
      align-items: center;
      cursor: pointer;
      background: rgba(0, 0, 0, 0.4);
    }
  }

  .scoped-self-input {
    height: 32px;
    width: 100%;

    .el-input {
      .el-input__wrapper {
        outline: none;
        box-shadow: none;
        padding: 0;
        height: 32px;
        padding-right: 10px;

        .el-input__inner {
          width: calc(100% - 40px);
          height: 32px;
          border: none;
          color: #ffffff;
          padding: 0 8px;
          outline: none;
          box-shadow: none;
        }
      }
    }
  }
}

.scoped-web3dspace-search-items {
  width: 100%;
  height: calc(100% - 32px);
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  overflow-y: scroll;
  overflow-x: hidden;

  &::-webkit-scrollbar {
    width: 5px;
    height: 5px;
    background: transparent;
  }

  &::-webkit-scrollbar-corner,
  &::-webkit-scrollbar-thumb,
  &::-webkit-scrollbar-track {
    border-radius: 5px;
  }

  &::-webkit-scrollbar-corner,
  &::-webkit-scrollbar-track {
    box-shadow: inset 0 0 1px rgba(0, 0, 0, 0.3);
  }

  &::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 5px;
    background: rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    border: 1px solid rgba(194, 197, 209, 0.5);
    height: 15px;
  }

  .scoped-web3dspace-header-toolBar-search-item {
    width: 100%;
    height: 32px;
    display: flex;
    flex-direction: row;
    align-items: center;
    font-size: 14px;
    justify-content: space-between;
    cursor: pointer;

    .kf-toolbar-item4 {
      width: calc(100% - 30px);
      display: flex;
      font-size: 12px;
      flex-direction: row;
      justify-content: flex-start;
      align-items: center;
      flex-flow: inherit;

      .kf-toolbar-item1 {
        display: inline-block;
        height: 32px;
        width: 60px;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        line-height: 32px;
      }

      .kf-toolbar-item2 {
        display: inline-block;
        height: 32px;
        width: calc(100% - 60px);
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        line-height: 32px;
        font-size: 13px;
      }
    }

    .kf-toolbar-item3 {
      width: 30px;
    }
  }
}

.scoped-web3dspace-header-toolBar-search-item:nth-child(odd) {
  background: rgba(0, 0, 0, 0.4);
}

.scoped-web3dspace-header-toolBar-search-item:nth-child(even) {
  background: #1c1c1c;
}

.scoped-web3dspace-header-toolBar-search-item {
  font-size: 16px;
  line-height: 32px;
  display: flex;

  .kf-toolbar-item1 {
    color: #dedede88;
    // flex: 0 0 20%;
    margin-left: 8px;
  }

  .kf-toolbar-item2 {
    //flex: 0 0 60%;
    margin-left: 8px;
    overflow: hidden;
  }

  .kf-toolbar-item3 {
    cursor: pointer;
  }
}

.scoped-web3dspace-header-toolBar-search-item:hover {
  background-color: #305792;
}

.scoped-web3dspace-header-toolBar-dropDown-item {
  height: 32px;
  flex: 0 0 100px;
  display: flex;
  // padding: 4px;
  justify-content: flex-start;
  align-items: center;
  // border-radius: 6px;
  // border: 1px solid rgba(255, 255, 255, 0.12);
  background: #0c0c0c;
  // margin: 3px;
  pointer-events: inherit;

  .el-checkbox.is-disabled {
    opacity: 0.2;
  }

  .margin4 {
    margin: 0 4px;
    font-size: 13px;
  }

  .scoped-check {
    * {
      //pointer-events: none !important;
    }

    .el-checkbox {
      .el-checkbox__input {
        .el-checkbox__inner {
          z-index: auto;
        }
      }
    }
  }
}

.scoped-domainModel {
  position: absolute;
  top: 20%;
  left: calc((100% - 400px) / 2);
  width: 300px;
  background: #1c1c1c;
  font-size: 13px;
  border-radius: 0;
  box-shadow: 0px 2px 4px 0px #00000033;
  border: 1px solid #ffffff1f;
  gap: 16px;
  padding: 0;
  border-radius: 4px;
  /*  padding: 0px 8px 16px 8px;*/
  z-index: 9;

  .kf-domain1 {
    width: 100%;
    display: flex;
    height: 32px;
    line-height: 32px;
    font-size: 13px;

    .kf-domain1-box1 {
      width: 40%;
      overflow: hidden;
    }

    .kf-domain1-box2 {
      width: 60%;
    }

    .kf-domain2 {
      width: 100%;
      display: flex;
      padding: 4px 4px 4px 8px;
      gap: 4px;
      height: 32px;
      color: rgba(#fff, 0.9);

      .el-switch__core {
        //height: 28px;
      }
    }
  }

  .kf-domain1-title {
    border-top-right-radius: 5px;
    border-top-left-radius: 5px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #ffffff1f;

    /* padding: 0;*/
    .kf-domain1-i {
      cursor: pointer;

      i {
        cursor: pointer;
        color: #fff;

        &:hover {
          color: #305792;
        }
      }

      .icon-suoxiao {
        font-size: 14px;
      }

      &:hover {

        //color: #409eff;
        i {
          //color: #409eff;
        }
      }
    }

    .kf-domain1-box1 {
      width: calc(100% - 24px);
      display: inline-block;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
      line-height: 32px;
    }
  }

  .domainModel-area {
    font-size: 13px;
    color: #eee;
    background-color: #1c1c1c;
    min-height: 300px;
    overflow-y: hidden;

    &-body {
      padding: 5px;
      overflow-y: scroll;
      max-height: 400px;
    }
  }

  .domainModel-warnning {
    font-size: 13px;
    color: #eee;
    background-color: #1c1c1c;
    min-height: 500px;
    overflow-y: hidden;

    &-body {
      padding: 5px;
      overflow-y: scroll;
      max-height: 600px;

      span {
        display: inline-block;
      }

      .domainModel-warnning-item {
        display: flex;
        align-items: center;
        margin-bottom: 15px;

        .warnning-item-label {
          // min-width: 80px;
          padding-right: 20px;
          color: #aaa;
        }

        .warnning-item-value {
          // width: 80px;
        }

        .warnning-item-name {
          color: #bbb;
          font-weight: 700;
        }

        .warnning-item-worker {
          width: 120px;
          height: 30px;
          border-radius: 3px;
          background-color: rgba(#305792, 0.8);
          text-align: center;
          line-height: 30px;
          font-weight: 700;
          transition: all 0.3s linear;
          margin: 10px 0 0 0;
          cursor: pointer;

          &:hover {
            color: #fff;
            background-color: rgba(#305792, 1);
          }
        }
      }

      .domainModel-warnning-item-video {
        display: flex;
        flex-direction: column;
        color: #bbb;
        gap: 10px;
        padding-bottom: 20px;

        .warnning-item-label {
          font-weight: 700;
          margin-bottom: 10px;
        }

        .warnning-item-video {
          width: 100%;
          // height: 300px;
          border: 1px solid #333;
          border-radius: 5px;
          padding: 5px;

          .warnning-item-video-header {
            display: flex;
            padding: 5px 0;

            span {
              display: inline-block;
            }

            .video-header-title {
              height: 25px;
              line-height: 25px;
            }

            .video-header-status {
              padding: 2px 5px;
              color: rgb(1, 176, 1);
              margin-left: 20px;
              background-color: rgba(72, 106, 3, 0.2);
              border-radius: 3px;
              text-align: center;
            }
          }

          .warnning-item-video-body {
            width: 100%;
            min-height: 220px;
            border-radius: 5px;
            background-color: #000;
          }
        }
      }
    }
  }

  .level-0 {
    color: #00ff00;
  }

  .level-1 {
    color: #ffff00;
  }

  .level-2 {
    color: #ffa500;
  }

  .level-3 {
    color: #ff0000;
  }

  .kf-domain1-video-box {
    height: calc(100% - 30px);
  }
}

.scoped-domainModel-active {
  border-color: #305792;
}

.kf-resize-dot {
  width: 6px;
  height: 6px;
  background: #305792;
  position: absolute;
  /* i{
      color: rgba(255, 255, 255, 0.5);
      transform: rotate(-45deg);
      display: inline-block;
  }*/
}

.kf-dot-top-left {
  left: -3px;
  top: -3px;
  cursor: nw-resize;
}

.kf-dot-top-right {
  right: -3px;
  top: -3px;
  cursor: ne-resize;
}

.kf-dot-bottom-left {
  left: -3px;
  bottom: -3px;
  cursor: ne-resize;
}

.kf-dot-bottom-right {
  right: -3px;
  bottom: -3px;
  cursor: nw-resize;
}

.panel-evt-body {
  width: 100%;
  display: flex;
  margin-top: 10px;
  padding: 0px 8px;

  span {
    color: #aaa;
    display: flex;
    align-items: center;
    width: 100px;
  }

  .panel-btn {
    width: calc(100% - 100px);
    line-height: 30px;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    color: rgba(122, 206, 128, 0.8);
  }
}
.space-container:focus-visible{
  outline: none;
}
.panel-btn {
  height: 28px;
  border: none;
  background-color: rgba(122, 206, 128, 0.5);
  border-radius: 3px;
  font-size: 12px;
  transition: all 0.3s linear;

  &:hover {
    cursor: pointer;
    background-color: rgba(122, 206, 128, 0.65);
  }
}
</style>
