<template>
  <div class="monitor-container">
    <template v-for="(sysItem, sysIndex) in deviceProperty.monitorDataGroupArr" :key="sysIndex">
      <div
        :id="`compressorCss3D${sysIndex + 1}`"
        class="threejs-Object-CSS compressorCss3D-box"
        style="width: 100%; height: 100%; position: absolute; pointer-events: none; overflow: hidden; z-index: 1; top: 0px; left: 0px"
      >
      </div>
    </template>
    <div id="compressor3D" style="width: 100%; height: 100%; position: absolute; overflow: hidden"></div>
    <div v-for="(sysItem, sysIndex) in deviceProperty.monitorDataGroupArr" :key="sysIndex" style="position: absolute; z-index: -1">
      <div v-show="monitorDataGroupFlag == sysIndex + 1" :id="`nitrogenMonitorBox${sysIndex}`">
        <div v-for="(groupNum, index) in sysItem" :key="index" class="modal-monitor">
          <fourBorderBg :class="`kyj${groupNum}`" :id="`nitrogenMonitor${groupNum}`">
            <div class="title">{{ deviceProperty.modelMonitor[0].title + (index + 1) }} </div>
            <template v-for="(preMonitor, preMonitorIndex) in deviceProperty.modelMonitor[0].list" :key="preMonitorIndex">
              <div v-if="preMonitor.code !== 'signal'" class="monitor-item">
                <span class="monitor-title">{{ preMonitor.title }}:</span>
                <span class="monitor-val"
                  ><span class="val">{{
                    selectData[`${deviceProperty.modelMonitor[0].key}${groupNum}${preMonitor.code}`]
                      ? formatNum(selectData[`${deviceProperty.modelMonitor[0].key}${groupNum}${preMonitor.code}`])
                      : '-'
                  }}</span
                  ><span class="unit">{{ preMonitor.unit }}</span></span
                >
              </div>
              <div v-else class="signal-item">
                <div class="signal" v-for="(signal, childIndex) in preMonitor.child" :key="childIndex">
                  <span class="monitor-title">{{ signal.title }}</span>
                  <span
                    :class="{
                      'signal-round': true,
                      'signal-round-run': selectData[`${deviceProperty.modelMonitor[0].key}${groupNum}${preMonitor.code}`] == '0',
                      'signal-round-warning': selectData[`${deviceProperty.modelMonitor[0].key}${groupNum}${preMonitor.code}`] == '1',
                      'signal-round-gry':
                        selectData[`${deviceProperty.modelMonitor[0].key}${groupNum}${preMonitor.code}`] != '1' &&
                        selectData[`${deviceProperty.modelMonitor[0].key}${groupNum}${preMonitor.code}`] != '0',
                    }"
                  ></span>
                </div>
              </div>
            </template>
          </fourBorderBg>
          <fourBorderBg v-if="getShowModelMonitor(deviceProperty.modelMonitor[1], groupNum)" :class="`cqg${groupNum}`" :id="`cqgMonitor${groupNum}`">
            <div class="title">{{ deviceProperty.modelMonitor[1].title + (index + 1) }}</div>
            <template v-for="(cqgMonitor, cqgMonitorIndex) in deviceProperty.modelMonitor[1].list" :key="cqgMonitorIndex">
              <div v-if="cqgMonitor.code !== 'signal'" class="monitor-item">
                <span class="monitor-title">{{ cqgMonitor.title }}:</span>
                <span class="monitor-val"
                  ><span class="val">{{
                    selectData[`${deviceProperty.modelMonitor[1].key}${groupNum}${cqgMonitor.code}`]
                      ? formatNum(selectData[`${deviceProperty.modelMonitor[1].key}${groupNum}${cqgMonitor.code}`])
                      : '-'
                  }}</span
                  ><span class="unit">{{ cqgMonitor.unit }}</span></span
                >
              </div>
              <div v-else class="signal-item">
                <div class="signal" v-for="(signal, childIndex) in cqgMonitor.child" :key="childIndex">
                  <span class="monitor-title">{{ signal.title }}</span>
                  <span
                    :class="{
                      'signal-round': true,
                      'signal-round-run': selectData[`${deviceProperty.modelMonitor[0].key}${groupNum}${cqgMonitor.code}`] == '0',
                      'signal-round-warning': selectData[`${deviceProperty.modelMonitor[0].key}${groupNum}${cqgMonitor.code}`] == '1',
                      'signal-round-gry':
                        selectData[`${deviceProperty.modelMonitor[0].key}${groupNum}${cqgMonitor.code}`] != '1' &&
                        selectData[`${deviceProperty.modelMonitor[0].key}${groupNum}${cqgMonitor.code}`] != '0',
                    }"
                  ></span>
                </div>
              </div>
            </template>
          </fourBorderBg>
        </div>
      </div>
    </div>
    <div class="total-data">
      <div class="vent-flex-row">
        <div class="item" v-for="(data, index) in deviceProperty.totalData" :key="index"
          >{{ data.title + '(' + data.unit + ')' }}：<span class="val">{{
            selectData[data.code] ? formatNum(selectData[data.code]) : '-'
          }}</span></div
        >
      </div>
    </div>
    <div v-if="selectData['netStatus'] == 0" class="device-state">网络断开</div>
    <div class="nitrogen-home">
      <div class="lr left-box">
        <div class="left-container">
          <div class="monitor-box">
            <template v-for="(device, leftIndex) in deviceProperty.leftMonitor" :key="leftIndex">
              <ventBox1 :class="{ 'vent-margin-t-10': leftIndex > 0 }">
                <template #title>
                  <div>{{ device.title }}</div>
                </template>
                <template #container>
                  <template v-for="(deviceChild, deviceChildIndex) in device.children" :key="deviceChildIndex">
                    <div v-for="(deviceKey, deviceIndex) in deviceChild.key" :key="deviceIndex">
                      <div v-if="deviceChild.key.length > 1" class="parameter-title group-parameter-title"
                        ><SvgIcon class="icon" size="14" name="pulp-title" /><span>{{ deviceChild.childTitle[deviceIndex] }}</span></div
                      >
                      <div class="input-box">
                        <div v-for="(item, index) in deviceChild.list" class="input-item" :key="index">
                          <div
                            :class="{
                              'w-280px': item.type == 'sign' || item.type == 'warning',
                              title: item.type !== 'sign' && item.type !== 'warning',
                            }"
                            >{{ item.title }}：</div
                          >
                          <template v-if="item.type !== 'sign' && item.type !== 'warning'">
                            <div class="value">{{
                              selectData && selectData[deviceKey + item.code] ? formatNum(selectData[deviceKey + item.code], 1) : '-'
                            }}</div>
                          </template>
                          <template v-else>
                            <div class="value">
                              <span
                                :class="{
                                  'signal-round': true,
                                  'signal-round-run': item.type === 'sign' && selectData[deviceKey + item.code] == '1',
                                  'signal-round-gry': selectData[deviceKey + item.code] == '0' || !selectData[deviceKey + item.code],
                                  'signal-round-warning': item.type === 'warning' && selectData[deviceKey + item.code] == '1',
                                }"
                              ></span>
                            </div>
                          </template>
                        </div>
                      </div>
                    </div>
                  </template>
                </template>
              </ventBox1>
            </template>
          </div>
        </div>
      </div>
      <div class="lr right-box">
        <div class="item-box" :class="{ 'mt-50px': deviceProperty.totalData.length > 0 }">
          <ventBox1 v-for="(device, rightIndex) in deviceProperty.rightMonitor" :key="rightIndex" class="vent-margin-t-10">
            <template #title>
              <div>{{ device.title }}</div>
            </template>
            <template #container>
              <div>
                <template v-for="(deviceChild, deviceChildIndex) in device.children" :key="deviceChildIndex">
                  <div v-for="(deviceKey, deviceIndex) in deviceChild.key" :key="deviceIndex">
                    <div v-if="deviceChild.key.length > 1" class="parameter-title group-parameter-title"
                      ><SvgIcon class="icon" size="14" name="pulp-title" /><span>{{ deviceChild.childTitle[deviceIndex] }}</span></div
                    >
                    <div class="input-box">
                      <div v-for="(item, index) in deviceChild.list" class="input-item" :key="index">
                        <div
                          :class="{
                            'w-280px': item.type == 'sign' || item.type == 'warning',
                            title: item.type !== 'sign' && item.type !== 'warning',
                          }"
                          >{{ item.title }}：</div
                        >
                        <template v-if="item.type !== 'sign' && item.type !== 'warning'">
                          <div class="value">{{
                            selectData && selectData[deviceKey + item.code] ? formatNum(selectData[deviceKey + item.code], 1) : '-'
                          }}</div>
                        </template>
                        <template v-else>
                          <div class="value">
                            <span
                              :class="{
                                'signal-round': true,
                                'signal-round-run': item.type === 'sign' && selectData[deviceKey + item.code] == '1',
                                'signal-round-gry': selectData[deviceKey + item.code] == '0' || !selectData[deviceKey + item.code],
                                'signal-round-warning': item.type === 'warning' && selectData[deviceKey + item.code] == '1',
                              }"
                            ></span>
                          </div>
                        </template>
                      </div>
                    </div>
                  </div>
                </template>
              </div>
            </template>
          </ventBox1>
        </div>
      </div>
    </div>
    <div
      v-if="renderPlayer"
      ref="playerRef"
      class="player-box"
      :class="{ 'sw-player': sysOrgCode == 'sdmtjtswmk' || sysOrgCode == 'hnqymdktymk' }"
    ></div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, onUnmounted, reactive, defineProps, inject, onBeforeUnmount } from 'vue';
  import { devicePropertyType, propertyListType, getMonitorData } from '../nitrogen.data.1';
  import fourBorderBg from '../../../comment/components/fourBorderBg.vue';
  import { mountedThree, destroy, setModelType } from '../nitrogen.threejs';
  import { list } from '../nitrogen.api';
  import ventBox1 from '/@/components/vent/ventBox1.vue';
  import { formatNum } from '/@/utils/ventutil';
  import { useCamera } from '/@/hooks/system/useCamera';
  import { useGlobSetting } from '/@/hooks/setting';

  const props = defineProps({
    deviceId: {
      type: String,
      require: true,
    },
    deviceType: {
      type: String,
      require: true,
    },
  });
  const { sysOrgCode } = useGlobSetting();
  // const sysOrgCode = 'sdmtjtswmk';
  const loading = ref(false);
  const monitorDataGroup = ref<Number[]>([]);
  const monitorDataGroupFlag = ref(1);
  const playerRef = ref();
  const renderPlayer = ref(true);
  const deviceProperty = ref({
    leftMonitor: [] as devicePropertyType[],
    rightMonitor: [] as devicePropertyType[],
    modelMonitor: [] as devicePropertyType[],
    detailCtrl: [] as devicePropertyType[],
    monitorDataGroupArr: [],
    totalData: [] as propertyListType[],
  });
  deviceProperty.value = await getMonitorData(props.deviceType);

  // 监测数据
  // const selectData = reactive({});
  const selectData = ref<Object | []>({});
  const { getCamera, removeCamera } = useCamera();

  // https获取监测数据
  let timer: null | NodeJS.Timeout = null;
  async function getMonitor(flag?) {
    if (Object.prototype.toString.call(timer) === '[object Null]') {
      return new Promise(async (resolve) => {
        timer = await setTimeout(
          async () => {
            await getDataSource();
            if (timer) {
              timer = null;
            }
            resolve(null);
            await getMonitor(false);
          },
          flag ? 0 : 1000
        );
      });
    }
  }

  async function getDataSource() {
    const res = await list({ devicetype: 'forcFan', pagetype: 'normal' });
    let dataSource = res.msgTxt[0] && res.msgTxt[0].datalist ? res.msgTxt[0].datalist[0] : [];
    // dataSource = {
    //   msgType: null,
    //   deviceID: '1781605808973565954',
    //   strname: '压风机',
    //   strinstallpos: '压风机',
    //   fsectarea: 'null',
    //   stationname: '压风机',
    //   stationtype: 'redis',
    //   deviceType: 'forcFan_normal',
    //   typeName: '压风机',
    //   netStatus: 1,
    //   warnFlag: 0,
    //   warnLevel: 0,
    //   warnLevel_str: '正常',
    //   warnTime: null,
    //   readTime: '2024-04-23 08:23:49',
    //   warnDes: '',
    //   frontGateOpenCtrl: null,
    //   rearGateOpenCtrl: null,
    //   readData: {
    //     PRE3_CPR_CoolantTemp: '62.0',
    //     PRE1_MOT_PhaseATemp: '59.0',
    //     PRE3_MOT_PhaseCTemp: '56.02',
    //     PRE2_CPR_HeadTemp: '81.0',
    //     sign: '0',
    //     PRE1_CPR_UnLoadPre: '6.0',
    //     PRE3_CPR_ExhaustPre: '5.7',
    //     PRE1_CPR_LoadorUnload: '0',
    //     PRE2_MOT_PhaseATempAlarm: '0',
    //     PRE2_CPR_ExhaustTemp: '18.01',
    //     PRE1_MOT_StopFail: '0',
    //     PRE3_MOT_StopFail: '0',
    //     PRE1_HMIReset: '0',
    //     PRE2_HMIStop: '0',
    //     PRE1_MOT_Ready: '1',
    //     PRE2_CPR_LoadorUnload: '0',
    //     PRE3_MOT_PhaseBTemp: '66.0',
    //     Reset: '0',
    //     PRE1_CPR_ExhaustPre: '5.3',
    //     PRE3_FaultSignal: '0',
    //     PRE1_MOT_PhaseATempAlarm: '0',
    //     PRE2_MOT_PhaseBTempAlarm: '0',
    //     PRE3_MOT_PhaseCTempAlarm: '0',
    //     PRE2_HMIStart: '0',
    //     PRE1_MOT_StartFail: '0',
    //     PRE3_MOT_PhaseATemp: '66.0',
    //     PRE2_CPR_CoolantTemp: '53.0',
    //     PRE3_HostorLoc: '0',
    //     PRE1_FaultSignal: '0',
    //     PRE2_FaultSignal: '0',
    //     PRE3_MOT_RunReturn: '1',
    //     PRE1_HMIStart: '0',
    //     PRE1_MOT_TotalRunTime: '6313.0',
    //     'PRE1_MOT_Pha seBTempAlarm': '0',
    //     PRE1_CPR_LoadTime: '5184.0',
    //     PRE2_MOT_PhaseCTempAlarm: '0',
    //     PRE2_CPR_LoadTime: '3328.0',
    //     PRE1_CPR_HeadTemp: '73.0',
    //     PRE3_CPR_LoadTime: '5920.0',
    //     PRE2_MOT_StartFail: '0',
    //     PRE2_MOT_PhaseBTemp: '61.0',
    //     PRE2_HostorLoc: '0',
    //     PRE3_HMIStop: '0',
    //     PRE3_CPR_HeadTemp: '84.0',
    //     PRE2_MOT_TotalRunTime: '4272.0',
    //     PRE3_HMIReset: '0',
    //     PRE2_MOT_Ready: '1',
    //     PRE2_MOT_RunReturn: '1',
    //     PRE3_MOT_PhaseBTempAlarm: '0',
    //     PRE2_MOT_StopFail: '0',
    //     PRE3_CPR_UnLoadPre: '6.0',
    //     PRE2_CPR_ExhaustPre: '5.7',
    //     PRE3_CPR_ExhaustTemp: '18.09',
    //     PRE3_MOT_StartFail: '0',
    //     PRE3_MOT_TotalRunTime: '8474.0',
    //     PRE2_MOT_PhaseATemp: '60.0',
    //     PRE1_MOT_PhaseCTempAlarm: '0',
    //     PRE3_HMIStart: '0',
    //     PRE1_HMIStop: '0',
    //     PRE3_MOT_Ready: '0',
    //     PRE1_HostorLoc: '0',
    //     PRE1_CPR_LoadPre: '5.0',
    //     PRE1_MOT_RunReturn: '0',
    //     PRE2_MOT_CtrlMode: '0',
    //     PRE2_HMIReset: '0',
    //     PRE1_MOT_CtrlMode: '0',
    //     PRE3_CPR_LoadPre: '5.0',
    //     PRE2_CPR_LoadPre: '5.0',
    //     PRE3_MOT_CtrlMode: '0',
    //     PRE1_MOT_PhaseCTemp: '58.0',
    //     PRE3_CPR_LoadorUnload: '1',
    //     TotalOutPipePre: '5.85',
    //     PRE1_MOT_PhaseBTemp: '60.0',
    //     PRE2_MOT_PhaseCTemp: '55.02',
    //     PRE1_CPR_CoolantTemp: '55.0',
    //     PRE3_MOT_PhaseATempAlarm: '0',
    //     PRE2_CPR_UnLoadPre: '6.0',
    //     isRun: '-2',
    //     PRE1_CPR_ExhaustTemp: '16.12',
    //     TotalOutPipeFlow: '884.0',
    //   },
    //   readDataDes: null,
    //   summaryHour: [],
    //   summaryDay: [],
    //   history: [],
    //   dayhistory: [],
    //   totalInfo: null,
    //   sign: null,
    //   cameras: [],
    //   links: [],
    //   other1: null,
    //   other2: null,
    //   other3: null,
    //   remarkInfo: null,
    //   linkInfo: null,
    // };
    if (dataSource) {
      Object.assign(selectData.value, dataSource, dataSource.readData);
    }
    loading.value = false;
  }

  function setMonitorGroupNum(flag) {
    if (flag != monitorDataGroupFlag.value) monitorDataGroupFlag.value = flag;
    const monitorGroup = deviceProperty.value.monitorDataGroupArr[flag - 1];
    setModelType('compressor' + (flag - 1));
    monitorDataGroup.value = monitorGroup;
  }

  function handleOK() {}

  function handleCancel() {}

  // 判断是否应该在某套件（组别）下展示监测数据详情
  function getShowModelMonitor(config: devicePropertyType, groupNum: number) {
    if (config.hideInGroup) {
      return !config.hideInGroup.includes(groupNum);
    }
    return !!config.list.length;
  }

  onMounted(async () => {
    setTimeout(() => {
      mountedThree(deviceProperty.value.monitorDataGroupArr).then(async () => {
        setMonitorGroupNum(1);
        getMonitor(true).then(async () => {
          if (selectData.value && selectData.value['deviceID']) await getCamera(selectData.value['deviceID'], playerRef, renderPlayer);
        });
      });
    }, 0);
  });
  onBeforeUnmount(() => {
    removeCamera(playerRef);
  });
  onUnmounted(() => {
    destroy();
    if (timer) {
      clearTimeout(timer);
      timer = undefined;
    }
  });
</script>
<style lang="less" scoped>
  @import '/@/design/vent/modal.less';
  @import '../../comment/less/workFace.less';
  @ventSpace: zxm;
  .monitor-container {
    position: fixed;
    width: 100%;
  }
  .compressorCss3D-box {
    pointer-events: auto;
    .modal-monitor {
      position: absolute;
      left: 0px;
      top: 0px;
    }

    &:deep(.win) {
      margin: 0 !important;
      background: #00000044;
    }

    &:deep(.main) {
      .title {
        height: 34px;
        text-align: center;
        font-weight: 600;
        color: #7af5ff;
        // background-image: url('../../../assets/img/yfj/light.png');
        background-repeat: no-repeat;
        background-position-x: center;
        background-position-y: 100%;
        background-size: 80%;
        font-size: 16px;
      }

      .monitor-item {
        display: flex;
        flex-direction: row;
        width: auto;
        margin-bottom: 3px;
        .monitor-val {
          color: #ffb700;
          display: flex;
          width: auto;

          .val {
            width: 80px;
            font-size: 14px;
          }

          .unit {
            color: #ffffffbb;
            font-size: 14px;
          }
        }
      }

      .monitor-title {
        width: 100px;
        color: #7af5ff;
        font-weight: 400;
        font-size: 14px;
      }

      .signal-item {
        display: flex;
        justify-content: space-between;

        // margin-bottom: 5px;
        .signal-round {
          display: inline-block;
          width: 8px;
          height: 8px;
          border-radius: 50%;
          margin: 0 10px;
          position: relative;

          &::after {
            display: block;
            content: '';
            position: absolute;
            width: 12px;
            height: 12px;
            top: -2px;
            left: -2px;
            border-radius: 50%;
          }
        }

        .signal-round-gry {
          background-color: #858585;

          &::after {
            background-color: #85858544;
            box-shadow: 0 0 1px 1px #85858599;
          }
        }

        .signal-round-run {
          background-color: #67fc00;

          &::after {
            background-color: #67fc0044;
            box-shadow: 0 0 1px 1px #c6ff77;
          }
        }

        .signal-round-warning {
          background-color: #e9170b;

          &::after {
            background-color: #e9170b44;
            box-shadow: 0 0 1px 1px #e9170b;
          }
        }
      }
    }
  }
  .total-data {
    position: absolute;
    top: 40px;
    right: 100px;
    z-index: 999;
    color: #e4cd00;
    .item {
      width: 200px;
      margin-left: 30px;
      .val {
        color: #00d8ff;
      }
    }
  }
  .nitrogen-home {
    width: 100%;
    height: calc(100%);
    position: fixed;
    z-index: 0;
    height: calc(100%);
    display: flex;
    justify-content: space-between;
    position: relative;
    top: 20px;
    pointer-events: none;
    .lr {
      margin-top: 0 !important;
    }
    .left-box {
      width: 360px !important;
      direction: rtl;
      overflow-y: auto;
      overflow-x: hidden;
      // height: calc(100% - 60px);//lxh
      height: calc(100% - 100px);
      margin-top: 30px !important;

      .left-container {
        direction: ltr;
        :deep(.input-item .title) {
          width: 220px !important;
        }
      }
    }
    .right-box {
      width: 360px !important;
      overflow-y: auto;
      overflow-x: hidden;
      height: calc(100% - 70px); //lxh
      .environment-monitor {
        .item {
          flex: 1;
          margin: 0 5px;
          .title {
            color: #7ae5ff;
            text-align: center;
            margin-bottom: 2px;
          }
          .num {
            width: 100%;
            height: 30px;
            text-align: center;
            border-top: 2px solid #50c8fc;
            border-radius: 4px;
            background-image: linear-gradient(#2e4d5955, #3780b499, #2e465955);
          }
        }
      }
      .pool-box {
        width: 327px;
        height: 65px;
        padding: 0 5px;
        background: url('/@/assets/images/vent/pump1.png') no-repeat;
        background-size: cover;
        background-origin: content-box;
        margin-top: 2px;
        .num {
          color: aqua;
        }
        .center {
          padding-right: 5px;
        }
      }
    }
  }
  .device-state {
    width: 100%;
    position: absolute;
    top: 30px;
    color: #e90000;
    display: flex;
    justify-content: center;
    font-size: 20px;
  }

  .player-box {
    position: absolute;
    height: 100%;
    width: 100%;
    padding: 0 20px 0 20px;
    z-index: 9999;
    display: flex;
    align-items: end;
    bottom: 80px;
    pointer-events: none;
    :deep(#LivePlayerBox) {
      display: flex;
      justify-content: end;
    }
  }
  //**上湾视频样式 */
  .sw-player {
    right: 350px;
    bottom: 130px;
    display: flex;
    flex-direction: row;
  }
  .input-box {
    width: calc(100%);
    display: flex;
    flex-direction: row !important;
    flex-wrap: wrap !important;
    .input-item {
      width: calc(50% - 8px);
      padding: 0 2px;

      &:nth-child(2n) {
        margin-left: 4px;
      }
    }
  }
  .btn-group {
    width: 100%;
    position: fixed;
    display: flex;
    justify-content: end;
    right: 380px;
    top: 85px;
    pointer-events: auto;
    .btn-item {
      width: auto;
      text-align: center;
    }
  }
  .state-header {
    display: flex;
    color: #73e8fe;
    .header-item {
      width: 25%;
      text-align: center;
    }
  }
  .device-row {
    display: flex;
    margin-top: 10px;
    .state {
      width: 25%;
      text-align: center;
      font-size: 13px;
    }
  }

  :deep(.@{ventSpace}-tabs-tabpane-active) {
    overflow: auto;
  }
</style>
