<template>
  <div class="bg" style="width: 100%; height: 100%; display: flex; justify-content: center; align-items: center; overflow: hidden"> </div>
  <div class="scene-box">
    <div class="top-box">
      <div class="top-center row">
        <div v-if="hasPermission('btn:control')" class="button-box" @click="playAnimation(1)">打开防火门</div>
        <div v-if="hasPermission('btn:control')" class="button-box" @click="playAnimation(2)">关闭防火门</div>
      </div>
      <!-- 控制模式 -->
      <div class="top-right row">
        <div class="vent-flex-m row" v-if="selectData.contrlMod == 'loopCtrl'">
          <div class="control-title">控制模式：</div>
          <a-radio-group v-model:value="selectData.autoRoManual">
            <template v-for="(item, index) in modelList" :key="index">
              <a-radio :value="item.value" :disabled="true">{{ item.text }}</a-radio>
            </template>
          </a-radio-group>
          <div class="button-box" @click="playAnimation(7)">切换模式</div>
        </div>
        <div class="vent-flex-m row" v-else>
          <div class="control-title">控制模式：</div>
          <a-radio-group v-model:value="selectData.autoRoManual">
            <template v-for="(item, index) in modelList" :key="index">
              <a-radio :value="item.value" :disabled="true">{{ item.text }}</a-radio>
            </template>
          </a-radio-group>
          <div class="button-box" v-for="(item, index) in modelList" @click="playAnimation(7, item.value)" :key="index">{{ item.text }}</div>
        </div>

        <!-- <div class="run-type row">
          <div class="control-title">运行状态：</div>
          <a-radio-group v-model:value="selectData.runRoRecondition">
            <a-radio :value="`0`">检修</a-radio>
            <a-radio :value="`1`">运行</a-radio>
          </a-radio-group>
        </div> -->
      </div>
    </div>
    <div class="title-text"> 设备监测 </div>
    <div class="bottom-tabs-box" @mousedown="setDivHeight($event, 300, scroll)">
      <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="实时监测">
            <MonitorTable
              v-if="activeKey === '1'"
              ref="MonitorDataTable"
              class="monitor-table"
              :columnsType="deviceType"
              :isShowActionColumn="true"
              :dataSource="dataSource"
              design-scope="gate-monitor"
              @select-row="getSelectRow"
              :scroll="{ y: scroll.y - 40 }"
              title="风门监测"
              :isShowPagination="true"
            >
              <template #filterCell="{ column, record }">
                <a-tag v-if="column.dataIndex === 'frontGateOpen' && record.frontGateOpen == '0' && record.frontGateClose == '0'" color="red"
                  >正在运行</a-tag
                >
                <a-tag v-else-if="column.dataIndex === 'frontGateOpen' && record.frontGateOpen == '0' && record.frontGateClose == 1" color="default"
                  >关闭</a-tag
                >
                <a-tag v-else-if="column.dataIndex === 'frontGateOpen' && record.frontGateOpen == '1' && record.frontGateClose == '0'" color="#46C66F"
                  >打开</a-tag
                >
                <a-tag v-else-if="column.dataIndex === 'frontGateOpen' && record.frontGateOpen == '1' && record.frontGateClose == '1'" color="#FF0000"
                  >点位异常</a-tag
                >
                <template v-else-if="column.dataIndex === 'warnLevel'">
                  <a-tag v-if="record.warnLevel == '101'" color="green">低风险</a-tag>
                  <a-tag v-else-if="record.warnLevel == '102'" color="#FF5812">一般风险</a-tag>
                  <a-tag v-else-if="record.warnLevel == '103'" color="#FF5812">较大风险</a-tag>
                  <a-tag v-else-if="record.warnLevel == '104'" color="#FF5812">重大风险</a-tag>
                  <a-tag v-else-if="record.warnLevel == '201'" color="#FF0000">报警</a-tag>
                  <a-tag v-else-if="record.warnLevel == '10000'" color="#FF5812">数据超限</a-tag>
                  <a-tag v-else-if="record.warnLevel == '1001'" color="default">网络中断</a-tag>
                  <a-tag v-else color="green">正常</a-tag>
                </template>
                <a-tag v-else-if="column.dataIndex === 'warnFlag'" :color="record.warnFlag == '0' ? 'green' : 'red'">{{
                  record.warnFlag == '0' ? '正常' : '报警'
                }}</a-tag>
                <a-tag v-if="column.dataIndex === 'netStatus'" :color="record.netStatus == '0' ? '#f00' : 'green'">{{
                  record.netStatus == '0' ? '断开' : '连接'
                }}</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>
            </MonitorTable>
          </a-tab-pane>
          <a-tab-pane key="3" tab="历史数据">
            <div class="tab-item" v-if="activeKey === '3'">
              <HistoryTable :columnsType="deviceType" :device-type="deviceType" designScope="gate-history" :scroll="scroll">
                <template #filterCell="{ column, record }">
                  <a-tag v-if="column.dataIndex === 'frontGateOpen' && record.frontGateOpen == '0' && record.frontGateClose == '0'" color="red"
                    >正在运行</a-tag
                  >
                  <a-tag v-else-if="column.dataIndex === 'frontGateOpen' && record.frontGateOpen == '0' && record.frontGateClose == 1" color="default"
                    >关闭</a-tag
                  >
                  <a-tag
                    v-else-if="column.dataIndex === 'frontGateOpen' && record.frontGateOpen == '1' && record.frontGateClose == '0'"
                    color="#46C66F"
                    >打开</a-tag
                  >
                  <a-tag
                    v-else-if="column.dataIndex === 'frontGateOpen' && record.frontGateOpen == '1' && record.frontGateClose == '1'"
                    color="#FF0000"
                    >点位异常</a-tag
                  >
                  <template v-else-if="column.dataIndex === 'warnLevel'">
                    <a-tag v-if="record.warnLevel == '101'" color="green">低风险</a-tag>
                    <a-tag v-else-if="record.warnLevel == '102'" color="#FF5812">一般风险</a-tag>
                    <a-tag v-else-if="record.warnLevel == '103'" color="#FF5812">较大风险</a-tag>
                    <a-tag v-else-if="record.warnLevel == '104'" color="#FF5812">重大风险</a-tag>
                    <a-tag v-else-if="record.warnLevel == '201'" color="#FF0000">报警</a-tag>
                    <a-tag v-else-if="record.warnLevel == '10000'" color="#FF5812">数据超限</a-tag>
                    <a-tag v-else-if="record.warnLevel == '1001'" color="default">网络中断</a-tag>
                    <a-tag v-else color="green">正常</a-tag>
                  </template>
                </template>
              </HistoryTable>
            </div>
          </a-tab-pane>
          <a-tab-pane key="4" tab="报警历史">
            <div class="tab-item" v-if="activeKey === '4'">
              <AlarmHistoryTable
                columns-type="alarm"
                :device-type="deviceType"
                :device-list-api="getTableList"
                designScope="alarm-history"
                :scroll="scroll"
              >
                <template #filterCell="{ column, record }">
                  <a-tag v-if="column.dataIndex === 'warnFlag'" :color="record.warnFlag == '0' ? 'green' : record.warnFlag == 1 ? '#FF5812' : 'gray'">
                    {{ record.warnFlag == '0' ? '正常' : record.warnFlag == 1 ? '报警' : record.warnFlag == 2 ? '断开' : '未监测' }}</a-tag
                  >
                  <a-tag v-if="column.dataIndex === 'netStatus'" :color="record.netStatus == '0' ? '#f00' : 'green'">{{
                    record.netStatus == '0' ? '断开' : '连接'
                  }}</a-tag>
                </template>
              </AlarmHistoryTable>
            </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="deviceType"
                :device-list-api="getTableList"
                designScope="operator_history"
                :scroll="scroll"
              />
            </div>
          </a-tab-pane>
        </a-tabs>
      </dv-border-box8>
    </div>
  </div>
  <div
    v-if="renderPlayer"
    ref="playerRef"
    style="
      z-index: 999;
      position: absolute;
      top: 100px;
      right: 15px;
      width: 100%;
      height: 800px;
      margin: auto;
      pointer-events: none;
      overflow-y: auto;
      flex-direction: column;
    "
  >
  </div>
  <HandleModal
    v-if="!globalConfig?.simulatedPassword"
    :modal-is-show="modalIsShow"
    :modal-title="modalTitle"
    :modal-type="modalType"
    @handle-ok="handleOK"
    @handle-cancel="handleCancel"
  />
  <DeviceBaseInfo @register="registerModal" :device-type="selectData['deviceType']" />
</template>

<script setup lang="ts">
  import { onBeforeUnmount, onUnmounted, onMounted, ref, reactive, nextTick, inject, unref } from 'vue';
  import MonitorTable from '../comment/MonitorTable.vue';
  import HistoryTable from '../comment/HistoryTable.vue';
  import AlarmHistoryTable from '../comment/AlarmHistoryTable.vue';
  import HandlerHistoryTable from '../comment/HandlerHistoryTable.vue';
  import HandleModal from './modal.vue';
  import DeviceBaseInfo from '../comment/components/DeviceBaseInfo.vue';
  import { deviceControlApi } from '/@/api/vent/index';
  import { message } from 'ant-design-vue';
  import { list, getTableList } from './deviceMonitor.api';
  import lodash from 'lodash';
  import { setDivHeight } from '/@/utils/event';
  import { BorderBox8 as DvBorderBox8 } from '@kjgl77/datav-vue3';
  import { useRouter } from 'vue-router';
  import { useModal } from '/@/components/Modal';
  import { useCamera } from '/@/hooks/system/useCamera';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { getDictItems } from '/@/api/common/api';

  const { hasPermission } = usePermission();

  const globalConfig = inject('globalConfig');

  const { currentRoute } = useRouter();
  const MonitorDataTable = ref();
  let contrlValue = '';
  const playerRef = ref();
  const renderPlayer = ref(true);
  const deviceType = ref('door');
  // const deviceType = ref('firedoor');
  const activeKey = ref('1'); // tab

  const scroll = reactive({
    y: 230,
  });
  const modelList = ref<{ text: string; value: string }[]>([]);
  const doorIsOpen = ref(false); //前门是否开启
  const modalIsShow = ref<boolean>(false); // 是否显示模态框
  const modalTitle = ref(''); // 模态框标题显示内容，根据设备操作类型决定
  const modalType = ref(''); // 模态框内容显示类型，设备操作类型

  const selectRowIndex = ref(-1); // 选中行
  const dataSource = ref([]);

  const deviceBaseList = ref([]); // 设备基本信息
  const [registerModal, { openModal, closeModal }] = useModal();

  const { getCamera, removeCamera } = useCamera();

  const tabChange = (activeKeyVal) => {
    activeKey.value = activeKeyVal;
    if (activeKeyVal == 1) {
      nextTick(() => {
        if (MonitorDataTable.value) MonitorDataTable.value.setSelectedRowKeys([selectData.deviceID]);
      });
    }
  };

  const initData = {
    deviceID: '',
    deviceType: '',
    strname: '',
    frontRearDP: '-', //压差
    // sourcePressure: '-', //气源压力
    runRoRecondition: null,
    autoRoManual: null,
    netStatus: '0', //通信状态
    frontGateOpen: '0',
    frontGateClose: '1',
    rearGateOpen: '0',
    rearGateClose: '1',
    midGateOpen: '0',
    midGateClose: '1',
    fault: '气源压力超限',
    masterComputer: 0,
    frontGateOpenCtrl: false,
    rearGateOpenCtrl: false,
    cameras: [],
  };

  // 监测数据
  const selectData = reactive(lodash.cloneDeep(initData));
  function deviceEdit(e: Event, type: string, record) {
    e.stopPropagation();
    openModal(true, {
      type,
      deviceId: record['deviceID'],
    });
  }
  // 获取设备基本信息列表
  function getDeviceBaseList() {
    getTableList({ pageSize: 1000 }).then((res) => {
      deviceBaseList.value = res.records;
    });
  }

  // https获取监测数据
  let timer: null | NodeJS.Timeout = null;
  async function getMonitor(flag?) {
    if (Object.prototype.toString.call(timer) === '[object Null]') {
      timer = await setTimeout(
        async () => {
          const res = await list({ devicetype: deviceType.value, pagetype: 'normal' });
          if (res.msgTxt && res.msgTxt[0]) {
            dataSource.value = res.msgTxt[0].datalist || [];
            dataSource.value.forEach((data: any) => {
              const readData = data.readData;
              data = Object.assign(data, readData);
            });
            if (dataSource.value.length > 0 && selectRowIndex.value == -1 && MonitorDataTable.value) {
              // 初始打开页面
              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, dataSource.value[selectRowIndex.value]);
            monitorAnimation(selectData);
            if (timer) {
              timer = null;
            }
            getMonitor();
          }
        },
        flag ? 0 : 1000
      );
    }
  }

  // 切换检测数据
  async function getSelectRow(selectRow, index) {
    if (!selectRow) return;
    selectRowIndex.value = index;
    const baseData: any = deviceBaseList.value.find((baseData: any) => baseData.id === selectRow.deviceID);
    Object.assign(selectData, initData, selectRow, baseData);
    doorDeviceState = 1; //记录设备状态，为了与下一次监测数据做比较
    isdoorOpenRunning = true; //开关门动作是否在进行
    await getCamera(selectRow.deviceID, playerRef, renderPlayer);
  }

  function playAnimation(handlerState, data: any = null) {
    const value = data;
    switch (handlerState) {
      case 1: // 打开前门
        modalTitle.value = '打开';
        modalType.value = '1';
        modalIsShow.value = true;
        break;
      case 2: // 关闭前门
        modalTitle.value = '关闭';
        modalType.value = '2';
        modalIsShow.value = true;
        break;
      case 7: // 控制模式切换
        modalTitle.value = '控制模式切换';
        modalType.value = '7';
        modalIsShow.value = true;
        break;
    }

    if (globalConfig?.simulatedPassword) {
      handleOK('', handlerState + '');
    }
    contrlValue = value;
  }

  function handleOK(passWord, handlerState) {
    if (!passWord && !globalConfig?.simulatedPassword) {
      message.warning('请输入密码');
      return;
    }
    if (isOpenRunning) {
      return;
    }
    const data = {
      deviceid: selectData.deviceID,
      devicetype: selectData.deviceType,
      paramcode: '',
      value: contrlValue,
      password: passWord || globalConfig?.simulatedPassword,
      masterComputer: selectData.masterComputer,
    };
    switch (handlerState) {
      case '1': // 打开前门
        if (selectData.doorOpen == '0' && selectData.doorClose == '1') {
          data.paramcode = 'frontGateOpen_S';
        }
        break;
      case '2': // 关闭前门
        if (selectData.doorOpen == '1' && selectData.doorClose == '0') {
          data.paramcode = 'frontGateClose_S';
        }
        break;
      case '7': // 远程与就地
        data.paramcode = 'autoRoManualControl';
        data.value = selectData.contrlMod != 'loopCtrl' ? contrlValue : '';
        selectData.autoRoManual = null;
    }

    if (data.paramcode) {
      deviceControlApi(data).then((res) => {
        // 模拟时开启
        if (res.success) {
          modalIsShow.value = false;
          if (globalConfig.History_Type == 'remote') {
            message.success('指令已下发至生产管控平台成功！');
          } else {
            message.success('指令已下发成功！');
          }
        } else {
          message.error(res.message);
        }
      });
    }
  }
  let isOpenRunning = false; //开关门动作是否在进行
  /** 开关门动画调用 */
  let isdoorOpenRunning = false; //开关门动作是否在进行
  // let isMidCloseRunning = false; //中间门动作是否在进行
  // 0 关闭 1 正在打开 2 打开 3正在关闭
  let doorDeviceState = 1; //记录设备状态，为了与下一次监测数据做比较
  function monitorAnimation(selectData) {
    const timeScale = 0.005;
    // 打开
    if (selectData.frontGateOpen == '1' && !isdoorOpenRunning) {
      isdoorOpenRunning = true;
      if (doorDeviceState != 1) {
        doorDeviceState = 1;
        doorIsOpen.value = true;
      }
    }
    // 关闭
    if (selectData.frontGateOpen == '0' && isdoorOpenRunning) {
      isdoorOpenRunning = false;
      if (doorDeviceState != 0) {
        doorDeviceState = 0;
        doorIsOpen.value = false;
      }
    }
  }

  function handleCancel() {
    modalIsShow.value = false;
    modalTitle.value = '';
    modalType.value = '';
    selectData.autoRoManual = null;
  }

  onMounted(async () => {
    const { query } = unref(currentRoute);
    if (query['deviceType']) deviceType.value = query['deviceType'] as string;
    modelList.value = await getDictItems('fireDoorModel');
  });

  onBeforeUnmount(() => {
    removeCamera(playerRef);
    getDeviceBaseList();
  });

  onUnmounted(() => {
    if (timer) {
      clearTimeout(timer);
      timer = undefined;
    }
  });
</script>
,
<style lang="less" scoped>
  @import '/@/design/vent/modal.less';
  .scene-box {
    .bottom-tabs-box {
      height: 300px;
    }
  }
  .button-box {
    border: none !important;
    height: 34px !important;

    &:hover {
      background: linear-gradient(#2cd1ff55, #1eb0ff55) !important;
    }

    &::before {
      height: 27px !important;
      background: linear-gradient(#1fa6cb, #127cb5) !important;
    }

    &::after {
      top: 35px !important;
    }
  }

  :deep(.@{ventSpace}-tabs-tabpane-active) {
    height: 100%;
  }

  ::-webkit-scrollbar-thumb {
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #4288a444;
  }
  :deep(.zxm-radio-disabled + span) {
    color: #fff !important;
  }
  :deep(.zxm-radio-disabled .zxm-radio-inner::after) {
    background-color: #127cb5 !important;
  }
</style>
