<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" v-show="!loading" 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-left row"> 井下风窗远程集中管理 </div>
      <div class="top-center row">
        <div class="input-box">
          <span class="input-title">风窗面积：</span>
          <a-input-number placeholder="0" :min="0" :max="90" :step="1" v-model:value="windowAngle" />
        </div>
        <div class="button-box" @click="setArea(1)">设定前窗面积</div>
        <div class="button-box" @click="setArea(2)">设定后窗面积</div>
        <div class="button-box" @click="setArea(2)" style="display: none">设定风窗面积</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-box"> 2-2煤主辅三联巷自动风窗 </div>
    <div class="tabs-box">
      <a-tabs v-model:activeKey="activeKey" @change="tabChange">
        <a-tab-pane key="1" tab="实时监测">
          <MonitorTable columnsType="window_monitor" :dataSource="dataSource" @selectRow="getSelectRow" design-scope="window-monitor" title="风窗监测" />
        </a-tab-pane>
        <a-tab-pane key="2" tab="实时曲线图" force-render>
          <div class="tab-item" v-if="activeKey === '2'">
            <BarMulti :chartData="dataSource" xAxisPropType="strname" :propTypeArr="propTypeArr" height="100%" :option="option" />
          </div>
        </a-tab-pane>
        <a-tab-pane key="3" tab="历史数据">
          <div class="tab-item"> Content of Tab Pane 2 </div>
        </a-tab-pane>
        <a-tab-pane key="4" tab="操作历史">
          <div class="tab-item"> Content of Tab Pane 2 </div>
        </a-tab-pane>
        <a-tab-pane key="5" tab="实时报警">
          <div class="tab-item"> Content of Tab Pane 2 </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="fc-player1" ref="player1" :videoUrl="flvURL1()" muted live loading controls />
    <LivePlayer id="fc-player2" ref="player2" :videoUrl="flvURL1()" muted live loading controls style="margin-top: 10px" />
  </div>
</template>

<script setup lang="ts">
  import '/@/assets/less/modal.less';
  import BarMulti from '/@/components/chart/BarMulti.vue';
  import { onBeforeMount, computed, ref, onMounted, nextTick, onUnmounted, reactive, toRaw, Ref } from 'vue';
  import MonitorTable from '../comment/MonitorTable.vue';
  import { initWebSocket, getRecordList } from '/@/hooks/web/useVentWebSocket';
  import { mountedThree, destroy, addFmText, play, setModelType } from './window.threejs';
  import { list, getTableList } from './window.api';
  import { deviceControlApi } from '/@/api/vent/index';
  import lodash from 'lodash';
  import LivePlayer from '@liveqing/liveplayer-v3';

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

  const deviceBaseList = ref([]);
  const activeKey = ref('1');
  const loading = ref(false);
  const windowAngle = ref(0);

  const rotationParam = {
    frontDeg0: 0, // 前门初始
    frontDeg1: windowAngle.value, // 前门目标
    backDeg0: 0, // 后门初始
    backDeg1: windowAngle.value, // 后门目标
  };

  const option = {
    grid: {
      show: false,
      left: 60,
      right: 50,
      bottom: 30,
    },
    xAxis: {
      axisLine: {
        show: true,
        lineStyle: {
          color: '#ffffffcc',
        },
      },
    },
    yAxis: {
      name: '单位(m/min)',
      nameTextStyle: {
        color: '#fff',
        fontSize: 14,
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: '#ffffffcc',
        },
      },
      splitLine: {
        show: false,
      },
    },
  };

  // 默认初始是第一行
  const selectRowIndex = ref(0);
  const dataSource = ref([]);

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

  const propTypeArr = new Map([
    ['frontPresentValue', '前窗风速'],
    ['rearPresentValue', '后窗风速'],
  ]);

  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 controlType = ref(1);

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

  const initData = {
    deviceID: '',
    deviceType: '',
    strname: '',
    dataDh: '-', //压差
    dataDtestq: '-', //测试风量
    sourcePressure: '-', //气源压力
    dataDequivalarea: '-',
    netStatus: '0', //通信状态
    fault: '气源压力超限',
    forntArea: '0',
    rearArea: '0',
    frontRearDifference: '-',
    rearPresentValue: '-',
    maxarea: '',
  };

  // 监测数据
  const selectData = reactive(lodash.cloneDeep(initData));

  // https获取监测数据
  let timer: null | NodeJS.Timeout = null;
  const getMonitor = () => {
    if (Object.prototype.toString.call(timer) === '[object Null]') {
      timer = setTimeout(async () => {
        const data = await getDataSource()
        Object.assign(selectData, data);
        playAnimation(data, selectData.maxarea);
        addFmText(selectData);
        if(timer){
          timer = null;
        }
        getMonitor();
      }, 1000);
    }
  };

  const getDataSource = async() => {
    const res = await list({ devicetype: 'window', pagetype: 'normal' })
    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
    return data
  }


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

  // 切换检测数据
  const getSelectRow = (selectRow, index) => {
    selectRowIndex.value = index;
    loading.value = true;
    const baseData: any = deviceBaseList.value.find((baseData: any) => baseData.id === selectRow.deviceID);
    Object.assign(selectData, initData, selectRow, baseData);

    const type = selectRowIndex.value > 6 ? 'doubleWindow': 'singleWindow'
    setModelType(type).then(() => {
      addFmText(selectData);
      playAnimation(selectRow, baseData.maxarea, true);
      loading.value = false;
    })
  };

  // 判断前后窗的面积是否发生改变，如果改变则开启动画
  const playAnimation = (data, maxarea, isFirst = false) => {
    rotationParam.frontDeg0 = 90 / maxarea * Number(isFirst ? 0 : selectData.forntArea);
    rotationParam.backDeg0 = 90 / maxarea * Number(isFirst ? 0 : selectData.rearArea);
    rotationParam.frontDeg1 = 90 / maxarea * Number(data.forntArea) || 0;
    rotationParam.backDeg1 = 90 / maxarea *  Number(data.rearArea) || 0;
    if (!rotationParam.frontDeg1 && !rotationParam.backDeg1) {
      play(rotationParam, 0);
    } else {
      if (rotationParam.frontDeg0 >= 0 && rotationParam.frontDeg1 >= 0 && rotationParam.frontDeg0 !== rotationParam.frontDeg1) {
        setTimeout(() => {
          play(rotationParam, 1);
        }, 0);
      }
      if (rotationParam.backDeg0 >= 0 && rotationParam.backDeg1 >= 0 && rotationParam.backDeg0 !== rotationParam.backDeg1) {
        setTimeout(() => {
          play(rotationParam, 2);
        }, 0);
      }
    }
  };

  // 设置风窗面积
  const setArea = (flag) => {
    const data = {
      deviceid: selectData.deviceID,
      devicetype: selectData.deviceType,
      paramcode:  flag === 1 ? 'frontSetValue' : 'rearSetValue',
      value: windowAngle.value,
    };
    deviceControlApi(data)
      .then((res) => {
        if (res.success) {
        }
      })
  };

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

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

    getDeviceBaseList();

    document.body.addEventListener('mousedown', addPlayVideo, false);
  });

  onMounted(() => {
    loading.value = true;
    mountedThree(player1.value, player2.value).then(() => {
      nextTick(() => {
        loading.value = false;
        addFmText(selectData);
        getMonitor();
      });
    });
  });
  onUnmounted(() => {
    destroy();
    if(timer) {
      clearTimeout(timer)
      timer = undefined;
    }
  });
</script>
<style lang="less" scoped>
  .input-box {
    display: flex;
    align-items: center;
    .input-title {
      color: rgb(0, 255, 242);
      width: auto;
    }
    margin-right: 10px;
  }

  :deep(.jeecg-basic-table .ant-table-wrapper) {
    background-color: #ffffff00;
  }
  :deep(.ant-tabs-bar) {
    margin: 0;
  }
  :deep(.ant-table) {
    background-color: #ffffff00 !important;
    color: #fff;
  }
  :deep(.ant-table-header) {
    background-color: transparent;
    // height: 42px;
  }
  :deep(.ant-table-thead > tr > th) {
    background-color: transparent;
    border: none;
  }
  :deep(.ant-table-body > tr > th) {
    background-color: transparent;
    border: none;
  }
  :deep(.ant-table-body > tr > td) {
    border: none;
  }
  :deep(.ant-table-fixed-header > .ant-table-content > .ant-table-scroll > .ant-table-body) {
    background-color: #ffffff05;
    margin-top: 8px;
    &::-webkit-scrollbar {
      display: none;
    }
  }

  :deep(.jeecg-basic-table .ant-table-wrapper .ant-table-title) {
    padding: 0;
  }
  :deep(.jeecg-basic-table-row__striped td) {
    background-color: transparent;
  }
  :deep(.ant-table-tbody > tr:hover.ant-table-row > td) {
    background-color: #ffffff22;
  }
  :deep(.ant-table-tbody > tr:hover.ant-table-row > th) {
    background-color: #ffffff22;
  }
  :deep(.ant-table-thead > tr:hover.ant-table-row > td) {
    background-color: #ffffff22;
  }
  :deep(.ant-table-tbody > tr.ant-table-row-selected td) {
    background-color: #ffffff22;
  }
  :deep(.ant-table-tbody > tr > td) {
    border-color: #ffffff22;
  }
  :deep(.ant-table-thead > tr > th:hover) {
    background-color: transparent !important;
  }
  :deep(.ant-table-thead > tr > th) {
    color: #fff;
  }
  :deep(.ant-table-fixed-header .ant-table-scroll .ant-table-header) {
    background: #ffffff44;
    position: relative;
    z-index: 999;
    padding: 4px 0 !important;
    &::-webkit-scrollbar {
      display: none;
    }
  }
  :deep(.ant-tabs-nav) {
    color: #fff;
  }
</style>
