<template>
  <div class="bg" style="width: 100%; height: 100%; display: flex; justify-content: center; align-items: center; overflow: hidden">
    <a-spin :spinning="loading" />
    <div
      id="main3DCSS"
      class="threejs-Object-CSS"
      v-show="!loading"
      style="width: 100%; height: 100%; position: absolute; pointer-events: none; overflow: hidden; z-index: 1; top: 0"
    >
      <div style="position: relative">
        <div class="elementTag" id="inputBox">
          <div class="elementContent elementContent-r" v-if="selectData.DataPa && backMonitorIsShow">
            <!-- <div class="element-item"><span class="data-title">风机气压(Pa)：</span><span>{{ selectData.DataPa ? selectData.DataPa : '-' }}</span></div> -->
            <div class="element-item"
              ><span class="data-title">风机负压(Pa)：</span><span>{{ selectData.Fan2FanPre ? selectData.Fan2FanPre : '-' }}</span></div
            >
            <div class="element-item"
              ><span class="data-title">风机风量(m³/s)：</span><span>{{ selectData.Fan2m3 ? selectData.Fan2m3 : '-' }}</span></div
            >
          </div>
        </div>
        <div class="elementTag" id="inputBox1">
          <div class="elementContent elementContent-r" v-if="selectData.DataPa && frontMonitorIsShow">
            <!-- <div class="element-item"><span class="data-title">风机全压(Pa)：</span><span>{{ selectData.DataPa ? selectData.DataPa : '-' }}</span></div> -->
            <div class="element-item"
              ><span class="data-title">风机负压(Pa)：</span><span>{{ selectData.Fan1FanPre ? selectData.Fan1FanPre : '-' }}</span></div
            >
            <div class="element-item"
              ><span class="data-title">风机风量(m³/s)：</span><span>{{ selectData.Fan1m3 ? selectData.Fan1m3 : '-' }}</span></div
            >
          </div>
        </div>
        <div v-if="globalConfig?.simulatedPassword" class="elementTag" id="fbm">
          <div class="elementContent elementContent-r fbm-box">
            <div class="fbm-video">
              <LivePlayer id="main-player2" ref="player2" :videoUrl="flvURL2()" muted live />
              <div class="vent-flex-row-between vent-margin-t-20">
                <span class="data-title">风门开启状态：</span>
                <template v-if="selectData['ExplosionVentOpen'] == 1 && selectData['ExplosionVentClose'] == 0">
                  <span class="data-title"><span class="signal-round signal-round-blue vent-margin-r-8"></span>开启</span>
                </template>
                <template v-else-if="selectData['ExplosionVentOpen'] == 0 && selectData['ExplosionVentClose'] == 1">
                  <span class="data-title"><span class="signal-round signal-round-gry vent-margin-r-8"></span>关闭</span>
                </template>
                <template v-else>
                  <div class="vent-margin-l-10"
                    ><span class="signal-round signal-round-warning vent-margin-r-8"></span>防爆门正在运行 或 数据异常</div
                  >
                </template>
              </div>
              <div class="vent-flex-row-between vent-margin-t-10">
                <span class="data-title">反风锁紧状态：</span>
                <template
                  v-if="
                    selectData['Lock1Open'] == 1 && selectData['Lock1Close'] == 0 && selectData['Lock2Open'] == 1 && selectData['Lock2Close'] == '0'
                  "
                >
                  <span class="data-title"><span class="signal-round signal-round-blue vent-margin-r-8"></span>锁1开</span>
                  <span class="data-title"><span class="signal-round signal-round-blue vent-margin-r-8"></span>锁2开</span>
                </template>
                <template
                  v-else-if="
                    selectData['Lock1Open'] == '0' && selectData['Lock1Close'] == 1 && selectData['Lock2Open'] == '0' && selectData['Lock2Close'] == 1
                  "
                >
                  <span class="data-title"><span class="signal-round signal-round-gry vent-margin-r-8"></span>锁1关</span>
                  <span class="data-title"><span class="signal-round signal-round-gry vent-margin-r-8"></span>锁2关</span>
                </template>
                <template v-else>
                  <div class="vent-margin-l-10"
                    ><span class="signal-round signal-round-warning vent-margin-r-8"></span>反风锁紧正在运行 或 数据异常</div
                  >
                </template>
              </div>
            </div>
            <div class="fbm-data">
              <div class="element-item"
                ><span class="data-title">井口负压(kPa)：</span><span>{{ selectData.DataPa ? selectData.DataPa : '-' }}</span></div
              >
              <div class="element-item"
                ><span class="data-title">井口正压(kPa)：</span><span>{{ selectData.DataPa ? selectData.DataPa : '-' }}</span></div
              >
              <div class="element-item"
                ><span class="data-title">井口温度(℃)：</span><span>{{ selectData.DataPa ? selectData.DataPa : '-' }}</span></div
              >
              <div class="element-item"
                ><span class="data-title">甲烷浓度(%)：</span><span>{{ selectData.Fan1Negative ? selectData.Fan1Negative : '-' }}</span></div
              >
              <div class="element-item"
                ><span class="data-title">CO浓度(%)：</span><span>{{ selectData.Fan1m3 ? selectData.Fan1m3 : '-' }}</span></div
              >
              <div class="vent-flex-row-between">
                <span class="data-title">操作方式：</span>
                <span class="data-title"><span class="signal-round signal-round-blue vent-margin-r-8"></span>远程</span>
                <span class="data-title"><span class="signal-round signal-round-gry vent-margin-r-8"></span>就地</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div id="main3D" style="width: 100%; height: 100%; position: absolute; overflow: hidden"> </div>
    <FanEchrats id="fan-echarts" :chartData="selectData" style="position: absolute; z-index: -1" />
  </div>

  <div class="scene-box" style="z-index: 999">
    <div class="title-text" style="position: absolute; z-index: 9999; width: 100%; text-align: center">{{
      selectData.supplyAirAddr || selectData.strinstallpos || selectData.stationname
    }}</div>
    <div class="top-box control-group" v-if="globalConfig?.simulatedPassword">
      <div class="button-box" v-for="(item, index) in modalTypeArr.centerBtnArr" :key="index" @click="showModal(item)">{{ item.value }}</div>
      <!-- <div class="button-box" v-for="(item, index) in modalTypeArr.centerBtnArr" :key="index" @click="showModal(item)">{{ item.value }}</div> -->
    </div>
    <div class="data-show-box">
      <div class="data-item">
        <div class="item-header">设备监测</div>
        <div class="item-container">
          <div class="tab">
            <div class="tab-item" :class="{ 'tab-item-active-r': dataMonitorRowIndex == 0 }" @click="selectDevice('dataMonitorRowIndex', 0)"
              >1#风机</div
            >
            <div class="tab-item" :class="{ 'tab-item-active-r': dataMonitorRowIndex == 1 }" @click="selectDevice('dataMonitorRowIndex', 1)"
              >2#风机</div
            >
          </div>
          <div class="container-group container-group-l">
            <template v-if="deviceType">
              <div class="container-item" v-for="(data, index) in leftColumns" :key="index">
                <div class="item-icon">
                  <SvgIcon class="icon-style" size="18" name="temperature" />
                </div>
                <div class="item-name">{{ data.title }}</div>
                <div v-if="data.dataIndex.startsWith('Fan')">
                  <div class="item-value" v-if="dataMonitorRowIndex == 0">{{
                    selectData['Fan1StartStatus'] == '0' && globalConfig?.simulatedPassword
                      ? '-'
                      : selectData[data.dataIndex.replace('Fan', 'Fan1')]
                      ? selectData[data.dataIndex.replace('Fan', 'Fan1')]
                      : '-'
                  }}</div>
                  <div class="item-value" v-if="dataMonitorRowIndex == 1">{{
                    selectData['Fan2StartStatus'] == '0' && globalConfig?.simulatedPassword
                      ? '-'
                      : selectData[data.dataIndex.replace('Fan', 'Fan2')]
                      ? selectData[data.dataIndex.replace('Fan', 'Fan2')]
                      : '-'
                  }}</div>
                </div>
                <div v-else>
                  <div class="item-value">{{ selectData[data.dataIndex] ? selectData[data.dataIndex] : '-' }}</div>
                </div>
              </div>
            </template>
          </div>
        </div>
      </div>
      <div class="data-item">
        <div class="item-header">设备报警</div>
        <div class="item-container">
          <div class="tab">
            <div class="tab-item" :class="{ 'tab-item-active-r': warningMonitorRowIndex === 0 }" @click="selectDevice('warningMonitorRowIndex', 0)"
              >1#风机</div
            >
            <div class="tab-item" :class="{ 'tab-item-active-r': warningMonitorRowIndex === 1 }" @click="selectDevice('warningMonitorRowIndex', 1)"
              >2#风机</div
            >
          </div>
          <div class="container-group">
            <div class="warning-header">
              <div class="header-item">
                <div class="header-title">报警总数</div>
                <div class="header-value">0</div>
              </div>
              <div class="header-item">
                <div class="header-title"> 未处理数</div>
                <div class="header-value">0</div>
              </div>
            </div>
            <div class="warning-group">
              <template v-if="deviceType">
                <div class="warning-item" v-for="(state, index) in rightColumns" :key="index">
                  <div class="item-name"><div class="icon"></div> {{ state.title }}</div>
                  <div v-if="state.dataIndex.startsWith('Fan')">
                    <div class="signal-item" v-if="warningMonitorRowIndex == 0">
                      <template v-if="selectData['Fan1StartStatus'] == '0' && globalConfig?.simulatedPassword">
                        <div class="signal-round signal-round-gry"></div>
                        <div class="vent-margin-l-8">无状态</div></template
                      >
                      <template v-else>
                        <div
                          class="signal-round"
                          :class="{
                            'signal-round-run': selectData[state.dataIndex.replace('Fan', 'Fan1')],
                            'signal-round-warning':
                              selectData[state.dataIndex.replace('Fan', 'Fan1')] !== undefined && !selectData[state.dataIndex.replace('Fan', 'Fan1')],
                            'signal-round-gry': selectData[state.dataIndex.replace('Fan', 'Fan1')] === undefined,
                          }"
                        ></div>
                        <div class="vent-margin-l-8">{{
                          selectData[state.dataIndex.replace('Fan', 'Fan1')] === undefined
                            ? '无状态'
                            : selectData[state.dataIndex.replace('Fan', 'Fan1')]
                            ? '正常'
                            : '异常'
                        }}</div>
                      </template>
                    </div>
                    <div class="signal-item" v-if="warningMonitorRowIndex == 1">
                      <template v-if="selectData['Fan2StartStatus'] == '0' && globalConfig?.simulatedPassword">
                        <div class="signal-round signal-round-gry"></div>
                        <div class="vent-margin-l-8">无状态</div></template
                      >
                      <template v-else>
                        <div
                          class="signal-round"
                          :class="{
                            'signal-round-run': selectData[state.dataIndex.replace('Fan', 'Fan2')] == '1',
                            'signal-round-warning':
                              selectData[state.dataIndex.replace('Fan', 'Fan2')] != undefined &&
                              selectData[state.dataIndex.replace('Fan', 'Fan2')] == '0',
                            'signal-round-gry': selectData[state.dataIndex.replace('Fan', 'Fan2')] == undefined,
                          }"
                        ></div>
                        <div class="vent-margin-l-8">{{
                          selectData[state.dataIndex.replace('Fan', 'Fan2')] == undefined
                            ? '无状态'
                            : selectData[state.dataIndex.replace('Fan', 'Fan2')] == '1'
                            ? '正常'
                            : '异常'
                        }}</div>
                      </template>
                    </div>
                  </div>
                  <div v-else>
                    <div class="signal-item">
                      <div
                        class="signal-round vent-margin-l-8"
                        :class="{
                          'signal-round-run': selectData[state.dataIndex],
                          'signal-round-warning': selectData[state.dataIndex] !== undefined && !selectData[state.dataIndex],
                          'signal-round-gry': selectData[state.dataIndex] === undefined,
                        }"
                      ></div>
                      <div class="vent-margin-l-8">{{
                        selectData[state.dataIndex] === undefined ? '无状态' : selectData[state.dataIndex] ? '正常' : '异常'
                      }}</div>
                    </div>
                  </div>
                </div>
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="bottom-tabs-box" @mousedown="setDivHeight($event, 250, scroll, 170)">
      <dv-border-box8 :dur="5" :style="`padding: 5px; height: ${scroll.y + 120}px`">
        <a-tabs class="tabs-box" v-model:activeKey="activeKey" @change="tabChange">
          <a-tab-pane key="1" tab="实时监测">
            <GroupMonitorTable
              ref="MonitorDataTable"
              :dataSource="dataSource"
              columnsType="fanmain_monitor"
              @selectRow="getSelectRow"
              :scroll="{ y: scroll.y - (headElHeight - 56) }"
              :is-action="true"
            >
              <template #bodyCell="{ column, record }">
                <!-- <a-tag :color="record.netStatus == '0' ? '#f00' : 'green'">{{ record.netStatus == '1' ? '报警' : '正常' }}</a-tag> -->
              </template>
              <template #action="{ record }">
                <a v-if="globalConfig?.showReport" class="table-action-link" @click="deviceEdit($event, 'reportInfo', record)">报表录入</a>
                <a class="table-action-link" @click="deviceEdit($event, 'deviceInfo', record)">设备编辑</a>
              </template>
            </GroupMonitorTable>
          </a-tab-pane>
          <!-- <a-tab-pane key="2" tab="实时曲线图" force-render>
            <div class="tab-item" v-if="activeKey === '2'">
              <Bar :chartData="dataSource" xAxisPropType="strname" :propTypeArr="propTypeArr" height="40vh" width="100%" />
            </div>
          </a-tab-pane> -->
          <a-tab-pane key="3" tab="历史数据">
            <div class="tab-item" v-if="activeKey === '3'">
              <HistoryTable device-type="fanmain" designScope="fanmain-history" :scroll="scroll" />
            </div>
          </a-tab-pane>
          <a-tab-pane key="4" tab="报警历史">
            <div class="tab-item" v-if="activeKey === '4'">
              <AlarmHistoryTable
                columns-type="alarm"
                device-type="fanmain"
                :device-list-api="baseList"
                designScope="alarm-history"
                :scroll="scroll"
              />
            </div>
          </a-tab-pane>
          <a-tab-pane key="5" tab="操作历史">
            <div class="tab-item" v-if="activeKey === '5'">
              <HandlerHistoryTable
                columns-type="operator_history"
                device-type="fanmain"
                :device-list-api="baseList"
                designScope="alarm-history"
                :scroll="scroll"
              />
            </div>
          </a-tab-pane>
        </a-tabs>
      </dv-border-box8>
    </div>
  </div>
  <div style="z-index: -1; position: absolute; top: -100px; right: 10px; width: 300px; height: 280px; margin: auto" class="palyer">
    <LivePlayer id="main-player1" ref="player1" :videoUrl="flvURL1()" muted loop loading controls />
  </div>
  <div
    ref="playerRef"
    style="z-index: 999; position: absolute; top: 100px; right: 15px; width: 100%; height: 100%; margin: auto; pointer-events: none"
  >
  </div>
  <a-modal v-model:visible="modalIsShow" :centered="true" :title="modalTitle" @ok="handleOk" @cancel="handleCancel" :destroyOnClose="true">
    <template #footer v-if="modalType == 'fbm'">
      <a-button key="back" @click="handleCancel">取消</a-button>
    </template>
    <div class="modal-container">
      <div class="vent-flex-row">
        <ExclamationCircleFilled style="color: #ffb700; font-size: 30px" />
        <div class="warning-text">您是否要进行{{ modalTitle }}操作？</div>
      </div>
      <div class="vent-flex-row input-box" v-if="!globalConfig?.simulatedPassword">
        <div class="label">操作密码：</div>
        <a-input size="small" type="password" v-model:value="passWord" />
      </div>
      <!-- 调频 -->
      <div class="vent-flex-row input-box" v-if="modalType == 'frequency'">
        <div class="label">运行频率（Hz）：</div>
        <a-input-number v-model:value="frequencyVal" :min="0" :max="50" :step="0.1" />
      </div>
      <!-- 启动或停止 -->
      <div class="" v-if="modalType == 'startSmoke'">
        <div class="startSmoke-select">
          <div class="label">1#风机：</div>
          <a-radio-group v-model:value="mainWindIsShow1" @change="changeMotor" name="mainWind1">
            <a-radio value="open">开启</a-radio>
            <a-radio value="stop">停止</a-radio>
          </a-radio-group>
        </div>
        <div class="startSmoke-select">
          <div class="label">2#风机：</div>
          <a-radio-group v-model:value="mainWindIsShow2" @change="changeMotor" name="mainWind2">
            <a-radio value="open">开启</a-radio>
            <a-radio value="stop">停止</a-radio>
          </a-radio-group>
        </div>
      </div>
      <!-- 防爆门控制 -->
      <div class="" v-if="modalType == 'fbm'">
        <div class="vent-margin-t-20">
          <span class="data-title vent-margin-r-8">反风锁紧状态：</span>
          <template
            v-if="selectData['Lock1Open'] == 1 && selectData['Lock1Close'] == 0 && selectData['Lock2Open'] == 1 && selectData['Lock2Close'] == 0"
          >
            <span class="data-title vent-margin-l-10"><span class="signal-round signal-round-blue vent-margin-r-8"></span>锁1开到位</span>
            <span class="data-title vent-margin-l-20"><span class="signal-round signal-round-blue vent-margin-r-8"></span>锁2开到位</span>
          </template>
          <template
            v-else-if="selectData['Lock1Open'] == 0 && selectData['Lock1Close'] == 1 && selectData['Lock2Open'] == 0 && selectData['  '] == 1"
          >
            <span class="data-title vent-margin-l-10"><span class="signal-round signal-round-gry vent-margin-r-8"></span>锁1关到位</span>
            <span class="data-title vent-margin-l-20"><span class="signal-round signal-round-gry vent-margin-r-8"></span>锁2关到位</span>
          </template>
          <template v-else>
            <span class="data-title vent-margin-l-10"><span class="signal-round signal-round-gry vent-margin-r-8"></span>锁1-</span>
            <span class="data-title vent-margin-l-20"><span class="signal-round signal-round-gry vent-margin-r-8"></span>锁2-</span>
          </template>
        </div>
        <div class="vent-flex-row btn-box vent-margin-t-20">
          <span class="data-title vent-margin-r-8">反风锁紧控制：</span>
          <div v-if="fbmControlData.CtrlLockOpen !== undefined">
            <span class="btn btn1" @click="handleOk('openLock')">开锁</span>
            <span class="btn btn2" @click="handleOk('closeLock')">关锁</span>
          </div>
          <!-- <a-switch v-if="fbmControlData.CtrlLockOpen !== undefined" style="margin-left: 5px;" v-model:checked="fbmControlData.CtrlLockOpen" checked-children="开锁" un-checked-children="关锁" /> -->
          <div v-else class="vent-margin-l-10"
            ><span class="signal-round signal-round-warning vent-margin-r-8"></span>反风锁紧正在运行 或 数据异常</div
          >
        </div>
        <div class="vent-flex-row btn-box vent-margin-t-20">
          <span class="data-title vent-margin-r-8">防爆门扇控制：</span>
          <div v-if="fbmControlData.CtrlExplosionVentOpen !== undefined">
            <span class="btn btn1" @click="handleOk('openGate')">开门</span>
            <span class="btn btn2" @click="handleOk('closeGate')">关门</span>
          </div>
          <!-- <a-switch v-if="fbmControlData.CtrlExplosionVentOpen !== undefined" style="margin-left: 5px;" v-model:checked="fbmControlData.CtrlExplosionVentOpen" checked-children="开门" un-checked-children="关门" /> -->
          <div class="vent-margin-l-10" v-else><span class="signal-round signal-round-warning vent-margin-r-8"></span>防爆门正在运行 或 数据异常</div>
        </div>
      </div>
    </div>
  </a-modal>
  <!-- 工况辅助决策 -->
  <ConditionAssistance @register="registerModal" />
  <DeviceBaseInfo @register="registerModalDeviceEdit" :device-type="selectData['deviceType']" />
</template>

<script setup lang="ts">
  import { ExclamationCircleFilled } from '@ant-design/icons-vue';
  import FanEchrats from '/@/views/vent/monitorManager/mainFanMonitor/fanEchrats.vue';
  import { onBeforeMount, computed, ref, onMounted, inject, onUnmounted, reactive, toRaw, watch, nextTick } from 'vue';
  import GroupMonitorTable from '../comment/GroupMonitorTable.vue';
  import HistoryTable from '../comment/HistoryTable.vue';
  import AlarmHistoryTable from '../comment/AlarmHistoryTable.vue';
  import HandlerHistoryTable from '../comment/HandlerHistoryTable.vue';
  import { modalTypeArr, fbmControlData } from './main.data';
  import { deviceControlApi } from '/@/api/vent/index';
  import { mountedThree, destroy, addText, setModelType, playAnimate, resetEcharts } from './main.threejs';
  import LivePlayer from '@liveqing/liveplayer-v3';
  import { SvgIcon } from '/@/components/Icon';
  import { list } from './main.api';
  import { list as baseList } from '../../deviceManager/fanTabel/fan.api';
  import { getTableList } from '/@/views/vent/monitorManager/fanLocalMonitor/fanLocal.api';
  import { getTableHeaderColumns } from '/@/hooks/web/useWebColumns';
  import { setDivHeight } from '/@/utils/event';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BorderBox8 as DvBorderBox8 } from '@kjgl77/datav-vue3';
  import { useRouter } from 'vue-router';
  import ConditionAssistance from './components/conditionAssistance.vue';
  import { useModal } from '/@/components/Modal';
  import type { BasicColumn } from '/@/components/Table/src/types/table';
  import { useCamera } from '/@/hooks/system/useCamera';
  import DeviceBaseInfo from '../comment/components/DeviceBaseInfo.vue';
  const globalConfig = inject('globalConfig');

  const [registerModal, { openModal, closeModal }] = useModal();
  const [registerModalDeviceEdit, { openModal: openModalDeviceEdit }] = useModal();
  const { currentRoute } = useRouter();

  const { createMessage } = useMessage();
  const scroll = reactive({
    y: 180,
  });
  const playerRef = ref();
  const isSimulation = true; // 是否模拟状态
  const MonitorDataTable = ref();
  const player1 = ref(null);
  const player2 = ref(null);
  const activeKey = ref('1');
  const loading = ref(false);
  const modalIsShow = ref<boolean>(false); // 是否显示模态框
  const modalTitle = ref(''); // 模态框标题显示内容，根据设备操作类型决定
  const modalType = ref(''); // 模态框内容显示类型，设备操作类型
  const frequencyVal = ref(40); //频率
  const mainWindIsShow1 = ref('stop'); // 1#风机默认启动
  const mainWindIsShow2 = ref('stop'); // 2#风机默认不启动
  const frontMonitorIsShow = ref(false); // 存放1#风机临时状态，保存模态框取消时，还需要返回之前的值
  const backMonitorIsShow = ref(false); // 存放2#风机临时状态，保存模态框取消时，还需要返回之前的值
  const passWord = ref('');
  // 默认初始是第一行 (默认n%2==0时是主机，n%2==1时是备机)
  const selectRowIndex = ref(-1);
  // 默认数据左边监测的是1#风机
  const dataMonitorRowIndex = ref(0);
  // 默认数据右边监测的是1#风机
  const warningMonitorRowIndex = ref(0);
  let headElHeight = ref(0);

  // 监测数据
  const selectData = reactive({
    deviceID: '',
    Fan1Negative: '-', // 静压
    Fan2Negative: '-', // 静压
    DataPa: '-', //全压
    Fan1m3: '-', //电机流量
    Fan2m3: '-', //电机流量
    deviceType: '',
    Fan2FanPre: '-',
    Fan1FanPre: '-',
  });

  const deviceType = ref(selectData.deviceType);
  const rightColumns = ref<BasicColumn[]>([]);
  const leftColumns = ref<BasicColumn[]>([]);
  watch(deviceType, (type) => {
    rightColumns.value = getTableHeaderColumns(type + '_monitor_right') as [];
    if (rightColumns.value && rightColumns.value.length < 1) {
      rightColumns.value = getTableHeaderColumns(type.split('_')[0] + '_monitor_right') as [];
    }
    leftColumns.value = getTableHeaderColumns(type + '_monitor_left') as [];
    if (leftColumns.value && leftColumns.value.length < 1) {
      leftColumns.value = getTableHeaderColumns(type.split('_')[0] + '_monitor_left') as [];
    }
  });

  const flvURL1 = () => {
    // return `https://muiplayer.js.org/media/media.m3u8`;
    return `/video/mainWind.mp4`;
  };
  const flvURL2 = () => {
    return `/video/mainWind.mp4`;
    // return `https://sf1-hscdn-tos.pstatp.com/obj/media-fe/xgplayer_doc_video/flv/xgplayer-demo-360p.flv`;
  };

  // const dataSource = computed(() => {
  //   const data = [...getRecordList()] || [];
  //   Object.assign(selectData, toRaw(data[selectRowIndex.value]));
  //   addMonitorText(selectData);
  //   return data;
  // });

  const dataSource = ref([]);

  const propTypeArr = new Map([
    ['incipientWindSpeed1', 'V1风速'],
    ['incipientWindSpeed2', 'V2风速'],
    ['incipientWindSpeed3', 'V3风速'],
    ['sourcePressure', '气源压力'],
  ]);

  const { getCamera, removeCamera } = useCamera();

  const tabChange = (activeKeyVal) => {
    activeKey.value = activeKeyVal;
    MonitorDataTable.value.setSelectedRowKeys(selectData.deviceID);
  };

  // 设备数据
  const controlType = ref(1);

  const getDataSource = async () => {
    const res = await list({ devicetype: 'fanmain', pagetype: 'normal' });
    const dataArr = res.msgTxt[0].datalist || [];
    dataSource.value = [];
    dataArr.forEach((data) => {
      const readData = data.readData;
      data = Object.assign(data, readData);
      dataSource.value.push(data);
    });
    const data: any = toRaw(dataSource.value[selectRowIndex.value]); //maxarea

    Object.assign(selectData, data);
    return data;
  };
  // https获取监测数据
  let timer: null | NodeJS.Timeout = null;
  const getMonitor = (flag?) => {
    if (Object.prototype.toString.call(timer) === '[object Null]') {
      timer = setTimeout(
        async () => {
          await getDataSource();
          if (dataSource.value.length > 0 && selectRowIndex.value == -1) {
            // 初始打开页面
            if (currentRoute.value && currentRoute.value['query'] && currentRoute.value['query']['id']) {
              MonitorDataTable.value.setSelectedRowKeys(currentRoute.value['query']['id']);
            } else {
              MonitorDataTable.value.setSelectedRowKeys(dataSource.value[0]['deviceID']);
            }
          }
          Object.assign(selectData, deviceBaseList.value, dataSource.value[selectRowIndex.value]);
          if (selectData['Fan1StartStatus'] == 1 && selectData['Fan2StartStatus'] == 0) {
            frontMonitorIsShow.value = true;
            backMonitorIsShow.value = false;
          } else if (selectData['Fan2StartStatus'] == 1 && selectData['Fan1StartStatus'] == 0) {
            backMonitorIsShow.value = true;
            frontMonitorIsShow.value = false;
          }
          deviceType.value = selectData.deviceType;
          addText();
          playAnimate(selectData);
          if (timer) {
            timer = null;
          }
          getMonitor();
        },
        flag ? 0 : 1000
      );
    }
  };

  // const getMonitor = () => {
  //   if (Object.prototype.toString.call(timer) === '[object Null]') {
  //     timer = setTimeout(() => {
  //       if (timer) {
  //         timer = null;
  //       }
  //       dataSource.value = getData();
  //       // 默认前两行（主、备）是正在监测的主通风机, 实际中需要手动选中
  //       const monitorData = getMonitorData();
  //       Object.assign(dataSource.value[selectRowIndex.value], monitorData);
  //       const data: any = toRaw(dataSource.value[selectRowIndex.value]);
  //       Object.assign(selectData, data);
  //       resetEcharts('mainWindRect');
  //       getMonitor();
  //     }, 1000);
  //   }
  // };

  const deviceBaseList = ref([]);
  const getDeviceBaseList = () => {
    getTableList({ pageSize: 1000 }).then((res) => {
      deviceBaseList.value = res.records;
    });
  };
  // 切换检测数据
  const getSelectRow = async (id) => {
    if (!id) return;
    loading.value = true;
    const baseDataIndex: any = dataSource.value.findIndex((baseData: any) => baseData.deviceID === id);
    selectRowIndex.value = baseDataIndex;
    const type = 'mainWindRect';
    for (const key in selectData) {
      selectData[key] = '';
    }
    nextTick(async () => {
      await setModelType(type);
      loading.value = false;
      if (!headElHeight.value) {
        const headEl = document.querySelector(`.zxm-table-thead`);
        if (headEl) {
          headElHeight.value = headEl.clientHeight;
        }
      }
      const data = dataSource.value[selectRowIndex.value];
      if (data['Fan1StartStatus'] == 1) {
        selectDevice('warningMonitorRowIndex', 0);
        selectDevice('dataMonitorRowIndex', 0);
      } else if (data['Fan2StartStatus'] == 1) {
        selectDevice('warningMonitorRowIndex', 1);
        selectDevice('dataMonitorRowIndex', 1);
      }
      Object.assign(selectData, data);
    });
    await getCamera(id, playerRef.value);
    return;
  };

  const start = (paramcode, value?, isTest?) => {
    return new Promise((reolve, reject) => {
      let data;
      if (isTest) {
        data = {
          deviceid: selectData.deviceID,
          devicetype: selectData.deviceType,
          paramcode: paramcode,
          password: passWord.value || globalConfig?.simulatedPassword,
          testvalue: value,
        };
      } else {
        data = {
          deviceid: selectData.deviceID,
          devicetype: selectData.deviceType,
          paramcode: paramcode,
          password: passWord.value || globalConfig?.simulatedPassword,
          value: value,
        };
      }
      deviceControlApi(data)
        .then((res) => {
          if (res.success) {
            reolve(null);
          } else {
            reject(null);
          }
        })
        .catch(() => {
          reject(null);
        });
    });
  };

  // 切换左右两边1#、2#风机的监测数据
  const selectDevice = (key, val) => {
    if (key === 'dataMonitorRowIndex') {
      dataMonitorRowIndex.value = val;
    } else {
      warningMonitorRowIndex.value = val;
    }
  };

  // 打开并设置modal的标题
  const showModal = (obj) => {
    if (obj.key == 'kkjc') {
      // 工况辅助决策
      openModal(true, {});
      return;
    }
    modalType.value = obj.key;
    modalTitle.value = obj.value;
    modalIsShow.value = true;
    if (modalType.value == 'startSmoke') {
      if (selectData['Fan1StartStatus'] == 1 && selectData['Fan2StartStatus'] == 0) {
        mainWindIsShow1.value = 'open';
        mainWindIsShow2.value = 'stop';
        frontMonitorIsShow.value = true;
        backMonitorIsShow.value = false;
      } else if (selectData['Fan2StartStatus'] == 1 && selectData['Fan1StartStatus'] == 0) {
        mainWindIsShow2.value = 'open';
        mainWindIsShow1.value = 'stop';
        backMonitorIsShow.value = true;
        frontMonitorIsShow.value = false;
      }
    }
    if (modalType.value == 'frequency') {
      if (selectData['Fan1StartStatus'] == 1 && selectData['Fan2StartStatus'] == 0) {
        frequencyVal.value = selectData['Fan1FreqHz'];
      }
      if (selectData['Fan2StartStatus'] == 1 && selectData['Fan1StartStatus'] == 0) {
        frequencyVal.value = selectData['Fan2FreqHz'];
      }
    }
  };

  const changeMotor = (e) => {
    const target = e.target;
    if (target.name === 'mainWind1') {
      if (target.value === 'open') {
        mainWindIsShow2.value = 'stop';
      }
    } else if (target.name === 'mainWind2') {
      if (target.value === 'open') {
        mainWindIsShow1.value = 'stop';
      }
    }
  };

  const handleOk = (flag?) => {
    // if (passWord.value !== '123456') {
    //   createMessage.warning('密码不正确，请重新输入');
    //   return;
    // }
    if (modalType.value == 'startSmoke') {
      if (selectData['Fan1StartStatus'] == 1 && selectData['Fan2StartStatus'] == 0) {
        start('CtrlFan2Start')
          .then(() => {
            frontMonitorIsShow.value = false;
            backMonitorIsShow.value = true;
          })
          .catch(() => {
            createMessage.error('操作失败，请联系管理员');
          });
      } else if (selectData['Fan1StartStatus'] == 0 && selectData['Fan2StartStatus'] == 1) {
        start('CtrlFan1Start')
          .then(() => {
            frontMonitorIsShow.value = true;
            backMonitorIsShow.value = false;
          })
          .catch(() => {
            createMessage.error('操作失败，请联系管理员');
          });
      } else if (mainWindIsShow1.value === 'stop' && mainWindIsShow2.value === 'stop') {
        frontMonitorIsShow.value = false;
        backMonitorIsShow.value = false;
      }
    } else if (modalType.value == 'changeDirection') {
      if (selectData['Fan1StartStatus'] == 1 && selectData['Fan2StartStatus'] == 0) {
        // 主机一键反风
        if (isSimulation) {
          const fan1Forward = selectData['Fan1FreqForwardRun'] == 1 ? 0 : 1;
          const fan1Reverse = fan1Forward == 0 ? 1 : 0;
          // 模拟
          start('CtrlFan1Reverse', { Fan1FreqForwardRun: fan1Forward, Fan1FreqReverseRun: fan1Reverse }, true).catch(() => {
            createMessage.error('操作失败，请联系管理员');
          });
        } else {
          // 实际
          start('CtrlFan1Reverse').catch(() => {
            createMessage.error('操作失败，请联系管理员');
          });
        }
      } else if (selectData['Fan2StartStatus'] == 1 && selectData['Fan1StartStatus'] == 0) {
        if (isSimulation) {
          const fan2Forward = selectData['Fan2FreqForwardRun'] == 1 ? 0 : 1;
          const fan2Reverse = fan2Forward == 0 ? 1 : 0;
          // 模拟
          start('CtrlFan2Reverse', { Fan2FreqForwardRun: fan2Forward, Fan2FreqReverseRun: fan2Reverse }, true).catch(() => {
            createMessage.error('操作失败，请联系管理员');
          });
        } else {
          // 实际
          start('CtrlFan2Reverse').catch(() => {
            createMessage.error('操作失败，请联系管理员');
          });
        }
      }
    } else if (selectData['Fan2StartStatus'] == 0 && selectData['Fan1StartStatus'] == 0) {
    } else if (modalType.value == 'changeSmoke') {
      // 不听风倒机
      if (selectData['Fan1StartStatus'] == 1 && selectData['Fan2StartStatus'] == 0) {
        // 由主到备
        // 正启动
        if (selectData['Fan1FreqForwardRun'] && selectData['Fan1FreqForwardRun'] == 1) {
          console.log('一键1倒2正启动控制  ');
          start('CtrlFan1ToFan2Forward')
            .then(() => {
              frontMonitorIsShow.value = false;
              backMonitorIsShow.value = true;
            })
            .catch(() => {
              createMessage.error('操作失败，请联系管理员');
            });
        }
        // 反启动
        if (selectData['Fan1FreqReverseRun'] && selectData['Fan1FreqReverseRun'] == 1) {
          console.log('一键1倒2反启动控制');
          start('CtrlFan1ToFan2Reverse')
            .then(() => {
              frontMonitorIsShow.value = false;
              backMonitorIsShow.value = true;
            })
            .catch(() => {
              createMessage.error('操作失败，请联系管理员');
            });
        }
      } else if (selectData['Fan2StartStatus'] == 1 && selectData['Fan1StartStatus'] == 0) {
        // 由备到主
        // 正启动
        if (selectData['Fan2FreqForwardRun'] && selectData['Fan2FreqForwardRun'] == 1) {
          console.log('一键2倒1正启动控制');
          start('CtrlFan2ToFan1Forward')
            .then(() => {
              frontMonitorIsShow.value = true;
              backMonitorIsShow.value = false;
            })
            .catch(() => {
              createMessage.error('操作失败，请联系管理员');
            });
        }
        // 反启动
        if (selectData['Fan2FreqReverseRun'] && selectData['Fan2FreqReverseRun'] == 1) {
          console.log('一键2倒1反启动控制');
          start('CtrlFan2ToFan1Reverse')
            .then(() => {
              frontMonitorIsShow.value = true;
              backMonitorIsShow.value = false;
            })
            .catch(() => {
              createMessage.error('操作失败，请联系管理员');
            });
        }
      }
    } else if (modalType.value == 'frequency') {
      if (selectData['Fan1StartStatus'] == 1 && selectData['Fan2StartStatus'] == 0) {
        start('CtrlFan1FreqSet', frequencyVal.value).catch(() => {
          createMessage.error('操作失败，请联系管理员');
        });
      } else if (selectData['Fan2StartStatus'] == 1 && selectData['Fan1StartStatus'] == 0) {
        start('CtrlFan2FreqSet', frequencyVal.value).catch(() => {
          createMessage.error('操作失败，请联系管理员');
        });
      }
    } else if (modalType.value == 'fbm') {
      // 门扇处于打开状态时，反风锁紧装置无法操作
      if (selectData['ExplosionVentOpen'] == 1 && (flag === 'openLock' || flag === 'closeLock')) {
        createMessage.warning('门扇处于打开状态时，反风锁紧装置无法操作');
        return;
      }
      // 当反风装置关锁时，无法控制门体打开或关闭
      if ((selectData['Lock1Close'] == 1 || selectData['Lock2Close'] == 1) && (flag === 'openGate' || flag === 'closeGate')) {
        createMessage.warning('当反风装置关锁时，无法控制门体打开或关闭');
        return;
      }
      // 开锁 // 关锁
      if (flag === 'openLock') {
        start('CtrlLockOpen').then(() => {
          createMessage.success('开锁成功');
        });
      } else if (flag === 'closeLock') {
        start('CtrlLockClose').then(() => {
          createMessage.success('关锁成功');
        });
      }

      // 开门  关门
      if (flag === 'openGate') {
        start('CtrlExplosionVentOpen').then(() => {
          createMessage.success('开门成功');
        });
      } else if (flag === 'closeGate') {
        start('CtrlExplosionVentClose').then(() => {
          createMessage.success('关门成功');
        });
      }
    }

    modalTitle.value = '';
    modalIsShow.value = false;
  };

  // 取消
  const handleCancel = () => {
    if (modalType.value == 'startSmoke') {
      const data = dataSource.value[selectRowIndex.value];
      mainWindIsShow1.value = 'stop';
      mainWindIsShow2.value = 'stop';
      if (data['fanStart1'] == 1) {
        mainWindIsShow1.value = 'open';
      } else if (data['fanStart2'] == 1) {
        mainWindIsShow2.value = 'open';
      }
    }
    modalIsShow.value = false;
  };

  function deviceEdit(e: Event, type: string, record) {
    e.stopPropagation();
    openModalDeviceEdit(true, {
      type,
      deviceId: record['deviceID'],
    });
  }

  onBeforeMount(() => {
    // document.body.addEventListener('mousedown', addPlayVideo, true);
    getDeviceBaseList();
  });

  onMounted(() => {
    loading.value = true;

    mountedThree(player1.value).then(async () => {
      // await setModelType('mainWindRect');
      getMonitor(true);
      addText();
      // addText();
      // play('initiatePlay', 'front', frequencyVal.value, 'open', 'tubPositivePath');
    });
  });

  onUnmounted(() => {
    destroy();
    removeCamera();
    if (timer) {
      clearTimeout(timer);
      timer = undefined;
    }
  });
</script>

<style scoped lang="less">
  @import '/@/design/vent/modal.less';
  :deep(.@{ventSpace}-tabs-tabpane-active) {
    height: 100%;
  }
  .head-line {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    .button-box {
      position: relative;
      padding: 5px;
      border: 1px transparent solid;
      border-radius: 5px;
      // margin-left: 8px;
      // margin-right: 8px;
      width: auto;
      height: 34px;
      border: 1px solid #65dbea;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      padding: 0 10px;
      cursor: pointer;
      &:hover {
        background: linear-gradient(#3eb2ff55, #00c3ff55);
      }
      &::before {
        width: calc(100% - 6px);
        height: 26px;
        content: '';
        position: absolute;
        top: 3px;
        right: 0;
        left: 3px;
        bottom: 0;
        z-index: -1;
        border-radius: inherit; /*important*/
        background: linear-gradient(#014978, #3bf3fc);
      }
    }
  }

  .control-group,
  .top-box {
    display: flex !important;
    align-items: center !important;
    justify-content: space-around !important;
    position: absolute !important;
    width: 915px !important;
    height: 75px !important;
    left: 50% !important;
    top: 85px !important;
    transform: translateX(-50%) !important;
    background: url('/@/assets/images/vent/tab-group-bg.png') no-repeat !important;
    padding: 0 30px !important;
    .button-box {
      height: 35px !important;
      min-width: 100px;
      padding-top: 3px !important;
      border: 1px transparent solid;
      border: 1px solid #65dbea;
      &:hover {
        background: linear-gradient(#2cd1ff55, #1eb0ff55) !important;
      }
      &::before {
        height: 27px !important;
        background: linear-gradient(#1fa6cb, #127cb5) !important;
      }
      &::after {
        top: 35px !important;
      }
    }
    .button-box-disable {
      border: 1px solid #65dbea !important;
      &:hover {
        background: none !important;
      }
      &:before {
        background: linear-gradient(#5897c299, #4a92a899) !important;
      }
    }
  }
  .data-show-box {
    position: relative;

    display: flex;
    flex-direction: row;
    justify-content: space-between;
    padding: 10px;
    color: #ffffff;
    z-index: 999;
    top: 70px;
    .data-item {
      pointer-events: auto;
      .item-header {
        width: 374px;
        background: url('/@/assets/images/vent/lr-top-bg.png') no-repeat;
        background-size: auto;
        height: 32px;
        text-align: center;
        line-height: 34px;
        font-size: 15px;
        font-weight: 600;
        color: #fafafa;
      }
      .item-container {
        width: 346px;
        margin: 0 14px;
        padding: 10px;
        background: #004aac33;
        backdrop-filter: blur(2px);
        .tab {
          width: 323px;
          background: url('/@/assets/images/vent/lr-tab-bg.png') no-repeat;
          display: flex;
          .tab-item {
            flex: 1;
            text-align: center;
            padding-top: 2px;
            color: #ffffff99;
            cursor: pointer;
            &:hover {
              color: #ffffff;
            }
          }
          .tab-item-active-l {
            color: #ffffff;
            background-image: url('/@/assets/images/vent/l-tab-active.png');
            background-repeat: no-repeat;
            background-size: auto;
            background-position: 6px 3px;
          }
          .tab-item-active-r {
            color: #ffffff;
            background-image: url('/@/assets/images/vent/r-tab-active.png');
            background-repeat: no-repeat;
            background-position: 0 3px;
          }
        }
        .container-group {
          width: 314px;
          margin: 0px 4px;
          padding: 10px 0;
          min-height: 472px;
          background: linear-gradient(to right, #007bff22, #2081ff05);
          max-height: 480px;
          overflow-y: auto;
        }
        .container-group-l {
          .container-item {
            width: 100%;
            height: 63px;
            display: flex;
            padding: 10px 0 0 20px;
            margin-bottom: 5px;
            position: relative;
            background: url('/@/assets/images/vent/plane-bottom.png') no-repeat;
            background-size: auto;
            background-position: bottom;
            &::before {
              content: '';
              display: block;
              width: 100%;
              height: 5px;
              position: absolute;
              top: 62px;
              left: 0;
              background-color: #73f4ff66;
              backdrop-filter: blur(5px);
            }
            .item-icon {
              width: 54px;
              height: 45px;
              background: url('/@/assets/images/vent/plane-icon-bg.png') no-repeat;
              background-size: cover;
              .icon-style {
                margin: 10px 0 0 18px;
              }
            }
            .item-name {
              width: 180px;
              line-height: 60px;
            }
            .item-value {
              position: relative;
              height: 26px;
              line-height: 24px;
              margin: 15px 0;
              text-align: center;
              width: 80px;
              border: 1px solid #00f5fe;
              border-radius: 13px;
              background: linear-gradient(to right, #00f5fe44, #0090ff44);
              &::before {
                width: 6px;
                height: 6px;
                content: '';
                position: absolute;
                left: -3px;
                top: 8px;
                background: #ffa500;
                border-radius: 3px;
              }
            }
          }
        }
        .warning-header {
          display: flex;
          font-size: 14px;
          .header-item {
            flex: 1;
            display: flex;
            flex-direction: column;
            margin: 5px 10px;
            justify-content: center;
            align-items: center;
            .header-title {
              color: #39e7fe;
            }
            .header-value {
              width: 133px;
              height: 56px;
              font-weight: 600;
              font-family: 'douyuFont';
              font-size: 16px;
              color: #ffa500;
              display: flex;
              justify-content: center;
              align-items: center;
              background: url('/@/assets/images/vent/count-header-bg.png') no-repeat;
            }
          }
        }
        .warning-group {
          padding: 0 10px;
          position: relative;
          &::before {
            content: '';
            display: block;
            width: 1px;
            height: 100%;
            position: absolute;
            left: 12px;
            background-color: #00f5fe;
          }
          .warning-item {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            align-items: center;
            height: 38px;
            .item-name {
              .icon {
                width: 6px;
                height: 6px;
                display: inline-block;
                background-color: #1cd5ff;
                border-radius: 3px;
                position: relative;
                margin-right: 5px;
                &::before {
                  content: '';
                  width: 10px;
                  height: 10px;
                  display: block;
                  border: 1px solid #34edff99;
                  border-radius: 5px;
                  position: absolute;
                  top: -2px;
                  left: -2px;
                }
              }
            }
          }
        }
      }
    }
  }

  .scene-box .bottom-tabs-box {
    height: 280px;
    .tabs-box {
      position: relative !important;
    }
  }

  .threejs-Object-CSS {
    .elementTag {
      .elementContent {
        backdrop-filter: blur(2px);
        width: 220px;
        background-color: rgba(0, 0, 0, 0.6);
        box-shadow: 0px 0px 40px rgb(0 90 131 / 55%) inset;
        border: 2px solid rgb(153 176 195 / 55%);
        padding: 15px 20px 15px 20px;
        font-size: 15px;
        .element-item {
          line-height: 38px;
          display: flex;
          justify-content: space-between;
        }
        span {
          color: #f2a500;
          // color: #74e9fe;
        }
        .data-title {
          display: inline-block;
          color: #fff;
        }
      }
      .elementContent-r {
        &::before {
          right: 120px;
        }
        &::after {
          right: 270px;
          border: 4px solid rgb(0, 221, 255); //rgb(0 220 255 / 75%)
          background: #a7a7a766;
        }
      }
      .fbm-box {
        width: auto;
        display: flex;
        justify-content: space-between;
        .fbm-video {
          width: 240px;
          margin-right: 20px;
        }
        .fbm-data {
          width: 200px;
        }
      }
    }
  }

  .btn {
    padding: 4px 12px;
    position: relative;
    border-radius: 2px;
    color: #fff;
    cursor: pointer;

    &::before {
      position: absolute;
      display: block;
      content: '';
      width: calc(100% - 4px);
      height: calc(100% - 4px);
      top: 2px;
      left: 2px;
      border-radius: 2px;
      z-index: -1;
    }
  }

  .btn1 {
    border: 1px solid #5cfaff;

    &::before {
      background-image: linear-gradient(#2effee92, #0cb1d592);
    }

    &:hover {
      border: 1px solid #5cfaffaa;

      &::before {
        background-image: linear-gradient(#2effee72, #0cb1d572);
      }
    }
  }
  .btn2 {
    border: 1px solid #19c3e9;
    margin-left: 10px;

    &::before {
      background-image: linear-gradient(#2584b0, #1f75a3);
    }

    &:hover {
      &::before {
        background-image: linear-gradient(#2584b0cc, #1f75a3cc);
      }
    }
  }
  ::v-deep(#LivePlayerBox) {
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    padding-right: 380px;
    pointer-events: none;
    .video-parent {
      height: 208px;
      pointer-events: auto !important;
    }
  }
  ::v-deep(.@{ventSpace}-table-wrapper) {
    height: 100% !important;
  }
  ::v-deep(.@{ventSpace}-spin-container) {
    height: 100% !important;
    overflow-y: auto;
  }
  .label {
    max-width: 220px;
  }
  .@{ventSpace}-input {
    width: 150px;
  }
</style>
