<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="deviceDetail" class="device-detail">
      <div id="deviceCard" class="device-card" style="z-index: -1; position: absolute">
        <div class="title">KJ-980-F矿用本安型监控分站</div>
        <div class="detail-box">
          <div class="left-box"></div>
          <div class="right-box">
            <div><span class="detail-title">规格型号：</span> <span>KJ-980-F</span></div>
            <div
              ><span class="detail-title">技术参数：</span>
              <span
                >380V，电机功率22kW,50Hz，B级绝缘，额定电流42.2A，效率90.5%，能效等级3，接法角型，2940r/min，轴承6311/CM 6211/CM，功率因数0.89</span
              ></div
            >
          </div>
        </div>
      </div>
    </div>
    <div id="damper3D" style="width: 100%; height: 100%; position: absolute; overflow: hidden"></div>
  </div>
  <div class="scene-box">
    <div class="top-box">
      <div class="top-center row">
        <div class="button-box" :class="{ 'button-disable': backDoorIsOpen }" @click="playAnimation(1)">打开前门</div>
        <div class="button-box" :class="{ 'button-disable': backDoorIsOpen }" @click="playAnimation(2)">关闭前门</div>
        <div class="button-box" :class="{ 'button-disable': frontDoorIsOpen }" @click="playAnimation(3)">打开后门</div>
        <div class="button-box" :class="{ 'button-disable': frontDoorIsOpen }" @click="playAnimation(4)">关闭后门</div>
        <div class="button-box" :class="{ 'button-disable': frontDoorIsOpen || backDoorIsOpen }" @click="playAnimation(5)">打开前后门</div>
        <div
          class="button-box"
          :class="{ 'button-disable': (frontDoorIsOpen && !backDoorIsOpen) || (backDoorIsOpen && !frontDoorIsOpen) }"
          @click="playAnimation(6)"
          >关闭前后门</div
        >
        <!-- <div class="button-box" @click="enterMY">漫游</div> -->
      </div>
      <div class="top-right row">
        <div class="control-type row">
          <div class="control-title">控制模式：</div>
          <a-radio-group v-model:value="selectData.masterComputer" @change="changeType">
            <a-radio :value="`0`">就地</a-radio>
            <a-radio :value="`1`">远程</a-radio>
          </a-radio-group>
        </div>
        <div class="run-type row">
          <div class="control-title">运行状态：</div>
          <a-radio-group v-model:value="controlType">
            <a-radio :value="`1`">检修</a-radio>
          </a-radio-group>
        </div>
        <div class="run-state row">
          <div class="control-title">网络状态：</div>
          <a-radio-group v-model:value="selectData.netStatus">
            <a-radio :value="`1`">运行</a-radio>
          </a-radio-group>
        </div>
      </div>
    </div>
    <div class="title-text">
      {{ selectData.stationname }}
    </div>
    <div class="bottom-tabs-box">
      <a-tabs class="tabs-box" v-model:activeKey="activeKey" @change="tabChange">
        <a-tab-pane key="1" tab="实时监测">
          <MonitorTable
            class="monitor-table"
            columnsType="gate_monitor"
            :dataSource="dataSource"
            design-scope="gate-monitor"
            @selectRow="getSelectRow"
            title="风门监测"
          >
            <template #filterCell="{ column, record }">
              <template v-if="record.frontGateOpenCtrl">
                <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'" color="processing">打开</a-tag>
              </template>
              <template v-else>
                <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="default">打开</a-tag>
              </template>
              <template v-if="record.rearGateOpenCtrl">
                <a-tag v-if="column.dataIndex === 'rearGateOpen' && record.rearGateOpen == 0 && record.rearGateClose == 0" color="red">正在打开</a-tag>
                <a-tag v-else-if="column.dataIndex === 'rearGateOpen'" color="processing">打开</a-tag>
              </template>
              <template v-else>
                <a-tag v-if="column.dataIndex === 'rearGateOpen' && record.rearGateOpen == 0 && record.rearGateClose == 0" color="red">正在关闭</a-tag>
                <a-tag v-else-if="column.dataIndex === 'rearGateOpen' && record.rearGateOpen == 0 && record.rearGateClose == 1" color="default">关闭</a-tag>
                <a-tag v-else-if="column.dataIndex === 'rearGateOpen' && record.rearGateOpen == 1 && record.rearGateClose == 0" color="default">打开</a-tag>
              </template>
              
              <a-tag v-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 ? 'default' : 'green'">{{
                record.netStatus == 0 ? '断开' : '连接'
              }}</a-tag>
            </template>
          </MonitorTable>
        </a-tab-pane>
        <a-tab-pane key="2" tab="实时曲线图" force-render>
          <div class="tab-item" v-if="activeKey === '2'">
            <DeviceEcharts
              chartsColumnsType="gate_chart"
              xAxisPropType="strname"
              :dataSource="dataSource"
              height="100%"
              :chartsColumns="chartsColumns"
              :device-list-api="list"
              device-type="gate"
            />
          </div>
        </a-tab-pane>
        <a-tab-pane key="3" tab="历史数据">
          <div class="tab-item">
            <HistoryTable columns-type="gate_history" device-type="gate" :device-list-api="baseList" designScope="gate-history" />
          </div>
        </a-tab-pane>
        <a-tab-pane key="4" tab="报警历史">
          <div class="tab-item">
            <AlarmHistoryTable columns-type="alarm_history" device-type="gate" :device-list-api="baseList" designScope="alarm-history" />
          </div>
        </a-tab-pane>
        <a-tab-pane key="5" tab="操作历史">
          <div class="tab-item">
            <HandlerHistoryTable columns-type="alarm_history" device-type="fanlocal" :device-list-api="baseList" designScope="alarm-history" />
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>
  </div>
  <div style="z-index: -1; position: absolute; top: 50px; right: 10px; width: 300px; height: 280px; margin: auto" class="palyer1">
    <LivePlayer id="fm-player1" ref="player1" :videoUrl="flvURL1()" muted live loading controls />
    <LivePlayer id="fm-player2" ref="player2" :videoUrl="flvURL1()" muted live loading controls style="margin-top: 10px" />
  </div>
  <!-- <a-modal v-model:visible="modalIsShow" :title="modalTitle" @ok="handleOk">
    <div class="modal-container">
      <div class="vent-flex-row">
        <ExclamationCircleFilled style="color: #ffb700; font-size: 30px" />
        <div class="warning-text">您是否要进行{{ modalTitle }}操作？</div>
      </div>
    </div>
  </a-modal> -->
  <HandleModal :modal-is-show="modalIsShow" :modal-title="modalTitle" :modal-type="modalType" @handle-ok="handleOK" @handle-cancel="handleCancel" />
</template>

<script setup lang="ts">
  import LivePlayer from '@liveqing/liveplayer-v3';
  import { onBeforeMount, onBeforeUnmount, onUnmounted, onMounted, ref, reactive, toRaw, nextTick } from 'vue';
  import DeviceEcharts from '../comment/DeviceEcharts.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 { initWebSocket, getRecordList } from '/@/hooks/web/useVentWebSocket';
  import { mountedThree, addFmText, play, destroy, initOpenState, deviceDetailCard } from './gate.threejs';
  import { deviceControlApi } from '/@/api/vent/index';
  import { message } from 'ant-design-vue';
  import { list, getTableList } from './gate.api';
  import { chartsColumns } from './gate.data';
  import lodash from 'lodash';

  const player1 = ref(null);
  const player2 = ref(null);

  const activeKey = ref('1');
  const loading = ref(false);

  const frontDoorIsOpen = ref(false); //前门是否开启
  const backDoorIsOpen = ref(false); //后门是否开启

  const modalIsShow = ref<boolean>(false); // 是否显示模态框
  const modalTitle = ref(''); // 模态框标题显示内容，根据设备操作类型决定
  const modalType = ref(''); // 模态框内容显示类型，设备操作类型

  const selectRowIndex = ref(0);
  const dataSource = ref([]);

  const deviceBaseList = ref([]);
  //  webSocket 请求 实时监测数据
  // const dataSource:any = computed(() => {
  //   const data = [...getRecordList()] || []
  //
  //   Object.assign(selectData, toRaw(data[selectRowIndex.value]))
  //
  //   addFmText(selectData)
  //
  //   return data;
  // });

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

  const tabChange = (activeKeyVal) => {
    activeKey.value = activeKeyVal;
  };
  const initData = {
    deviceID: '',
    deviceType: '',
    strname: '',
    frontRearDP: '-', //压差
    sourcePressure: '-', //气源压力
    netStatus: '0', //通信状态
    frontGateOpen: '0',
    rearGateOpen: '0',
    fault: '气源压力超限',
    masterComputer: 0,
  };
  // 监测数据
  const selectData = reactive(lodash.cloneDeep(initData));

  // 获取设备基本信息列表
  const getDeviceBaseList = () => {
    getTableList({ pageSize: 1000 }).then((res) => {
      deviceBaseList.value = res.records;
    });
  };

  // https获取监测数据
  let timer: null | NodeJS.Timeout = null;
  const getMonitor = () => {
    if (Object.prototype.toString.call(timer) === '[object Null]') {
      timer = setTimeout(() => {
        list({ devicetype: 'gate', pagetype: 'normal' }).then((res) => {
          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 > selectRowIndex.value) {
              const data: any = toRaw(dataSource.value[selectRowIndex.value]); //maxarea
              Object.assign(selectData, data);
              addFmText(data);
              monitorAnimation(data)
              if (timer) {
                timer = null;
              }
              getMonitor();
            }
          }
        });
      }, 1000);
    }
  };

  // 切换检测数据
  const getSelectRow = async (selectRow, index) => {
    if (!selectRow) return;
    loading.value = true;
    selectRowIndex.value = index;
    const baseData: any = deviceBaseList.value.find((baseData: any) => baseData.id === selectRow.deviceID);
    Object.assign(selectData, initData, selectRow, baseData);
    // selectData = selectRow;
    // frontDoorIsOpen.value = selectData.frontGateOpen === '1';
    // backDoorIsOpen.value = selectData.rearGateOpen === '1';
    initOpenState(selectData)?.then(() => {
      loading.value = false;
    });
  };

  // 播放动画
  const playAnimation = (handlerState) => {
    switch (handlerState) {
      case 1: // 打开前门
        if (!frontDoorIsOpen.value && !backDoorIsOpen.value) {
          modalTitle.value = '打开前门';
          modalType.value = '1';
          modalIsShow.value = true;
        }
        break;
      case 2: // 关闭前门
        if (frontDoorIsOpen.value && !backDoorIsOpen.value) {
          modalTitle.value = '关闭前门';
          modalType.value = '2';
          modalIsShow.value = true;
        }
        break;
      case 3: // 打开后门
        if (!backDoorIsOpen.value && !frontDoorIsOpen.value) {
          modalTitle.value = '打开后门';
          modalType.value = '3';
          modalIsShow.value = true;
        }
        break;
      case 4: // 关闭后门
        if (backDoorIsOpen.value && !frontDoorIsOpen.value) {
          modalTitle.value = '关闭后门';
          modalType.value = '4';
          modalIsShow.value = true;
        }
        break;
      case 5: // 打开前后门
        if (!frontDoorIsOpen.value && !backDoorIsOpen.value) {
          modalTitle.value = '打开前后门';
          modalType.value = '5';
          modalIsShow.value = true;
        }
        break;
      case 6: // 关闭前后门
        if (frontDoorIsOpen.value && backDoorIsOpen.value) {
          modalTitle.value = '关闭前后门';
          modalType.value = '6';
          modalIsShow.value = true;
        }
        break;
    }
  };
  

  const handleOK = (passWord, handlerState) => {
    if (passWord !== '123456') {
      message.warning('密码不正确，请重新输入');
      return;
    }

    if(isFrontRunning && (handlerState == 2 || handlerState == 1 || handlerState == 5 || handlerState == 6)){
      return
    }

    if (isRearRunning && (handlerState == 3 || handlerState == 4 || handlerState == 5 || handlerState == 6)) {
      return
    }
    
    const data = {
      deviceid: selectData.deviceID,
      devicetype: selectData.deviceType,
      paramcode: '',
      value: null,
      masterComputer: selectData.masterComputer,
    };
    let handler = () => {};

    switch (handlerState) {
      case '1': // 打开前门
        if (!frontDoorIsOpen.value && !backDoorIsOpen.value) {
          handler = () => {
            frontDoorIsOpen.value = true;
          };
          data.paramcode = 'frontGateOpen_S';
        }
        break;
      case '2': // 关闭前门
        if (frontDoorIsOpen.value && !backDoorIsOpen.value) {
          handler = () => {
            frontDoorIsOpen.value = false;
          };
          data.paramcode = 'frontGateClose_S';
        }
        break;
      case '3': // 打开后门
        if (!backDoorIsOpen.value && !frontDoorIsOpen.value) {
          handler = () => {
            backDoorIsOpen.value = true;
          };
          data.paramcode = 'rearGateOpen_S';
        }
        break;
      case '4': // 关闭后门
        if (backDoorIsOpen.value && !frontDoorIsOpen.value) {
          handler = () => {
            backDoorIsOpen.value = false;
          };
          data.paramcode = 'rearGateClose_S';
        }
        break;
      case '5': // 打开前后门
        if (!frontDoorIsOpen.value && !backDoorIsOpen.value) {
          handler = () => {
            frontDoorIsOpen.value = true;
            backDoorIsOpen.value = true;
          };
          data.paramcode = 'sameTimeOpen';
        }
        break;
      case '6': // 关闭前后门
        if (frontDoorIsOpen.value && backDoorIsOpen.value) {
          handler = () => {
            frontDoorIsOpen.value = false;
            backDoorIsOpen.value = false;
          };
          data.paramcode = 'sameTimeClose';
        }
        break;
    }
    if (data.paramcode) {
      deviceControlApi(data)
        .then((res) => {
          // 模拟时开启
          // if (res.success) {
          //   modalIsShow.value = false;
          //   modalTitle.value = '';
          //   modalType.value = '';
          //   handler();
          //   play(Number(handlerState));
          // }
        })
    }
  };

  /** 开关门动画调用 */
  let isFrontRunning = false //开关门动作是否在进行
  let isRearRunning = false //开关门动作是否在进行
  let frontDeviceState = 0 //记录设备状态，为了与下一次监测数据做比较
  let rearDeviceState = 0 //记录设备状态，为了与下一次监测数据做比较  
  //backDoorIsOpen frontDoorIsOpen
  const monitorAnimation = (selectData) => {
    debugger
    
    const timeScale = 0.0003
    if (selectData.frontGateOpenCtrl) {

      if (selectData.frontGateOpen == 0 && selectData.frontGateClose == 0) {
        //打开前门1
        
        
        if(!isFrontRunning){
          frontDoorIsOpen.value = true
          backDoorIsOpen.value = true
          isFrontRunning = true
          play(1, timeScale)
          frontDeviceState = 1
        }
        
      }
      if (selectData.frontGateOpen == 1 && selectData.frontGateClose == 0) {
        isFrontRunning = false
        if (frontDeviceState != 1) {
          play(1)
          frontDeviceState = 1
          frontDoorIsOpen.value = false
          backDoorIsOpen.value = true
        }
      }
    } else {
      if (selectData.frontGateOpen == 0 && selectData.frontGateClose == 0) {
        //关闭前门
        
        if(!isFrontRunning){
          isFrontRunning = true
          play(2, timeScale)
          frontDeviceState = 2
          frontDoorIsOpen.value = true
          backDoorIsOpen.value = true
        }
        
      }
      if (selectData.frontGateClose == 1 && selectData.frontGateOpen == 0) {
        isFrontRunning = false
        if (frontDeviceState == 1) {
          play(2)
          frontDeviceState = 2
          frontDoorIsOpen.value = false
          // backDoorIsOpen.value = false
        }
      }
    }
    
    if (selectData.rearGateOpenCtrl) {
      if (selectData.rearGateOpen == 0 && selectData.rearGateClose == 0) {
        //打开后门
        if(!isRearRunning){
          isRearRunning = true
          play(3, timeScale)
          rearDeviceState = 3
          frontDoorIsOpen.value = true
          backDoorIsOpen.value = true
        }
        
      }
      if (selectData.rearGateOpen == 1 && selectData.rearGateClose == 0) {
        isRearRunning = false
        
        if (rearDeviceState != 3) {
          rearDeviceState = 3
          play(3)
          backDoorIsOpen.value = false
          frontDoorIsOpen.value = true
        }
      }
    } else {

      if (selectData.rearGateOpen == 0 && selectData.rearGateClose == 0) {
        //关闭后门
        
        
        if(!isRearRunning){
          isRearRunning = true
          play(4, timeScale)
          rearDeviceState = 4
          frontDoorIsOpen.value = true
          backDoorIsOpen.value = true
        }
        
      }
      if (selectData.rearGateClose == 1 && selectData.rearGateOpen == 0) {
        isRearRunning = false
        
        if (rearDeviceState == 3) {
          rearDeviceState = 4
          play(4)
          // frontDoorIsOpen.value = false
          backDoorIsOpen.value = false
        }
      }
    }
    if(!(selectData.frontGateOpen == 0 && selectData.frontGateClose == 0 && selectData.rearGateOpen == 0 && selectData.rearGateClose == 0)) {
      if (selectData.frontGateOpenCtrl && selectData.rearGateOpenCtrl && selectData.frontGateOpen == 1 && selectData.rearGateOpen == 1) {
        frontDoorIsOpen.value = true
        backDoorIsOpen.value = true
      }
      if (!selectData.frontGateOpenCtrl && !selectData.rearGateOpenCtrl && selectData.frontGateClose == 1 && selectData.rearGateClose == 1) {
        frontDoorIsOpen.value = false
        backDoorIsOpen.value = false
      }
    }
    

    // if (!selectData.frontGateOpenCtrl && selectData.rearGateOpenCtrl) {
    //   frontDoorIsOpen.value = true
    //   backDoorIsOpen.value = false
    // }

    // if (selectData.frontGateOpenCtrl && !selectData.rearGateOpenCtrl) {
    //   frontDoorIsOpen.value = false
    //   backDoorIsOpen.value = true
    // }
    
    // if (frontDeviceState == 1 || frontDeviceState == 2) {
    //   frontDoorIsOpen.value = false
    //   backDoorIsOpen.value = true
    // } else if (rearDeviceState == 3 || rearDeviceState == 4) {
    //   frontDoorIsOpen.value = true
    //   backDoorIsOpen.value = false
    // } else {
    //   frontDoorIsOpen.value = false
    //   backDoorIsOpen.value = false
    // }
    // if(selectData.frontGateOpenCtrl && selectData.rearGateOpenCtrl){
    //   if (selectData.frontGateOpen == 0 && selectData.frontGateClose == 0 && !isFrontRunning && selectData.rearGateOpen == 0 && selectData.rearGateClose == 0 && !isRearRunning) {
    //     //打开前后门
    //     frontDoorIsOpen.value = true
    //     backDoorIsOpen.value = true
    //   }
    //   if (selectData.frontGateOpen == 1 && selectData.frontGateClose == 0 && selectData.rearGateOpen == 1 && selectData.rearGateClose == 0) {
    //     frontDoorIsOpen.value = true
    //     backDoorIsOpen.value = true
    //   }
    // }
    // if(!selectData.frontGateOpenCtrl && !selectData.rearGateOpenCtrl){
    //   if (selectData.frontGateOpen == 0 && selectData.frontGateClose == 0 && !isFrontRunning && selectData.rearGateOpen == 0 && selectData.rearGateClose == 0 && !isRearRunning) {
    //     //打开前后门
    //     frontDoorIsOpen.value = true
    //     backDoorIsOpen.value = true
    //   }
    //   if (selectData.frontGateOpen == 0 && selectData.frontGateClose == 1 && selectData.rearGateOpen == 0 && selectData.rearGateClose == 1) {
    //     frontDoorIsOpen.value = false
    //     backDoorIsOpen.value = false
    //   }
    // }
  }
  
  const handleCancel = () => {
    modalIsShow.value = false;
    modalTitle.value = '';
    modalType.value = '';
  };

  // 远程、就地切换
  const changeType = () => {
    const data = {
      deviceid: selectData.deviceID,
      devicetype: selectData.deviceType,
      paramcode: 'masterComputerControl',
      value: selectData.masterComputer,
    };
    deviceControlApi(data).then(() => {
      message.success('状态切换成功！');
    });
  };

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

  // 视频播放
  const addPlayVideo = () => {
    if (player1.value && player2.value && player1.value?.play && player2.value?.play) {
      // player1.value.setMuted(false);
      // player2.value.setMuted(false);
      player1.value.play();
      player2.value.play();
      document.body.removeEventListener('mousedown', addPlayVideo);
    }
  };

  const handleOk = (e: MouseEvent) => {
    //
  };
  

  onBeforeMount(() => {
    const sendVal = JSON.stringify({ pagetype: 'normal', devicetype: 'gate', orgcode: '', ids: '', systemID: '' });
    initWebSocket(sendVal);
  });

  onMounted(() => {
    loading.value = true;
    mountedThree(player1.value, player2.value).then(() => {
      nextTick(() => {
        getMonitor();
        addFmText(selectData);
        deviceDetailCard();
      });
      loading.value = false;
    });
    document.body.addEventListener('mousedown', addPlayVideo, false);
  });
  onBeforeUnmount(() => {
    getDeviceBaseList();
  });
  onUnmounted(() => {
    if (timer) {
      clearTimeout(timer);
      timer = undefined;
    }
    destroy();
  });
</script>

<style lang="less" scoped>
  @import '/@/design/vent/modal.less';
  .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(.ant-tabs-tabpane-active) {
    overflow: auto;
  }
</style>
