<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-center">
        <!-- <div class="input-box">
          <span class="input-title">风窗面积：</span>
          <a-input-number size="small" placeholder="0" :min="0" :max="90" :step="1" v-model:value="windowAngle" />
        </div> -->
        <div v-if="selectData.nwindownum == 2" class="row">
          <div class="button-box" @click="setArea(1)">设定前窗面积</div>
          <div class="button-box" @click="setArea(2)">设定后窗面积</div>
        </div>
        <div v-if="selectData.nwindownum == 1" class="row">
            <div class="button-box" @click="setArea(1)">设定风窗面积</div>
        </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">
      <a-tabs class="tabs-box" 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="风窗监测"
          >
            <template #filterCell="{ column, record }">
              <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>
              <div v-if="record.nwindownum == 1 && column.dataIndex === 'rearArea'">/</div>
            </template>
          </MonitorTable>
        </a-tab-pane>
        <a-tab-pane key="2" tab="实时曲线图" force-render>
          <div class="tab-item" v-if="activeKey === '2'">
            <DeviceEcharts
              chartsColumnsType="window_chart"
              xAxisPropType="strname"
              :dataSource="dataSource"
              height="100%"
              :chartsColumns="chartsColumns"
              :device-list-api="baseList"
              device-type="window"
            />
          </div>
        </a-tab-pane>
        <a-tab-pane key="3" tab="历史数据">
          <div class="tab-item">
            <HistoryTable columns-type="window_history" device-type="window" :device-list-api="baseList" designScope="window-history" />
          </div>
        </a-tab-pane>
        <a-tab-pane key="4" tab="报警历史">
          <div class="tab-item">
            <AlarmHistoryTable columns-type="alarm_history" device-type="window" :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="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>
  <HandleModal :modal-is-show="modalIsShow" :modal-title="modalTitle" :modal-type="modalType" @handle-ok="handleOK" @handle-cancel="handleCancel" />
</template>

<script setup lang="ts">
  import { message } from 'ant-design-vue';
  import DeviceEcharts from '../comment/DeviceEcharts.vue';
  import { onBeforeMount, ref, onMounted, onUnmounted, reactive, toRaw } 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 { initWebSocket, getRecordList } from '/@/hooks/web/useVentWebSocket';
  import { mountedThree, destroy, addFmText, play, setModelType } from './window.threejs';
  import { list, getTableList } from './window.api';
  import { list as baseList } from '../../deviceManager/windWindowTabel/ventanalyWindow.api';
  import { chartsColumns } from './window.data';
  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 modalIsShow = ref<boolean>(false); // 是否显示模态框
  const modalTitle = ref(''); // 模态框标题显示内容，根据设备操作类型决定
  const modalType = ref(''); // 模态框内容显示类型，设备操作类型

  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 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 flvURL1 = () => {
    // return `https://sf1-hscdn-tos.pstatp.com/obj/media-fe/xgplayer_doc_video/flv/xgplayer-demo-360p.flv`;
    return ''
  };
  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: '',
    nwindownum: 0
  };

  // 监测数据
  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(selectData, 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) => {
    if (!selectRow) return;
    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 = selectData.nwindownum == 1 ? 'singleWindow' : 'doubleWindow';
    setModelType(type).then(() => {
      addFmText(selectData);
      playAnimation(selectRow, baseData.maxarea, true);
      loading.value = false;
    });
  };

  // 判断前后窗的面积是否发生改变，如果改变则开启动画
  const playAnimation = (data, maxarea = 90, isFirst = false) => {
    maxarea = 90
    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 (isFirst) {
      console.log('最大面积---->', maxarea, '前窗实际面积---->', selectData.forntArea, '后窗实际面积---->', selectData.rearArea, '计算的值---->', rotationParam);
    }

    if (!rotationParam.frontDeg1 && !rotationParam.backDeg1) {
      // 当返回值有误时默认关闭
      play(rotationParam, 0);
    } else {
      if (data.nwindownum == 1 || data.nwindownum == 2) {
        setTimeout(() => {
          play(rotationParam, 1);
        }, 0);
      }
      if (data.nwindownum == 2) {
        setTimeout(() => {
          play(rotationParam, 2);
        }, 0);
      }
    }
  };

  // 设置风窗面积
  const setArea = (flag) => {
    if(selectData.nwindownum == 2){
      modalTitle.value = flag === 1 ? '设定前窗面积' : '设定后窗面积';
    }else {
      modalTitle.value = '设定风窗面积'
    }
    
    modalType.value = flag+'';
    modalIsShow.value = true;
  };

  const handleOK = (passWord, handlerState, windowAngleNum) => {
    windowAngle.value = windowAngleNum;
    if (passWord !== '123456') {
      message.warning('密码不正确，请重新输入');
      return;
    }
    const data = {
      deviceid: selectData.deviceID,
      devicetype: selectData.deviceType,
      paramcode: handlerState == 1 ? 'frontSetValue' : 'rearSetValue',
      value: windowAngle.value,
    };
    deviceControlApi(data)
      .then((res) => {
        if (res.success) {
        }
      })
      .finally(() => {
        handleCancel();
      });
  };

  const handleCancel = () => {
    modalIsShow.value = false;
    modalTitle.value = '';
    modalType.value = '';
  };

  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();
  });

  onMounted(() => {
    loading.value = true;
    mountedThree(player1.value, player2.value).then(async () => {
      // await setModelType('singleWindow');
      loading.value = false;
      addFmText(selectData);
      getMonitor();
    });
    document.body.addEventListener('mousedown', addPlayVideo, false);
  });
  onUnmounted(() => {
    destroy();
    if (timer) {
      clearTimeout(timer);
      timer = undefined;
    }
  });
</script>
<style lang="less" scoped>
  @import '/@/design/vent/modal.less';
  @ventSpace: zxm;

  :deep(.@{ventSpace}-tabs-tabpane-active) {
    overflow: auto;
  }
  .input-box {
    display: flex;
    align-items: center;
    padding-left: 10px;
    .input-title {
      color: #73e8fe;
      width: auto;
    }
    .@{ventSpace}-input-number {
      border-color: #ffffff88 !important;
    }
    margin-right: 10px;
  }
</style>
