<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="window3D" style="width: 100%; height: 100%; position: absolute; overflow: hidden"> </div>
    <!-- <div id="damper3DCSS" v-show="!loading" style="width: 100%; height: 100%; top:0; left: 0; position: absolute; overflow: hidden;">
      <div>
        <div ref="elementContent" class="elementContent">
          <p><span class="data-title">压力(Pa)：</span>{{selectData.frontRearDP}}</p>
          <p><span class="data-title">动力源压力(MPa)：</span>{{selectData.sourcePressure}}</p>
          <p><span class="data-title">故障诊断：</span>
            <i
              :class="{'state-icon': true, 'open': selectData.messageBoxStatus, 'close': !selectData.messageBoxStatus}"
            ></i>{{selectData.fault}}</p>
        </div>
      </div>
    </div> -->
  </div>
  <div class="scene-box">
    <div class="top-box">
      <div class="top-center row">
        <!-- <div class="button-box" @click="start(0)">复位</div> -->
        <!-- <div class="button-box" @click="testPlay()">自测动画</div> -->
        <div class="button-box" @click="testPlay('up')">上</div>
        <div class="button-box" @click="testPlay('center')">中</div>
        <div class="button-box" @click="testPlay('down')">下</div>
        <div class="button-box" @click="testPlay('reset')">复位</div>
      </div>
      <div class="top-right row">
        <div class="control-type row">
          <div class="control-title">控制模式：</div>
          <a-radio-group v-model:value="controlType">
            <a-radio :value="1">就地</a-radio>
            <a-radio :value="2">远程</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="controlType">
            <a-radio :value="1">运行</a-radio>
          </a-radio-group>
        </div>
      </div>
    </div>
    <div class="title-text">
      {{ selectData.strname }}
    </div>
    <div class="bottom-tabs-box">
      <div class="tabs-button-group">
        <a-button class="tabs-button" type="primary" @click="openModel">一键测风</a-button>
        <!-- <a-button class="tabs-button" type="primary" @click="exportExcel()">导出报表</a-button> -->
      </div>
      <a-tabs class="tabs-box" v-model:activeKey="activeKey" @change="tabChange">
        <a-tab-pane key="1" tab="实时监测">
          <MonitorTable
            columnsType="windrect_monitor"
            :dataSource="dataSource"
            design-scope="windrect-monitor"
            @selectRow="getSelectRow"
            title="测风装置监测"
          >
            <template #filterCell="{ column, record }">
              <a-tag v-if="column.dataIndex === 'sign'" :color="record.sign == 0 ? '#95CF65' : record.sign == 1 ? '#4590EA' : '#9876AA'">{{
                record.sign == 0 ? '高位' : record.sign == 1 ? '中位' : '低位'
              }}</a-tag>
              <template v-if="record && column && column.dataIndex === 'isRun' && record.isRun">
                <a-tag v-if="record.isRun == -2 || record.isRun == -1" :color="record.isRun == -2 ? '#95CF65' : '#ED5700'">{{
                  record.isRun == -2 ? '空闲' : '等待'
                }}</a-tag>
                <a-tag v-else-if="record.isRun == 100" color="#4693FF">完成</a-tag>
                <Progress v-else :percent="Number(record.isRun)" size="small" status="active" />
              </template>
              <!-- <a-tag v-if="column.dataIndex === 'sign'" :color="record.sign == 0 ? '#95CF65' : record.sign == 1 ? '#4590EA' : '#9876AA'">{{
                record.sign == 0 ? '高位' : record.sign == 1 ? '中位' : '低位'
              }}</a-tag>
              <template v-if="record && column && column.dataIndex === 'isRun' && record.isRun">
                <a-tag v-if="record.isRun == -2 || record.isRun == -1" :color="record.isRun == -2 ? '#95CF65' : '#ED5700'">{{
                  record.isRun === -2 ? '空闲' : '等待'
                }}</a-tag>
                <Progress v-else :percent="Number(record.isRun)" size="small" status="active" />
              </template> -->
            </template>
          </MonitorTable>
        </a-tab-pane>
        <a-tab-pane key="2" tab="实时曲线图" force-render>
          <div class="tab-item" v-if="activeKey === '2'">
            <DeviceEcharts
              chartsColumnsType="windrect_chart"
              xAxisPropType="strname"
              :dataSource="dataSource"
              height="100%"
              :chartsColumns="chartsColumns"
              :device-list-api="baseList"
              device-type="windrect"
            />
          </div>
        </a-tab-pane>
        <a-tab-pane key="3" tab="历史数据">
          <div class="tab-item">
            <HistoryTable columns-type="windrect_history" device-type="windrect" :device-list-api="baseList" designScope="windrect-history" />
          </div>
        </a-tab-pane>
        <a-tab-pane key="4" tab="报警历史">
          <div class="tab-item">
            <AlarmHistoryTable columns-type="alarm_history" device-type="windrect" :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-tab-pane key="6" tab="测风结果">
          <ResultTable v-if="activeKey == 6" deviceType="windrect_list" />
        </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="palyer">
    <LivePlayer id="cf-player1" ref="player1" :videoUrl="flvURL1()" muted live loading controls />
    <LivePlayer id="cf-player2" ref="player2" :videoUrl="flvURL1()" muted live loading controls style="margin-top: 10px" />
  </div>

  <BasicModal v-bind="$attrs" @register="registerModal" title="一键测风" width="900px" @ok="handleOk" @cancel="handleCancel">
    <div class="head-line">
      <div class="vent-flex-row">
        <span>同时运行数量：</span>
        <a-input-number v-model:value="runNum" :min="1" :max="10" />
      </div>
      <div class="vent-flex-row">
        <div v-for="(criticalPath, index) in criticalPathList" :key="index" class="button-box" @click="selectCriticalPath(criticalPath.id)">{{
          criticalPath.systemname
        }}</div>
      </div>
    </div>
    <div>
      <ModalTable ref="modalTable" deviceType="windrect_list" />
    </div>
  </BasicModal>
</template>

<script setup lang="ts">
  import DeviceEcharts from '../comment/DeviceEcharts.vue';
  import { onBeforeMount, computed, ComputedRef, ref, onMounted, onUnmounted, reactive, toRaw, toRef, toRefs, Ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import MonitorTable from '../comment/MonitorTable.vue';
  import ModalTable from './components/modalTable.vue';
  import ResultTable from './components/resultTable.vue';
  import HistoryTable from '../comment/HistoryTable.vue';
  import AlarmHistoryTable from '../comment/AlarmHistoryTable.vue';
  import HandlerHistoryTable from '../comment/HandlerHistoryTable.vue';
  import { initWebSocket, getRecordList } from '/@/hooks/web/useVentWebSocket';
  import { deviceControlApi } from '/@/api/vent/index';
  import { mountedThree, destroy, addFmText, play, setModelType } from './windrect.threejs';
  import LivePlayer from '@liveqing/liveplayer-v3';
  import { list, pathList, deviceList, testWind } from './windrect.api';
  import { list as baseList } from '../../deviceManager/windfindingTabel/windfinding.api';
  import { message, Progress } from 'ant-design-vue';
  import { chartsColumns } from './windrect.data';

  const modalTable = ref();
  const runNum = ref(5); //设备运行数量
  const criticalPathList = ref([]);
  const player1 = ref<HTMLDivElement | null>(null);
  const player2 = ref<HTMLDivElement | null>(null);
  const activeKey = ref('1');
  const loading = ref(false);
  // 默认初始是第一行
  const selectRowIndex = ref(0);
  // 监测数据
  const selectData = reactive({
    deviceID: '',
    deviceType: '',
    strname: '',
    dataDh: '-', //压差
    dataDtestq: '-', //测试风量
    sourcePressure: '-', //气源压力
    dataDequivalarea: '-',
    netStatus: '0', //通信状态
    fault: '气源压力超限',
    sign: -1
  });

  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 dataSource = computed(() => {
  //   const data = [...getRecordList()] || [];
  //   Object.assign(selectData, toRaw(data[selectRowIndex.value]));
  //   addFmText(selectData);
  //   return data;
  // });

  const dataSource = ref([]);

  const tabChange = (activeKeyVal) => {
    activeKey.value = activeKeyVal;
  };

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

  // https获取监测数据
  let timer: null | NodeJS.Timeout = null;
  const getMonitor = () => {
    if (Object.prototype.toString.call(timer) === '[object Null]') {
      timer = setTimeout(() => {
        list({ devicetype: 'windrect', pagetype: 'normal' }).then((res) => {
          dataSource.value = res.msgTxt[0].datalist || [];
          dataSource.value.forEach((data: any) => {
            const readData = data.readData;
            data = Object.assign(data, readData);
          });
          const data: any = toRaw(dataSource.value[selectRowIndex.value]); //maxarea
          Object.assign(selectData, data);
          addFmText(selectData);
          // 根据3个点位分别执行动画

          if(data.deviceType == "windrect_fold"){
            if (selectData['apparatusRun'] == 1) {
              const flag = selectData.sign == 0 ? 'up' : selectData.sign == 1 ? 'center' : selectData.sign == 2 ? 'down' : null
              if (flag) play(flag);
            } else {
              const flag = selectData.sign == 1 ? 'center' : selectData.sign == 2 ? 'down' : null
              if (flag) play(flag, true);
            }
          }
          
          if(data.deviceType == "windrect_rect"){
            if (selectData['apparatusRun'] == 1) {
              const flag = selectData.sign == 0 ? 'center' : selectData.sign == 1 ? 'down' : selectData.sign == 2 ? 'up' : null
              if (flag) play(flag);
            } else {
              const flag = selectData.sign == 1 ? 'center' : selectData.sign == 2 ? 'down' : selectData.sign == 0 ? 'up': null
              if (flag) play(flag, true);
            }
          }

          if (data.deviceType == "windrect_ds") {
            if (selectData['apparatusRun'] == 1) {
              play('start')
            }else{
              play('start', true)
            }
          }

          if (timer) {
            timer = null;
          }
          getMonitor();
        });
      }, 1000);
    }
  };

  // 自测动画方法
  const testPlay = (flag) => {
    play(flag);
    // play('start')
    // setTimeout(() => {
    //   play('up')
    // }, 0)
    // setTimeout(() => {
    //   play('center')
    // }, 10000)
    // setTimeout(() => {
    //   play('down')
    // }, 40000)
    // setTimeout(() => {
    //   play('up')
    // }, 60000)
  };

  // 切换检测数据
  const getSelectRow = async (selectRow, index) => {
    loading.value = true;
    selectRowIndex.value = index;
    // Object.assign(selectData, selectRow);
    const type = selectRow.deviceType == 'windrect_rect' ? 'lmWindRect' : selectRow.deviceType == 'windrect_fold' ? 'zdWindRect' : 'dsWindRect'; 
    // const type = selectRowIndex.value >= 1 ? 'lmWindRect' : selectRowIndex.value <= 3 ? 'zdWindRect' : 'dsWindRect';
    await setModelType(type);
    loading.value = false;
  };

  const start = (flag) => {
    const data = {
      deviceid: selectData.deviceID,
      devicetype: selectData.deviceType,
      paramcode: flag == 1 ? 'testStart' : '',
    };
    deviceControlApi(data).then((res) => {
      if (res.success) {
        //
      }
    });
  };

  const addPlayVideo = (event) => {
    event.preventDefault();
    if (player1.value.play && player2.value.play) {
      player1.value.play();
      player2.value.play();
      document.body.removeEventListener('mousedown', addPlayVideo);
    }
  };

  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner();

  /* 一键测风 */
  const handleOk = () => {
    const ids = toRaw(modalTable.value.selectedRowKeys);
    testWind({ ids: ids, maxnum: runNum.value }).then((res) => {
      message.success(res);
      setModalProps({ visible: false });
      modalTable.value.clearSelectedRowKeys();
    });
  };

  /* 打开一键测风弹窗 */
  const openModel = () => {
    setModalProps({ visible: true });
  };

  const exportExcel = (id) => {
    exportXls({ testid: id })
  }

  /* 关闭一键测风弹窗 */
  const handleCancel = () => {
    setModalProps({ visible: false });
    modalTable.value.clearSelectedRowKeys();
  };

  const getPathList = async () => {
    const pathArr = await pathList({});
    criticalPathList.value = pathArr.records.filter((item) => {
      return item.strsystype == 3;
    });
  };
  /* 根据路线选择测风装置 */
  const selectCriticalPath = (pathId) => {
    deviceList({ deviceType: 'wind', sysId: pathId }).then((res) => {
      const ids: string[] = [];
      res.records.forEach((item) => {
        ids.push(item.id);
      });
      if (modalTable.value) modalTable.value.setSelectedRowKeys(ids);
    });
  };

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

  onMounted(() => {
    loading.value = true;
    mountedThree(player1.value, player2.value).then(async () => {
      getMonitor();
      // loading.value = false;
    });
    document.body.addEventListener('mousedown', addPlayVideo, false);
  });

  onUnmounted(() => {
    destroy();
    if (timer) {
      clearTimeout(timer);
      timer = undefined;
    }
  });
</script>
<style scoped lang="less">
  @import '/@/design/vent/modal.less';
  :deep(.ant-tabs-tabpane-active) {
    overflow: auto;
  }
  .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 15px;
      cursor: pointer;
      pointer-events: auto;
      &: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);
      }
    }
  }
  .ant-tabs-tabpane {
    overflow-y: auto !important;
  }
</style>
