<template>
  <div ref="container" style="position: static">
    <div v-for="(dialog, index) in dialogSettings" :key="'dialog-line-' + index">
      <div v-for="(line, lineIndex) in dialog.lines" :key="'dialog-line-' + lineIndex">
        <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 === dialogSettings.length - 1 ? '#305792' : '#80808080',
                    position: 'absolute',
                    'pointer-events': 'none'
                  }"/>
      </div>
    </div>
    <kf-dialog :dialogVersion="dialogVersion" :list="dialogSettings" :props="bound"
               @selectObjects="selectObjects" @updateLine="updateLine"></kf-dialog>
  </div>
</template>

<script>
import {ref, watch, onUnmounted} from 'vue';
import kfDialog from '@/components/ui/widgets/kfDialog.vue';
import detailPanel from '@/components/ui/model/detailPanel';
import globalEventManager from '@/utils/globalEvent';
import {SysTopo} from '@/model/sysTopo';

export default {
  name: 'index',
  props: {
    panelSets: {
      type: Object,
      default: function() {
        return {};
      },
    },
    callBack: {
      type: Function,
    },
    sceneHunter: {
      type: Object,
      required: false,
    },
    weakKey: {
      type: Object,
      required: false,
    },
    bound: {
      type: Object,
      required: false,
    },
  },
  setup(props) {
    const panelSetList = ref([]);
    const container = ref(null);
    const sceneHunter = props.sceneHunter;
    let scene;
    let sysTopo;
    const detailSettings = {};
    const listeners = {};

    watch(
        () => props.panelSets,
        () => {
          let _panelSets = [];
          if (props.panelSets) {
            let keys = Object.keys(props.panelSets);
            for (let key of keys) {
              if (props.panelSets[key].enable) {
                _panelSets.push(props.panelSets[key]);
              }
            }
          }
          panelSetList.value = _panelSets;
          if (panelSetList.value) {
            panelSetList.value.map(panel => {
              if (panel.panels && panel.panels.length > 0 && // 取第一个面板设置
                  (panel.panels[0].displayType === 'click-model' ||
                      panel.panels.containerType === 'pop-ups')
              ) {
                if (props.weakKey) {
                  scene = webPageSceneMap.get(props.weakKey);
                } else {
                  scene = sceneHunter
                      ? window.Kc[
                      sceneHunter.fn(sceneHunter.widgetId, sceneHunter.pageName).props.props.id + '_scene'
                          ]
                      : window.scene;
                }
                if (panel.panels[0].enable) {
                  listeners[panel.targetId] = Kingfisher.Runtime.PartInterface.addEventListener(
                      scene,
                      panel.targetId,
                      function() {
                        if (panel.panels[0].displayType === 'click-model') {
                          if (!detailSettings[panel.targetId]) {
                            detailSettings[panel.targetId] = generateDetailSetting(panel);
                          }
                          if (detailSettings[panel.targetId]) {
                            detailPanel.showDialog(detailSettings[panel.targetId], null, null, scene);
                            detailPanel.updateLine(detailSettings[panel.targetId], null, scene, props.bound);
                          }
                        }
                      },
                      true,
                  );
                } else {
                  Kingfisher.Runtime.PartInterface.removeEventListener(scene, panel.targetId,
                      listeners[panel.targetId]);
                  detailPanel.hideDialog(detailSettings[panel.targetId]);
                }
              }
            });
          }
        },
        {deep: true},
    );

    const generateDetailSetting = (panel) => {
      sysTopo = SysTopo.getSysTopoInstance(scene);
      let deviceId = sysTopo.getDeviceIdByPartId(panel.targetId);
      let device = sysTopo.getDeviceById(deviceId);
      if(!device){
        return;
      }
      let type = device.deviceTypeCode;
      let model = device.model;
      if (model?.properties?.length) {
        let dialogData = {
          uuid: deviceId,
          target: 'diagram',
          name: panel.panels[0].label,
          model: device,
          type: type,
          fullScreen: false,
          deviceId: deviceId,
          panelEvent: model.panelEvent ? JSON.parse(model.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;
        detailPanel.updateDialogData(dialogData, device);
        dialogData.lines = [];
        const targetObj = scene.getNodeByID(panel.targetId);
        const boundingBox = targetObj.getHierarchyBoundingVectors();
        const x = (boundingBox.max.x + boundingBox.min.x) / 2;
        const y = (boundingBox.max.y + boundingBox.min.y) / 2;
        const z = (boundingBox.max.z + boundingBox.min.z) / 2;
        dialogData.lines.push(
            {pos3d: new Kingfisher.Vector3(x, y, z)});

        return dialogData;
      }
    };

    const events = {
      addEvent: function(documentMousemove) {
        container.value.parentNode.addEventListener(
            'mousemove',
            documentMousemove,
        );
      },
      removeEvent: function(documentMousemove) {
        container.value.parentNode.removeEventListener(
            'mousemove',
            documentMousemove,
        );
      },
    };

    const selectObjects = (objects) => {
      let _id = '';
      if (objects?.obj) {
        _id = objects.obj.deviceId || objects.obj.properties?.deviceId ||
            objects.obj.nanoId;
      }
      if (_id) {
        globalEventManager.issueEvent('/space_select_devices', {
          componentKey: 'detailDialog',
          data: [_id],
        });
      } else {
        if (objects) {
          if (!Array.isArray(objects)) {
            objects = [objects];
          }
        } else {
          objects = [];
        }

        objects = objects.map(x => typeof x === 'string' ? x : x.nanoId);
        globalEventManager.issueEvent('/space_select_objects', {
          componentKey: 'detailDialog',
          data: objects,
        });
      }
    };

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

    onUnmounted(() => {
      detailPanel.cleanDialogSettings();
    });

    return {
      updateLine,
      panelSetList,
      container,
      events,
      dialogVersion: detailPanel.dialogVision,
      dialogSettings: detailPanel.dialogSettings,
      selectObjects,
    };
  },
  components: {kfDialog},
};
</script>

<style scoped>
</style>
