<template>
  <div v-for="(item, index) in dialogDatas" v-show="dialogDatas?.length>0"
       :key="item.deviceId" :class="[dialogDatas.length - 1==index?'scoped-domainModel-active':'']"
       :style="getStyle(item)"
       ref="componentDom"
       class="scoped-domainModel"
       @mousedown.stop="startDrag($event, 1, item, index)"
  >
    <div class="w-100 h-100 kf-dialog-cons1">
      <div v-if="dialogDatas.length - 1===index && item.type === 'camera'">
        <div class="kf-resize-dot kf-dot-bottom-right"
             @mousedown="startDrag($event, 2, item, index, 'bl')"></div>
      </div>
      <div v-if="item?.type !== 'warnningInfo'" class="kf-domain1 kf-domain1-title">
        <div :title="item.name" class="kf-domain1-box1 ml8">{{ item?.name }}
        </div>
        <div class="kf-domain1-i mr4">
          <i v-if="item.type === 'camera'" :class="[item.fullScreen?'icon-suoxiao':'icon-quanping1']"
             class="iconfont  mr5"
             @mousedown.stop="switchDialogFullScreen(item,index,!item.fullScreen,$event)"></i>
          <i class="iconfont icon-close-fill" @mousedown="close(item,index)"></i>
        </div>
      </div>
      <freePanel v-if="item.type !== 'camera' && item.data"  :confData="item" :style="{
        'padding-bottom':item.type !== 'camera' && item.data?'16px':'',
      }"></freePanel>
      <div v-if="item.panelEvent" class="panel-evt-body flex-row-start-center">
        <span class="kf-p-label" :title="item.panelEvent.buttons[0].label">{{ item.panelEvent.buttons[0].label }}</span>
        <button class="panel-btn" @click="initFunc(item.panelEvent.buttons[0].action)">
          {{ item.panelEvent.buttons[0].label }}
        </button>
      </div>
      <div v-if="item.type === 'camera'" ref="videoBox" class="kf-domain1 kf-domain1-video-box">
        <kf-video-item :key="'video' + item.deviceId" :props="getVideo(item)"
                       style="border: 1px solid #FFFFFF1F"></kf-video-item>
      </div>
      <div v-if="item?.type === 'warnningInfo'" class="domainModel-warnning">
        <div class="kf-domain1 kf-domain1-title">
          <div :title="item?.currWarnningInfo.title" class="kf-domain1-box1 ml8">
            {{ item?.currWarnningInfo.deviceName }}
          </div>
          <div class="kf-domain1-i mr4">
            <i :class="[item.fullScreen?'icon-suoxiao':'icon-quanping1']" class="iconfont  mr5"
               @mousedown.stop="switchDialogFullScreen(item,index,!item.fullScreen,$event)"></i>
            <i class="iconfont icon-close-fill" @mousedown="close(item,index)"></i>
          </div>
        </div>
        <div class="domainModel-warnning-body">
          <div class="domainModel-warnning-item">
            <span class="warnning-item-label">{{ $t('DeviceAlarm') }}:</span>
            <span
                :class="['warnning-item-value','level-' + item?.currWarnningInfo.level]">{{
                $t('Level2')
              }}：{{ warnningLevel[item?.currWarnningInfo.level] }}</span>
          </div>
          <div class="domainModel-warnning-item">
            <span class="warnning-item-label">{{ $t('Name') }}:</span>
            <span
                class="warnning-item-value warnning-item-name">{{ item?.currWarnningInfo.deviceName }}</span>
          </div>
          <div class="domainModel-warnning-item">
            <span class="warnning-item-label">{{ $t('Type') }}:</span>
            <span
                :class="['level-' + item?.currWarnningInfo.level]">{{ item?.currWarnningInfo.message }}</span>
          </div>
          <div class="domainModel-warnning-item">
                        <span class="warnning-item-worker" @click="createWorkOrder(item.currWarnningInfo)">
                            <i class="iconfont icon-gongdan"></i>{{ $t('CreateSheet') }}</span>
          </div>
          <div class="domainModel-warnning-item-video">
            <span class="warnning-item-label">{{ $t('NearbyMonitoringScreen') }}</span>
            <div v-for="(aVideo,index) in alertVideos" :key="'warnning-video' + index" ref="warnningVideo"
                 class="warnning-item-video">
              <div class="warnning-item-video-header">
                <span class="video-header-title">{{ aVideo.name }}</span>
                <span class="video-header-status">{{ $t('Online2') }}</span>
              </div>
              <div class="warnning-item-video-body">
                <kf-video-item :key="'warnning-video-item' + index" :props="getVideo(aVideo)"
                               style="border: 1px solid #FFFFFF1F"></kf-video-item>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-if="item?.type === 'selectArea'" class="domainModel-area" >
        <div class="domainModel-area-body">
          <div class="scoped-web3dspace-search-items" style="overflow: hidden">
            <div v-for="(deviceItem,index) in item.deviceList"
                 :key="'search' + index"
                 class="scoped-web3dspace-header-toolBar-search-item">
              <div class="kf-toolbar-item4">
                <div :title="deviceItem.type" class="kf-toolbar-item1"> {{ deviceItem.type }}</div>
                <div :title="deviceItem.name" class="kf-toolbar-item2"> {{ deviceItem.name }}</div>
              </div>
              <div class="kf-toolbar-item3"><i class="iconfont icon-dingwei"
                                               @click="touchDialog(deviceItem)"></i>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

import freePanel from '@/components/uiWidget/freePanel/freePanel.vue';
import kfVideoItem from '@/components/ui/widgets/kfVideoItem.vue';
import {computed, getCurrentInstance, onMounted, ref, watch} from 'vue';
import pageModel from '@/components/ui/model/page';
//import {scaleData} from '@/components/ui/model/domNode';
import videoModel from '@/components/ui/model/video';
import {ElMessage} from 'element-plus';
import dataModel from '@/components/ui/model/data';
//import componentsDefine from '@/components/ui/model/componentsDefine';
//import eventManager from '@/components/ui/utils/event';

export default {
  name: 'kfDialog',
  components: {kfVideoItem, freePanel},
  props: {
    list: {
      type: Array,
      default: () => {
        return [];
      },
    },
    props: {
      type: Object,
      default: () => {},
    },
    alertVideos: {
      type: Array,
      default: () => {
        return [];
      },
    },
    dialogVersion: {
      type: Number,
      default: 0,
    },
  },
  emits: ['updateLine', 'selectObjects', 'switchDialogFullScreen'],
  setup(props, {emit}) {
    const {proxy} = getCurrentInstance();
    let componentDom = ref(null);
    let uiVersion = computed(() => {
      return props.dialogVersion;
    });
    const dialogDatas = computed(() => {
      return props.list;
    });
    watch(uiVersion, (newValue, oldValue) => {
      setTimeout(() => {
        if (componentDom.value && dialogDatas.value?.length > 0) {
          let pageName = dialogDatas.value[0].pageName;
          let componentMap = {};
          componentDom.value.map(comp => {
            if (comp?.props?.pageName) {
              pageName = comp.props.pageName;
            }
            if(comp?.props?.key){
              let _key = comp.props.key;
              if (comp.props?.deviceId) {
                _key = comp.props.key + comp.props.deviceId;
              }
              componentMap[_key] = comp;
            }
          });
          pageModel.loadedComponents[pageName] = pageModel.loadedComponents[pageName] || {};
          pageModel.loadedComponents[pageName] = Object.assign(pageModel.loadedComponents[pageName], componentMap); // 丢失组件问题
        }
      }, 0);
    });

    let dragging = 0;
    let draggingX = 0;
    let draggingY = 0;
    let draggingLeft = 0;
    let draggingTop = 0;
    let draggingWidth = 0;
    let draggingHeight = 0;
    const moveIndex = function(index) {
      if (index >= 0 && index >= dialogDatas.value.length) {
        return;
      }

      let oldDialog = dialogDatas.value[index];
      dialogDatas.value.splice(index, 1);
      dialogDatas.value.push(oldDialog);
      for (let i = 0; i < dialogDatas.value.length; i++) {
        dialogDatas.value[i].zIndex = 10 + i;
      }
    };
    const startDrag = function(event, mode, item, index) {
      if (index < 0 || index >= dialogDatas.value.length) {
        return;
      }
      event.stopPropagation();

      let dialogData = item;
      if (dialogData.fullScreen) {
        return;
      }
      if (dialogData?.panelContent && !dialogData?.panelContent?.page?.draggable) {
        return;
      }

      dragging = mode;
      moveIndex(index);

      draggingX = event.clientX;
      draggingY = event.clientY;
      draggingLeft = dialogData.left;
      draggingTop = dialogData.top;
      draggingWidth = dialogData.width;
      draggingHeight = dialogData.height;

      document.addEventListener('mousemove', dragMove);
      document.addEventListener('mouseup', stopDrag);
    };
    const dragMove = function(event) {
      if (dragging) {
        let dialogData =
            dialogDatas.value[dialogDatas.value.length - 1];
        if (dialogData) {
          let pps = props.props;
          if (pps?.x === undefined) {
            pps.x = 0;
          }
          if (pps?.y === undefined) {
            pps.y = 0;
          }
          let modules =
              pageModel.pageModulesBounds.value[pps.modules] ||
              pageModel.pageModulesBounds.value['main'];
          //let scale = scaleData.value.scale;
          let scale = 1;
          if (dragging === 1) {
            let left = draggingLeft + (event.clientX - draggingX) / scale;
            let top = draggingTop + (event.clientY - draggingY) / scale;
            left = Math.min(Math.max(left, -pps.x), modules.width - pps.x - dialogData.width);
            top = Math.min(Math.max(top, -pps.y), modules.height - pps.y - (dialogData.height || 40));
            dialogData.left = left;
            dialogData.top = top;
            dialogData.topStyle = dialogData.top + 'px';
            dialogData.leftStyle = dialogData.left + 'px';
          } else if (dragging === 2) {
            let width = Math.max(dialogData.minWidth, draggingWidth + (event.clientX - draggingX) / scale);
            let height = Math.max(dialogData.minHeight, draggingHeight + (event.clientY - draggingY) / scale);
            width = Math.min(width, modules.width - pps.x - dialogData.left);
            height = Math.min(height, modules.height - pps.y - dialogData.top);
            dialogData.width = width;
            dialogData.height = height;
            dialogData.widthStyle = dialogData.width + 'px';
            dialogData.heightStyle = dialogData.height ? dialogData.height + 'px' : 'auto';
          }
          emit('updateLine', dialogData);
        }
      }
    };
    const stopDrag = function(event) {
      if (dragging) {
        dragging = 0;
        document.removeEventListener('mousemove', dragMove);
        document.removeEventListener('mouseup', stopDrag);
      }
    };
    const close = function(item, index) {
      if (dialogDatas.value?.length > 0) {
        if (index === 0 && dialogDatas.value.length === 1) {
          emit('selectObjects');
        }
        dialogDatas.value.splice(index, 1);
      }
    };
    const switchDialogFullScreen = function(item, index, val, event) {

      event.stopPropagation();
      moveIndex(index);
      item.fullScreen = val;
      emit('switchDialogFullScreen', item, index, val, event);
    };
    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);
      }
      return;*/
    };
    const getVideo = function(property) {
      if (videoModel.videoList.value?.length <= 0) {
        return;
      }
      let _data = {
        deviceName: property.name || Kf.t('UnknownDevice'),
        data: {},
      };
      let _video = {};
      if (property?.model) {
        if (!property.videoData) {
          if (property?.model?.deviceId) {
            _video = videoModel.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 = videoModel.videoList.value.find((video) => {
            return video.deviceId === _deviceId;
          });
          if (_video && _video?.data) {
            _data.data = _video.data;
          }
        }
      }
      return _data;
    };

    const createWorkOrder = (alert) => {
      ElMessage.success(Kf.t('Workorder') + `-${alert.message}-` + Kf.t('CreateSuccessful'));
    };
    const touchDialog = function(item) {
      if (item.fullScreen) {
        return;
      }
      moveIndex(dialogDatas.value.length - 1);
      emit('selectObjects', item);
    };
    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 switchChange = (value, device, property) => {
      const props = {
        props: {deviceId: device.deviceId},
      };
      dataModel.doControl(
          props,
          device.model,
          null,
          value,
          property.name,
      );
    };

    const getStyle = function(item) {
      let style = {};
      style.width = !item.fullScreen && item.panelContent && item.panelContent.page && item.panelContent.page.width
          ? item.panelContent.page.width + 'px'
          :!item.fullScreen?'calc(' + item.widthStyle + ' - 2px)': 'calc(' + componentDom.value[0].parentNode.clientWidth + 'px - 2px)';
      style.height = !item.fullScreen && item.panelContent ? 'auto' : !item.fullScreen?'calc(' + item.heightStyle + ' - 2px)':'calc(' + componentDom.value[0].parentNode.clientHeight + 'px - 2px)';
      style.left =  !item.fullScreen || item.panelContent?item.leftStyle:0;
      style.top =  !item.fullScreen || item.panelContent?item.topStyle:0;
      style.zIndex = item.zIndex;
      style.background = item.panelContent && item.panelContent.page && item.panelContent.page.backgroundColor
          ? item.panelContent.page.backgroundColor
          : '#1c1c1c';
      if (item.panelContent && item.panelContent.page?.showModal) {
        style.height = 0;
        style.padding = 0;
        style.borderWidth = 0;
      }
      return style;
      //:style="'width:'+item.widthStyle+';left:'+item.leftStyle+ ';top:'+item.topStyle+';z-index:'+item.zIndex+';height:'+item.heightStyle"
    };
    const getBoxStyle = function(item) {
      let res = {
        width: item.props.width + 'px',
        height: item.props.height + 'px',
        left: item.props.x + 'px',
        top: item.props.y + 'px',
        zIndex: item.props.zIndex,
      };
      /*if((envModel.isPreview() || pageModel.control.value)  && item.props.pointerEvents!==undefined){
          res.pointerEvents =item.props.show?(!item.props.pointerEvents  ? 'auto' : 'none'): "auto";
      }
      if(envModel.isContent() || (envModel.isUI() && !pageModel.control.value)){
          res.pointerEvents='none'
      }*/
      res.pointerEvents = 'auto';
      return res;
    };
    /*const getEvent = function(item) {
      //return componentsDefine.getEventList(item);
    };
    let defaultHandler = ref({});
    const eventHandler = computed(() => {
      return eventManager.loadEventHandler(
          defaultHandler,
          undefined,
          props.props.pageName,
      );
    });*/

    const handleClick = function(value, event, index) {
      try {
        //eventHandler.value.click(value, event, value);
      } catch (e) {
        console.error(e);
      }
    };
    /*const refreshEvents = function(firstTime = false) {
      eventManager.registerEvent(proxy);
    };*/
    onMounted(() => {
      //refreshEvents();
    });
    return {
      dialogDatas,
      startDrag,
      close,
      switchDialogFullScreen,
      initFunc,
      getVideo,
      createWorkOrder,
      touchDialog,
      getValue,
      switchChange,
      getStyle,
      getBoxStyle,
      handleClick,
      componentDom,
    };
  },
};
</script>

<style lang="scss">
.scoped-domainModel {
  position: absolute;
  top: 20%;
  left: calc((100% - 400px) / 2);
  width: 400px;
  background: #1c1c1c;
  font-size: 13px;
  border-radius: 0;
  box-shadow: 0px 2px 4px 0px #00000033;
  border: 1px solid #ffffff1f;
  gap: 16px;
  /* padding: 0px 8px 0 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 {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #ffffff1f;
    padding: 0;
    border-top-right-radius: 5px;
    border-top-left-radius: 5px;

    .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;
    }
  }

  .ml8 {
    margin-left: 8px;
  }

  .mr4 {
    margin-right: 4px;
  }

  .domainModel-area {
    font-size: 13px;
    color: #eee;
    background-color: #1c1c1c;
    min-height: 300px;
    overflow-y: hidden;
    .domainModel-area-body::-webkit-scrollbar {
      width: 5px; /* 设置滚动条的宽度 */
    }

    .domainModel-area-body::-webkit-scrollbar-track {
      border-radius: 5px;
      background: rgba(255,255,255,0.1); /* 滚动条轨道的背景颜色 */
    }

    .domainModel-area-body::-webkit-scrollbar-thumb {
      border-radius: 5px;
      background: rgb(255,255,255,0.5); /* 滚动条实际可拖动部分的颜色 */
    }

    .domainModel-area-body::-webkit-scrollbar-thumb:hover {
      background: rgb(255,255,255,0.5); /* 滚动条实际可拖动部分的悬停颜色 */
    }
    &-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-domain1-dialogs {

  .kf-domain1-dialog-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #ffffff1f;
    padding: 0 4px 0 8px;
    height: 50px;
    width: 100%;
  }

  .kf-domain1-dialog-main {
    display: flex;
    width: 100%;
    min-height: calc(100% - 100px);
  }

  .kf-domain1-dialog-footer {
    height: 50px;
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    align-items: center;
    border-top: 1px solid #ffffff1f;
    padding: 0 4px 0 8px;
  }

}

.kf-custom-dialog-modal.el-overlay {
  overflow: hidden;

  .el-overlay-dialog {
    overflow: hidden;
  }
}

.el-dialog.kf-custom-dialog {
  border: 1px solid transparent;

  .el-dialog__header {
    padding: 0;
    background: inherit;
  }

  .kf-domain1-dialog-header {
    height: 50px;
  }

  .el-dialog__headerbtn {
    height: 50px;
    line-height: 50px;
  }

  .el-dialog__footer {
    padding: 0;
    background: inherit;
  }

  .el-dialog__body {
    padding: 0;
    background: inherit;
  }

}

.el-dialog.kf-custom-dialog.scoped-domainModel-active {
  border-color: #305792;
}

.pb16 {
  padding-bottom: 16px;
}

.w-100 {
  width: 100%;
}

.h-100 {
  height: 100%;
}

.kf-dialog-cons1 {
  //border-top-right-radius: 5px;
  //border-top-left-radius: 5px;
}

.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);
  }
}
</style>
